Home > Web Front-end > JS Tutorial > body text

How to evaluate a blockchain implemented in JavaScript?

PHPz
Release: 2023-08-27 21:05:07
forward
954 people have browsed it

Blockchain is a blockchain containing information. In 2009, this technology was later adopted by Satoshi Nakamoto to create the digital cryptocurrency Bitcoin. This is completely open to anyone who wants to develop or analyze. One thing about this technology is that once certain data is recorded in the blockchain, changing it becomes very complicated. The following are some terms used for evaluation in blockchain programs.

  • Block

    - A block in the blockchain contains information such as data, hash value, and previous block hash value.

  • Data

    - This data completely depends on the type of block, for example cryptocurrencies have information such as who the transaction came from, who the transaction was to, and the transaction volume. Coins have been traded.

  • Hash

    - This is a unique string ID, just like Aadhar number, it can be used to locate the details of a person, just like this hash is used to identify blocks Details are the same. Once a block is created, its hash is created. Changing the block hash is easily identifiable. Once a block hash changes, it is no longer the same block.

  • Previous Hash

    - This is the hash of the previous block and is used to connect or create a chain of blocks.

  • In the above image, you can observe that the previous hash has the hash of the previous block. The first block is also called the genesis block because it cannot point to the previous block. If you change the hash, the next block with the previous hash will be invalid due to the change.

The package we will use is

crypto.js.

This is a JavaScript library that provides encryption algorithms and functions. It can be used to perform various cryptographic operations such as hashing, encryption, decryption, and key generation in a web browser or in a server-side JavaScript environment such as Node.js. This library is widely used in web applications to provide secure communication, data protection, and user authentication. For example, it can be used to encrypt sensitive data before sending it over the Internet, or to generate secure password hashes for user authentication.

Let us understand through a program that uses Crypto.JS library for hashing and proof of work.

There are two classes Block and Blockchain.

class Block{
   constructor(prev_hashValue, data){
      this.data=data;
      this.hash=this.calculateHash();
      this.prev_hashValue=prev_hashValue;
      this.time_stamp= new Date();
      this.pf_work=0;
   }
}
Copy after login

Block class has five attributes -

  • data

    - This will store the data in blocks.

  • hash

    - This will store the hash of the block by calling the calculateHash method.

  • prev_hashValue

    - This will store the hash value of the previous block.

  • time_stamp

    - The timestamp will contain the time the block was created.

  • pf_work

    - A number that is incremented during mining.

  • Block class contains two methods -
calculateHash(){
   return SHA256(this.pf_work + this.prev_hashValue + this.timestamp + JSON.stringify(this.data)).toString();
}
Copy after login

This function will calculate the hash value of the block by concatenating pf_work, prev_hashValue time_stamp and data and passing it to the

SHA256

hash function using the CryptoJS library.

mine(difficulty){
   while(!this.hash.startsWith("0".repeat(difficulty))){
      this.pf_work++;
      this.hash=this.calculateHash();
   }
}
Copy after login
This function uses proof of work to find hashes that start with a certain number of zeros. The number of zeros is determined by the difficulty parameter passed to this method. The pf_work attribute is incremented until a valid hash value is found.

class Blockchain{
   constructor(){
      let genesisBlock=new Block("0", {isGenesisBlock: true});
      this.chain=[genesisBlock];
   }
}
Copy after login

chain

- This is an array of Block objects that form a chain of blocks. The blockchain class has two methods -

addNewBlock(data){
   let lastBlock=this.chain[this.chain.length-1];
   let newBlock=new Block(lastBlock.hash, data);
   newBlock.mine(2); //find a hash for new block
   this.chain.push(newBlock);
}
Copy after login

This method creates a new Block object, the data in it is passed as a parameter, and mines are used to find a valid hash value and add it to the chain array.

isValid_hash(){
      for(let i=1; i<this.chain.length; i++){
      const currentBlock=this.chain[i];
      const previousBlock=this.chain[i-1];
      if(currentBlock.hash!=currentBlock.calculateHash()) return false;
      if(currentBlock.prev_hashValue!=previousBlock.hash) return false;
      }
      return true;
}
Copy after login

This method checks the validity of the blockchain by iterating through each block in the chain array and verifying that its hash properties match the calculated hash value.

let blockchain=new Blockchain();
blockchain.addNewBlock({
   from: "joe",
   to:"Juhi",
   amount: 100,
});
blockchain.addNewBlock({
   from: "martin",
   to: "Genny",
   amount: 150,
});
Copy after login

Here an object will be created using two blocks, which will have properties of the blockchain class.

This implementation can be used as a starting point for building more complex blockchain applications that require secure and immutable data storage. But it should be noted that this is only a basic implementation, and a fully functional blockchain system also requires many additional functions, such as transaction verification, consensus mechanisms, and security measures.

Example: Complete Code

Blockchain.js

const SHA256 = require('crypto-js/sha256');
class Block{
   constructor(prev_hashValue, data){
      this.data=data;
      this.hash=this.calculateHash();
      this.prev_hashValue=prev_hashValue;
      this.time_stamp= new Date();
      this.pf_work=0;
   }

   calculateHash(){
      return SHA256(this.pf_work + this.prev_hashValue + this.time_stamp + JSON.stringify(this.data)).toString();
   }

   mine(difficulty){
      while(!this.hash.startsWith("0".repeat(difficulty))){
         this.pf_work++;
         this.hash=this.calculateHash();
      }
   }
}

class Blockchain{
   constructor(){
      let genesisBlock=new Block("0", {isGenesisBlock: true});
      this.chain=[genesisBlock];
   }

   addNewBlock(data){
      let lastBlock=this.chain[this.chain.length-1];
      let newBlock=new Block(lastBlock.hash, data);
      newBlock.mine(2); //find a hash for new block
      this.chain.push(newBlock);
   }

   isValid_hash(){
      for(let i=1; i<this.chain.length; i++){
         const currentBlock=this.chain[i];
         const previousBlock=this.chain[i-1];
         if(currentBlock.hash!=currentBlock.calculateHash()) return false;
         if(currentBlock.prev_hashValue!=previousBlock.hash) return false;
      }
      return true;
   }
}
//test
let blockchain=new Blockchain();

blockchain.addNewBlock({
   from: "joe",
   to:"Juhi",
   amount: 100,
});

blockchain.addNewBlock({
   from: "martin",
   to: "Genny",
   amount: 150,
});

console.log(blockchain);
console.log("Blockchain is valid: "+blockchain.isValid_hash());
Copy after login
To compile this program, you must install node.js. Use this article (Node.js - Environment Setup) to install Node.js. Then use the following command to install the crypto.js library.

npm install crypto-js
Copy after login

Then compile the JavaScript program file. Here, the filename is blockchain.

node blockchain.js
Copy after login

Output

The above is the detailed content of How to evaluate a blockchain implemented in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!