https://grokonez.com/node-js/how-to-build-consensus-algorithm-blockchain-network-javascript-tutorial
How to build Consensus Algorithm for Blockchain Network in Javascript
During broadcasting Transactions over our Blockchain network, a certain node may not receive a piece of information, or even there is a bad actor who sent out false information or created fraudulent transactions and broadcasts them to the whole network, convinces everybody that they are legitimate transactions. So, the Consensus Algorithm provides us a way to compare one Node to all the other Nodes inside of the network to confirm that it has the correct data. In this tutorial, we're gonna create a Consensus Algorithm that implements the Longest Chain rule.
Previous Post: How to Synchronize Blockchain Network in JavaScript
Next Post: How to explore Data inside of Blockchain Network in Javascript
Consensus Algorithm
Longest Chain rule
This rule simply compares the chain of the chosen Node with all the other chains inside of our Blockchain network.
If one of the other chains has longer length than the current chain, we simply replace the chain of the Node we are on with the longest chain in the network.
Why we use Longest Chain rule?
The longest chain has the most Blocks in it and each of those Blocks was mined by using Proof of Work. We can assume that the whole network contributed to the longest chain because of how much work went into that chain.
Implement Longest Chain rule
Validate chain
This method validates a Blockchain by comparing all of the hashes of all of the Blocks inside of the chain.
class Blockchain {
...
isChainValid(blockchain) {
// 1- validate Genesis Block
// 2- forEach block in chain
// 2.1 validate block Hash
// 2.2 compare Hash with previous block Hash
}
}
Consensus Endpoint
We add an endpoint GET /consensus
to our API. It will:
- make a request to every Node inside of our Blockchain network to get their copies of the Blockchain
- find the longest chain by comparing current chain with these chains
- use
isChainValid()
function to check if the longest chain found in previous step is valid - if all things are validated, assign chain & transactions from the longest chain to this Blockchain
More at:
https://grokonez.com/node-js/how-to-build-consensus-algorithm-blockchain-network-javascript-tutorial
How to build Consensus Algorithm for Blockchain Network in Javascript
Top comments (0)