英文原文:Lauri Hartikka
區(qū)塊鏈的基礎(chǔ)概念很簡(jiǎn)單:一個(gè)分布式數(shù)據(jù)庫(kù),存儲(chǔ)一個(gè)不斷加長(zhǎng)的 list,list 中包含著許多有序的記錄。然而,在通常情況下,當(dāng)我們談到區(qū)塊鏈的時(shí)候也會(huì)談起使用區(qū)塊鏈來(lái)解決的問(wèn)題,這兩者很容易混淆。像流行的比特幣和以太坊這樣基于區(qū)塊鏈的項(xiàng)目就是這樣。“區(qū)塊鏈”這個(gè)術(shù)語(yǔ)通常和像交易、智能合約、加密貨幣這樣的概念緊緊聯(lián)系在一起。

這就令理解區(qū)塊鏈變得不必要得復(fù)雜起來(lái),特別是當(dāng)你想理解源碼的時(shí)候。下面我將通過(guò) 200 行 JS 實(shí)現(xiàn)的超級(jí)簡(jiǎn)單的區(qū)塊鏈來(lái)幫助大家理解它,我給這段代碼起名為 NaiveChain。
塊結(jié)構(gòu)
第一個(gè)邏輯步驟是決定塊結(jié)構(gòu)。為了保證事情盡可能的簡(jiǎn)單,我們只選擇最必要的部分:index(下標(biāo))、timestamp(時(shí)間戳)、data(數(shù)據(jù))、hash(哈希值)和 previous hash(前置哈希值)。

這個(gè)塊中必須能找到前一個(gè)塊的哈希值,以此來(lái)保證整條鏈的完整性。
class Block {
constructor(index, previousHash, timestamp, data, hash) {
this.index = index;
this.previousHash = previousHash.toString();
this.timestamp = timest
this.data = data;
this.hash = hash.toString();
}
}
塊哈希
為了保存完整的數(shù)據(jù),必須哈希區(qū)塊。SHA-256會(huì)對(duì)塊的內(nèi)容進(jìn)行加密,記錄這個(gè)值應(yīng)該和“挖礦”毫無(wú)關(guān)系,因?yàn)檫@里不需要解決工作量證明的問(wèn)題。
var calculateHash = (index, previousHash, timestamp, data) => {
return CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
};
塊的生成
要生成一個(gè)塊,必須知道前一個(gè)塊的哈希值,然后創(chuàng)造其余所需的內(nèi)容(= index, hash, data and timestamp)。塊的data部分是由終端用戶所提供的。
var generateNextBlock = (blockData) => {
var previousBlock = getLatestBlock();
var nextIndex = previousBlock.index + 1;
var nextTimestamp = new Date().getTime() / 1000;
var nextHash = calculateHash(nextIndex, previousBlock.hash, nextTimestamp, blockData);
return new Block(nextIndex, previousBlock.hash, nextTimestamp, blockData, nextHash);
};
塊的存儲(chǔ)
內(nèi)存中的Javascript數(shù)組被用于存儲(chǔ)區(qū)塊鏈。區(qū)塊鏈的第一個(gè)塊通常被稱為“起源塊”,是硬編碼的。
var getGenesisBlock = () => {
return new Block(0, "0", 1465154705, "my genesis block!!", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7");
};
var blockchain = [getGenesisBlock()];
確認(rèn)塊的完整性
在任何時(shí)候都必須能確認(rèn)一個(gè)區(qū)塊或者一整條鏈的區(qū)塊是否完整。在我們從其他節(jié)點(diǎn)接收到新的區(qū)塊,并需要決定接受或拒絕它們時(shí),這一點(diǎn)尤為重要。
var isValidNewBlock = (newBlock, previousBlock) => {
if (previousBlock.index + 1 !== newBlock.index) {
console.log('invalid index');
return false;
} else if (previousBlock.hash !== newBlock.previousHash) {
console.log('invalid previoushash');
return false;
} else if (calculateHashForBlock(newBlock) !== newBlock.hash) {
console.log('invalid hash: ' + calculateHashForBlock(newBlock) + ' ' + newBlock.hash);
return false;
}
return true;
};
選擇最長(zhǎng)的鏈
任何時(shí)候在鏈中都應(yīng)該只有一組明確的塊。萬(wàn)一沖突了(例如:兩個(gè)結(jié)點(diǎn)都生成了72號(hào)塊時(shí)),會(huì)選擇有最大數(shù)目的塊的鏈。

var replaceChain = (newBlocks) => {
if (isValidChain(newBlocks) newBlocks.length > blockchain.length) {
console.log('Received blockchain is valid. Replacing current blockchain with received blockchain');
blockchain = newBlocks;
broadcast(responseLatestMsg());
} else {
console.log('Received blockchain invalid');
}
};
與其他結(jié)點(diǎn)的通信
結(jié)點(diǎn)的本質(zhì)是和其他結(jié)點(diǎn)共享和同步區(qū)塊鏈,下面的規(guī)則能保證網(wǎng)絡(luò)同步。
當(dāng)一個(gè)結(jié)點(diǎn)生成一個(gè)新塊時(shí),它會(huì)在網(wǎng)絡(luò)上散布這個(gè)塊。
當(dāng)一個(gè)節(jié)點(diǎn)連接新peer時(shí),它會(huì)查詢最新的block。
當(dāng)一個(gè)結(jié)點(diǎn)遇到一個(gè)塊,其index大于當(dāng)前所有塊的index時(shí),它會(huì)添加這個(gè)塊到它當(dāng)前的鏈中,或者到整個(gè)區(qū)塊鏈中查詢這個(gè)塊。

如圖為當(dāng)節(jié)點(diǎn)遵循前文所述協(xié)議時(shí)會(huì)發(fā)生的一些典型通信場(chǎng)景
我沒(méi)有采用自動(dòng)發(fā)現(xiàn)peer的工具。peers的位置(URL)必須是手動(dòng)添加的。
結(jié)點(diǎn)控制
在某種程度上用戶必須能夠控制結(jié)點(diǎn)。這一點(diǎn)通過(guò)搭建一個(gè)HTTP服務(wù)器可以實(shí)現(xiàn)。
var initHttpServer = () => {
var app = express();
app.use(bodyParser.json());
app.get('/blocks', (req, res) => res.send(JSON.stringify(blockchain)));
app.post('/mineBlock', (req, res) => {
var newBlock = generateNextBlock(req.body.data);
addBlock(newBlock);
broadcast(responseLatestMsg());
console.log('block added: ' + JSON.stringify(newBlock));
res.send();
});
app.get('/peers', (req, res) => {
res.send(sockets.map(s => s._socket.remoteAddress + ':' + s._socket.remotePort));
});
app.post('/addPeer', (req, res) => {
connectToPeers([req.body.peer]);
res.send();
});
app.listen(http_port, () => console.log('Listening http on port: ' + http_port));
};
用戶可以用下面的方法和結(jié)點(diǎn)互動(dòng):
- 列出所有的塊
- 用用戶提供的內(nèi)容創(chuàng)建一個(gè)新的塊
- 列出或者新增peers
下面這個(gè)Curl的例子就是最直接的控制結(jié)點(diǎn)的方法:
#get all blocks from the node
curl http://localhost:3001/blocks
體系結(jié)構(gòu)
需要指出的是,節(jié)點(diǎn)實(shí)際上展現(xiàn)了兩個(gè)web服務(wù)器:一個(gè)(HTTP服務(wù)器)是讓用戶控制節(jié)點(diǎn),另一個(gè)(Websocket HTTP服務(wù)器)。

NaiveChain的主要組成部分
總結(jié)
創(chuàng)造 NaiveChain 的目的是為了示范和學(xué)習(xí),因?yàn)樗](méi)有“挖礦”算法(PoS of PoW),不能被用于公用網(wǎng)絡(luò),但是它實(shí)現(xiàn)了區(qū)塊鏈運(yùn)作的基本特性。
你可以在 Github 庫(kù)中查看更多的技術(shù)細(xì)節(jié)。 https://github.com/lhartikk/naivechain
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 用不到50行的Python代碼構(gòu)建最小的區(qū)塊鏈
- Python學(xué)習(xí)入門之區(qū)塊鏈詳解
- 你應(yīng)該知道的區(qū)塊鏈運(yùn)作7個(gè)核心技術(shù)
- 14張圖看懂什么是區(qū)塊鏈技術(shù)
- 利用swoole+redis實(shí)現(xiàn)股票和區(qū)塊鏈服務(wù)
- Python從零開(kāi)始創(chuàng)建區(qū)塊鏈