首先,本人也是一周后在学习区块链的路上,学习中将自己看过的有用的信息就放在自己的GitHub上,方便自己复习好找
本人首页:www.github.com/cancerts/study-blockchain-referrence 【点击】
里面有我25本(写博客时)区块链领域比较热门的书籍,有PDF、mobi三种格式的,懂区块链的自己取
Index | Timestamp | Hash | Previous Hash | Data | Nonce |
区块号 | 时间戳 | sh256 | 前一个区块的hash | 输入的内容 | 随机值 |
代码:
class Block {
constructor (index, previousHash, timestamp, data, hash, nonce) {
this.index = index;
this.previousHash = previousHash;
this.timestamp = timestamp;
this.data = data;
this.hash = hash;
this.nonce = nonce;
}
get genesis() {
new Block(
0,
"0",
1508270000000,
"Welcome to Blockchain",
"000dc75a315c77a1f9c98fb6247d03dd18ac52632d7dc6a9920261d8109b37cf",
604
);
}
}
module.exports = Block;
// cosnt Block = reuqire("./Block.js");
// class Blockchain {
// constructor() {
// this.blockchain = [Block.genesis()];
this.difficulty = 20;
// }
// get() { ... }
// get latestBlock() { ... }
isValidHashDifficulty(hash) {
for (var i = 0; i < hash.length; i++) {
if (hash[i] !== "0") {
break;
};
}
return i >= this.difficulty;
}
// };
// module.exports = Blockchain;
// const Block = require("./Block.js");
const crypto = require("crypto");
// class Blockchain {
// constructor() { ... }
// get() { ... }
// get latestBlock() { ... }
// isValidHashDifficulty(hash) { ... }
calculateHashForBlock(block) {
const { index, previousHash, timestamp, transactions, nonce } = block;
return this.calculateHash(
index,
previousHash,
timestamp,
transactions,
nonce
);
}
calculateHash(index, previousHash, timestamp, data, nonce) {
return crypto
.createHash("sha256") // SHA256 Hash Function
.update(index + previousHash + timestamp + data + nonce)
.digest("hex");
}
// };
// module.exports = Blockchain;
// const Block = require("./Block.js");
// const crypto = require("crypto");
// class Blockchain {
// constructor() { ... }
// get() { ... }
// get latestBlock() { ... }
// isValidHashDifficulty(hash) { ... }
// calculateHashForBlock(block) { ... }
// calculateHash(...) { ... }
mine(data) {
const newBlock = this.generateNextBlock(data);
try {
this.addBlock(newBlock);
} catch (err) {
throw err;
};
}
// };
// module.exports = Blockchain;
// const Block = require("./Block.js");
// const crypto = require("crypto");
// class Blockchain {
// constructor() { ... }
// get() { ... }
// get latestBlock() { ... }
// isValidHashDifficulty(hash) { ... }
// calculateHashForBlock(block) { ... }
// calculateHash(...) { ... }
// mine(data) { ... }
generateNextBlock(data) {
const nextIndex = this.latestBlock.index + 1;
const previousHash = this.latestBlock.hash;
let timestamp = new Date().getTime();
let nonce = 0;
let nextHash = this.calculateHash(
nextIndex,
previousHash,
timestamp,
data,
nonce
);
while (!this.isValidHashDifficulty(nextHash)) {
nonce = nonce + 1;
timestamp = new Date().getTime();
nextHash = this.calculateHash(
nextIndex,
previousHash,
timestamp,
data,
nonce
);
}
const nextBlock = new Block(
nextIndex,
previousBlock.hash,
nextTimestamp,
data,
nextHash,
nonce
);
return nextBlock;
}
// };
// module.exports = Blockchain;
// const Block = require("./Block.js");
// const crypto = require("crypto");
// class Blockchain {
// constructor() { ... }
// get() { ... }
// get latestBlock() { ... }
// isValidHashDifficulty(hash) { ... }
// calculateHashForBlock(block) { ... }
// calculateHash(...) { ... }
// mine(data) { ... }
// generateNextBlock(data) { ... }
// addBlock(newBlock) { ... }
isValidNextBlock(nextBlock, previousBlock) {
const nextBlockHash = this.calculateHashForBlock(nextBlock);
if (previousBlock.index + 1 !== nextBlock.index) {
return false;
} else if (previousBlock.hash !== nextBlock.previousHash) {
return false;
} else if (nextBlockHash !== nextBlock.hash) {
return false;
} else if (!this.isValidHashDifficulty(nextBlockHash)) {
return false;
} else {
return true;
}
}
// };
// module.exports = Blockchain;
const wrtc = require('wrtc');
const Exchange = require('peer-exchange');
const p2p = new Exchange("Blockchain Demo 2.0", { wrtc: wrtc });
const net = require("net");
class PeerToPeer {
constructor(blockchain) {
this.peers = [];
this.blockchain = blockchain;
}
startServer(port) {
const server = net
.createServer(socket =>
p2p.accept(socket, (err, conn) => {
if (err) {
throw err;
} else {
this.initConnection.call(this, conn);
}
})
)
.listen(port);
}
}
module.exports = PeerToPeer;
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// class PeerToPeer {
// constructor(blockchain) { ... }
// startServer(port) { ... }
discoverPeers() {
p2p.getNewPeer((err, conn) => {
if (err) {
throw err;
} else {
this.initConnection.call(this, conn);
}
});
}
// }
// module.exports = PeerToPeer;
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// class PeerToPeer {
// constructor(blockchain) { ... }
// startServer(port) { ... }
// discoverPeers() { ... }
connectToPeer(host, port) {
const socket = net.connect(port, host, () =>
p2p.connect(socket, (err, conn) => {
if (err) {
throw err;
} else {
this.initConnection.call(this, conn);
}
})
);
}
closeConnection() {
p2p.close(err => {
throw err;
})
}
// }
// module.exports = PeerToPeer;
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
const messageType = {
REQUEST_LATEST_BLOCK: 0,
RECEIVE_LATEST_BLOCK: 1,
REQUEST_BLOCKCHAIN: 2,
RECEIVE_BLOCKCHAIN: 3,
};
const {
REQUEST_LATEST_BLOCK,
RECEIVE_LATEST_BLOCK,
REQUEST_BLOCKCHAIN,
RECEIVE_BLOCKCHAIN,
REQUEST_TRANSACTIONS,
RECEIVE_TRANSACTIONS
} = messageType;
// class PeerToPeer { ... }
// module.exports = PeerToPeer;
class Messages {
static getLatestBlock() {
return {
type: REQUEST_LATEST_BLOCK
};
}
static sendLatestBlock(block) {
return {
type: RECEIVE_LATEST_BLOCK,
data: block
};
}
static getBlockchain() {
return {
type: REQUEST_BLOCKCHAIN
};
}
static sendBlockchain(blockchain) {
return {
type: RECEIVE_BLOCKCHAIN,
data: blockchain
};
}
}
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// const messageType = { ... };
// const { ... } = messageType;
// class PeerToPeer {
// constructor(blockchain) { ... }
// startServer(port) { ... }
// discoverPeers() { ... }
// connectToPeer(host, port) { ... }
// closeConnection() { ... }
broadcastLatest() {
this.broadcast(Messages.sendLatestBlock(this.blockchain.latestBlock));
}
broadcast(message) {
this.peers.forEach(peer => this.write(peer, message));
}
write(peer, message) {
peer.write(JSON.stringify(message));
}
initConnection(connection) {
this.peers.push(connection);
this.initMessageHandler(connection);
this.initErrorHandler(connection);
this.write(connection, Messages.getLatestBlock());
}
initMessageHandler(connection) {
connection.on("data", data => {
const message = JSON.parse(data.toString("utf8"));
this.handleMessage(connection, message);
});
}
initErrorHandler(connection) {
connection.on("error", err => {
throw err;
});
}
handleMessage(peer, message) {
switch (message.type) {
case REQUEST_LATEST_BLOCK:
this.write(peer, Messages.sendLatestBlock(this.blockchain.latestBlock));
break;
case REQUEST_BLOCKCHAIN:
this.write(peer, Messages.sendBlockchain(this.blockchain.get()));
break;
case RECEIVE_LATEST_BLOCK:
this.handleReceivedLatestBlock(message, peer);
break;
case RECEIVE_BLOCKCHAIN:
this.handleReceivedBlockchain(message);
break;
default:
throw "Received invalid message.";
}
}
// }
// module.exports = PeerToPeer;
// class Messages { ... }
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// const messageType = { ... };
// const { ... } = messageType;
// class PeerToPeer {
// constructor(blockchain) { ... }
// startServer(port) { ... }
// discoverPeers() { ... }
// connectToPeer(host, port) { ... }
// closeConnection() { ... }
// broadcastLatest() { ... }
// broadcast(message) { ... }
// write(peer, message) { ... }
// initConnection(connection) { ... }
// initMessageHandler(connection) { ... }
// initErrorHandler(connection) { ... }
// handleMessage(peer, message) { ... }
handleReceivedLatestBlock(message, peer) {
const receivedBlock = message.data;
const latestBlock = this.blockchain.latestBlock;
if (latestBlock.hash === receivedBlock.previousHash) {
try {
this.blockchain.addBlock(receivedBlock);
} catch(err) {
throw err;
}
} else if (receivedBlock.index > latestBlock.index) {
this.write(peer, Messages.getBlockchain());
} else {
// Do nothing.
}
}
// }
// module.exports = PeerToPeer;
// class Messages { ... }
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// const messageType = { ... };
// const { ... } = messageType;
// class PeerToPeer {
// constructor(blockchain) { ... }
// startServer(port) { ... }
// discoverPeers() { ... }
// connectToPeer(host, port) { ... }
// closeConnection() { ... }
// broadcastLatest() { ... }
// broadcast(message) { ... }
// write(peer, message) { ... }
// initConnection(connection) { ... }
// initMessageHandler(connection) { ... }
// initErrorHandler(connection) { ... }
// handleMessage(peer, message) { ... }
handleReceivedLatestBlock(message, peer) {
// if (latestBlock.hash === receivedBlock.previousHash) {
// ...
} else if (receivedBlock.index > latestBlock.index) {
this.write(peer, Messages.getBlockchain());
} else {
// Do nothing.
}
}
handleReceivedBlockchain(message) {
const receivedChain = message.data;
try {
this.blockchain.replaceChain(receivedChain);
} catch(err) {
throw err;
}
}
// }
// module.exports = PeerToPeer;
// class Messages { ... }
好了就说这么多吧,