In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
How to use JS to build your own blockchain, for this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a simpler and easier way.
Preface
The blockchain is too complex, so let's talk about something simple. Using JS to build your own blockchain system, just a few lines of code can explain the underlying data structure of blockchain, POW mining ideas and trading process, etc. Of course, the real scene is far more complicated than that. The purpose of the editor is limited to let you have a preliminary understanding of the block chain.
Recognize the block chain
As the name implies, a blockchain is a chain connected by chunks, so the most basic data structure is Block. Each Block contains timestamp, data, hash, previousHash and other information. Where data is used to store data, and previousHash is the hash value of the previous block. The illustration is as follows:
Hash is the summary storage of chunk information. The advantage of hash is that any length of information can be mapped to a fixed-length string through hash, such as sha256:
Data structure of calculateHash () {return SHA256 (this.previousHash + this.timestamp + JSON.stringify (this.data)) .toString ();} Block
The most basic data structure of Block is as follows:
Class Block {constructor (timestamp, data, previousHash ='') {this.timestamp = timest this.data = data; this.previousHash = previousHash; / / the calculation of a pair of hash must be placed last to ensure that all data assignments are correct before calculating this.hash = this.calculateHash () } calculateHash () {return SHA256 (this.previousHash + this.timestamp + JSON.stringify (this.data)) .toString ();}} data structure of BlockChain
Multiple Block links form a BlockChain, which can obviously be represented by an array or linked list, such as:
Class BlockChain {constructor () {this.chain = [];}} Genesis Block
As the saying goes, everything begins with one. The first block of a block chain always needs to be created manually. The previousHash of this block is empty, such as:
CreateGenesisBlock () {return new Block ("2018-11-11 00:00:00", "Genesis block of simple chain", ");}
The construction method of block chain should also be changed to:
Class BlockChain {constructor () {this.chain = [this.createGenesisBlock ()];}} add blocks
For each new block added, it must be connected to the original block chain, namely:
Class BlockChain {getLatestBlock () {return this.chain [this.chain.length-1];} addBlock (newBlock) {/ / the previous hash value of the new chunk is the hash value of the last chunk in the existing chunk chain; newBlock.previousHash = this.getLatestBlock (). Hash; / / recalculate the hash value of the new chunk (because previousHash is specified) NewBlock.hash = newBlock.calculateHash (); / / add a new block to the chain; this.chain.push (newBlock);}.} check block chain
The core of the block chain data structure is to ensure that the front and rear links cannot be tampered with, but if someone does tamper with a block, how can we verify the discovery? The stupidest and most natural idea is to traverse all the situations and check them one by one, such as:
IsChainValid () {/ / traverses all chunks for (let I = 1; I < this.chain.length; iTunes +) {const currentBlock = this.chain [I]; const previousBlock = this.chain [I-1] / / recalculate the hash value of the current block. If it is found that the hash value does not match, the data in the block has been tampered with, and the hash value does not recalculate if (currentBlock.hash! = = currentBlock.calculateHash ()) {console.error ("hash not equal:" + JSON.stringify (currentBlock)); return false } / / determine whether the previousHash of the current block is really equal to the hash of the previous block. If not, the previous block has been tampered with. Although the hash value has been recalculated correctly, the hash value of the subsequent block has not been recalculated, resulting in the whole chain breaking if (currentBlock.previousHash! = = previousBlock.calculateHash) {console.error ("previous hash not right:" + JSON.stringify (currentBlock)). Return false;}} return true;} Just run it
Run up and have a look, that is:
Let simpleChain = new BlockChain (); simpleChain.addBlock (new Block ("2018-11-11 00:00:01", {amount: 10})); simpleChain.addBlock (new Block ("2018-11-11 00:00:02", {amount: 20})); console.log (JSON.stringify (simpleChain, null, 4)); console.log ("is the chain valid?" + simpleChain.isChainValid ())
The results are as follows:
Ali-186590cc4a7f:simple-chain shanyao$ node main_1.js {"chain": [{"timestamp": "2018-11-11 00:00:00", "data": "Genesis block of simple chain", "previousHash": "", "hash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89"} {"timestamp": "2018-11-11 00:00:01", "data": {"amount": 10}, "previousHash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89", "hash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529"}, {"timestamp": "2018-11-11 00:00:02" "data": {"amount": 20}, "previousHash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529", "hash": "274a7a13ed20118e8cb745654934a7e24a4d59333ba17dfbf5d4cfe0fa8a6e34"}]} is the chain valid? True
Notice that the previousHash and hash are indeed the previousHash of the current block pointing to the hash of the previous block.
Try tampering.
Is it true that the blockchain cannot be tampered with? Let's try tampering with the second block, such as:
Let simpleChain = new BlockChain (); simpleChain.addBlock (new Block ("2018-11-11 00:00:01", {amount: 10}); simpleChain.addBlock (new Block ("2018-11-11 00:00:02", {amount: 20})); console.log ("is the chain valid?" + simpleChain.isChainValid ()); / / change the data of the second block from 10 to 15simpleChain.chain [1] .data = {amount: 15} Console.log ("is the chain still valid?" + simpleChain.isChainValid ()); console.log (JSON.stringify (simpleChain, null, 4))
The results are as follows:
Ali-186590cc4a7f:simple-chain shanyao$ node main_1.js is the chain valid? Truehash not equal: {"timestamp": "2018-11-11 00:00:01", "data": {"amount": 15}, "previousHash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89", "hash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529"} is the chain still valid? False {"chain": [{"timestamp": "2018-11-11 00:00:00", "data": "Genesis block of simple chain", "previousHash": "", "hash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89"}, {"timestamp": "2018-11-11 00:00:01" "data": {"amount": 15}, "previousHash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89", "hash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529"}, {"timestamp": "2018-11-11 00:00:02", "data": {"amount": 20} "previousHash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529", "hash": "274a7a13ed20118e8cb745654934a7e24a4d59333ba17dfbf5d4cfe0fa8a6e34"]}
Obviously, after tampering with the data, the hash value is not recalculated, causing the hash value of the block to mismatch.
Try tampering again.
So, what if we were smart enough to recalculate the hash value after tampering?
Let simpleChain = new BlockChain (); simpleChain.addBlock (new Block ("2018-11-11 00:00:01", {amount: 10}); simpleChain.addBlock (new Block ("2018-11-11 00:00:02", {amount: 20})); console.log ("is the chain valid?" + simpleChain.isChainValid ()); / / recalculate the hash value simpleChain.chain [1] .data = {amount: 15} after tampering; simpleChain.chain [1] .hash = simpleChain.chain [1] .calculateHash () Console.log ("is the chain still valid?" + simpleChain.isChainValid ()); console.log (JSON.stringify (simpleChain, null, 4))
The results are as follows:
Ali-186590cc4a7f:simple-chain shanyao$ node main_1.js is the chain valid? Trueprevious hash not right: {"timestamp": "2018-11-11 00:00:02", "data": {"amount": 20}, "previousHash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529", "hash": "274a7a13ed20118e8cb745654934a7e24a4d59333ba17dfbf5d4cfe0fa8a6e34"} is the chain still valid? False {"chain": [{"timestamp": "2018-11-11 00:00:00", "data": "Genesis block of simple chain", "previousHash": "", "hash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89"}, {"timestamp": "2018-11-11 00:00:01" "data": {"amount": 15}, "previousHash": "fd56967ff621a4090ff71ce88fdd456547d1c92d2e93766b7e8791f7a5f91f89", "hash": "74d139274fb692495b7c805dd5822faa0c5b5e6058b6beef96e87e18ab83a6b1"}, {"timestamp": "2018-11-11 00:00:02", "data": {"amount": 20} "previousHash": "150b196268a0152e9f0e719ac131a722472a809f49bd507965029a78c7400529", "hash": "274a7a13ed20118e8cb745654934a7e24a4d59333ba17dfbf5d4cfe0fa8a6e34"]}
Obviously, the previousHash of the third block does not point to the hash of the second block.
Is it really impossible to tamper with it?
In fact, it is not. If we were smarter and recalculated the hash value of subsequent blocks, wouldn't it be OK? This is true, such as:
Let simpleChain = new BlockChain (); simpleChain.addBlock (new Block ("2018-11-11 00:00:01", {amount: 10}); simpleChain.addBlock (new Block ("2018-11-11 00:00:02", {amount: 20})); console.log ("is the chain valid?" + simpleChain.isChainValid ()); / / tampering with the second block simpleChain.chain [1] .data = {amount: 15}; simpleChain.chain [1] .hash = simpleChain.chain [1] .calculateHash () / / and recalculate the third block simpleChain.chain [2] .previousHash = simpleChain.chain [1] .hash; simpleChain.chain [2] .hash = simpleChain.chain [2] .calculateHash (); console.log ("is the chain still valid?" + simpleChain.isChainValid ()) Console.log (JSON.stringify (simpleChain, null, 4) this is the answer to the question about how to build your own blockchain with JS. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.