Blockchain using JavaScript | Try my React CodeSandbox for a quick demo
Blockchain is a technology to record information in a way that makes it difficult to perform any malicious data alterations. As the data cannot be modified, Blockchain is proven useful for many healthcare and banking applications. At the core of the Blockchain, is a digital ledger that is duplicated and distributed across all the systems in the chain.
Block:
A block contains all the data and the hash values i.e. the blocks form the actual pages of the digital ledger. The first block in the blockchain is called the genesis block, which starts the chain and sets the foundation for the following blocks. Every block will have at least 3 parts:
- Data: Any data that the block has to store. For instance, transactions in a banking system.
- Hash: Hash is computed using the data, previous hash, and nonce. A nonce is an abbreviation for "number only used once", which is a number added to a hashed or encrypted block in a blockchain that, when rehashed, meets the difficulty level restrictions.
- Previous Hash: A chain is formed by adding the hash of the previous block to the current block. Adding hash of the previous block ensures that any change to the preceding block will result in a hash mismatch thus, preventing any data alteration.
Proof of Work:
Proof of work is a piece of data that is difficult to produce but easy to verify. It is performed to prevent any particular user from cheating the storage mechanism by recomputing all hash values as computers are capable of super-fast calculations. Such low-probabilistic data involves lots of trial and error until a correct value is reached.
Mining:
Coin miners receive crypto coins as a reward for completing blocks of verified transactions, which are added to the blockchain. In other words, miners have to perform the proof of work and produce the right value to receive crypto coins. Below is the code snippet that performs mining in our demo application:
import generateHash from "./generateHash"; const performMining = ( sender: string, recipient: string, coins: number, prevHash: string, proofOfWork: number ) => { let nonce = 0; let blockObject = { sender, recipient, coins, prevHash, nonce }; let hash = generateHash(JSON.stringify(blockObject)); while (hash.substring(0, proofOfWork) !== Array(proofOfWork 1).join("0")) { nonce = 1; blockObject = { ...blockObject, nonce }; hash = generateHash(JSON.stringify(blockObject)); } return hash; }; export default performMining;
In the above snippet, notice how we change the nonce value to meet the difficulty restrictions.
Screenshots:
React CodeSandbox:
GitHub Repo:
References:
Youtube Channel: Simply Explained (https://www.youtube.com/savjee)