Blockchain consists of a block by a chain of blocks linked together

One can think of blockchain as a distributed ledger that everyone can trust

 

Block block

A block can be roughly divided into three parts:

  • data
  • Hash – The hash of the block is the human fingerprint
  • Pre-block hash – In addition to the hash of its own block, the hash of the previous block is stored

As soon as the data is changed, the hash value changes, so that people can detect the change in the data through the hash value.

The first Block of a blockchain has no pre-hash value and can be called a Genesis Block.

Yes, blockchain looks a lot like a linked list in that way

In order to keep blocks from being tampered with, blockchain introduces a Proof of Work(POW) Proof of Work mechanism

Blockchain also introduces peer-to-peer (P2P) networks that form distributed storage

Once a block needs to be added, all the people in the P2P network need to reach a consensus before the block can be added.

Blockchain tamper-proof does not mean that data cannot be tampered with, but that the cost of doing so becomes extremely high.

 

Hash Function

F of x is equal to y.

  • Given x, it’s easy to find y is equal to lambda
  • Given y, it’s hard to find x ==

For example, x^18 + x^5 + x^0.5 + x – 5 = y

We can try to guess the numbers. The faster we WORK, the faster we can theoretically get a resultCopy the code

crypto-js

The purpose of the Crypto module is to provide universal encryption and hashing algorithms. It’s not impossible to do this in pure JavaScript code, but it’s very slow. Nodejs implements these algorithms in C/C++ and exposes them as JavaScript interfaces through the CYPTO module, which is easy to use and fast to run.

Crypto-js installation download and use

 

  • Test hash code:
const sha256 = require("crypto-js/sha256");

console.log(sha256('hello').toString());
console.log(sha256('world').toString());
Copy the code

Test result: For different input, even a very small change, the output is different

The result is the hash value

For the same input, the output is the same.

 

  • Example: I now need to get a hash value that starts with 0. Please tell me what X is
function proofOfWork() {
    let data = "hello world";
    let x = 1;
    while (true) {
      if(sha256(data + x).toString()[0]! = ="0") {
        x = x + 1;
      } else {
        console.log(sha256(data + x).toString());
        console.log(x);
        break;
      }
    }
  }
proofOfWork();
Copy the code

Results:

 

  • Example: Now you need to get a hash with the first four bits being zeros. Please tell me what X is
function proofOfWork() {
    let data = "hello world";
    let x = 1;
    while (true) {
      if (
        sha256(data + x).toString()
          // You can adjust the length of the string to control the difficulty. Try it yourself.
          // You can implement this function in your preferred language.
          // This function is really not complicated.
          .substring(0.4)! = ="0000"
      ) {
        x = x + 1;
      } else {
        console.log(sha256(data + x).toString());
        console.log(x);
        break;
      }
    }
  }
  proofOfWork();
Copy the code

Results:

 

Class that creates a block

 const sha256 = require("crypto-js/sha256");

/** block * data * hash of previous block * own hash - calculated from information stored in the block (data + hash of previous block) */
// Write a block class
 class Block{
  constructor(data, previousHash) {
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.computeHash()
  }

  computeHash(){
    return sha256(this.data + this.previousHash).toString()
  }
 }

 const block = new Block("Transfer 10 yuan"."KLOP");
 console.log(block)
Copy the code

After running:

 

Write a chain class

class Block{
  constructor(data, previousHash) {
    this.data = data;
    this.previousHash = previousHash;
    this.hash = this.computeHash()
  }

  computeHash(){
    return sha256(this.data + this.previousHash).toString()
  }
 }

// const block = new block (" transfer 10 yuan ","KLOP");
// console.log(block)
class Chain {
  constructor(){
    this.chain = [this.bigBang()];
  }

  bigBang(){
    // Define an ancestor block
    const genesisBlock = new Block("I am the ancestor block"."");
    returngenesisBlock; }}const chain = new Chain();
console.log(chain);
Copy the code

Output a chain with an ancestor block

 

Add a block to the blockchain

class Chain {
  constructor(){
    this.chain = [this.bigBang()];
  }

  bigBang(){
    // Define an ancestor block
    const genesisBlock = new Block("I am the ancestor block"."");
    return genesisBlock;
  }
  // Find the hash of the most recent block
  getLatestBlock(){
    return this.chain[this.chain.length - 1];
  }
  // Add a block to the blockchain
  addBlocktoChain(newBlock){
    // Find the hash of the most recent block
    // This hash is the previousHash of the new block
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.computeHash();
    this.chain.push(newBlock); }}const chain = new Chain();
const block1 = new Block("Transfer 10 yuan"."");

chain.addBlocktoChain(block1);
console.log(chain);
Copy the code

 

Verify that data in the blockchain has not been tampered with

class Chain {
  constructor(){
    this.chain = [this.bigBang()];
  }

  bigBang(){
    // Define an ancestor block
    const genesisBlock = new Block("I am the ancestor block"."");
    return genesisBlock;
  }
  // Find the hash of the most recent block
  getLatestBlock(){
    return this.chain[this.chain.length - 1];
  }
  // Add a block to the blockchain
  addBlocktoChain(newBlock){
    // Find the hash of the most recent block
    // This hash is the previousHash of the new block
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.computeHash();
    this.chain.push(newBlock);
  }

  // Verify that the current blockchain is valid
  // Whether the current data has been tampered with
  // We verify that the previousHash of the block is equal to the hash of the previous block
  validateChain() {
    if (this.chain.length === 1) {
      if (this.chain[0].hash ! = =this.chain[0].computeHash()) {
        return false;
      }
      return true;
    }
    // this.chain[1] is the second block
    // We start with the second block
    // Validate to the last block this.chain.length-1
    for (let i = 1; i <= this.chain.length - 1; i++) {
      const blockToValidate = this.chain[i];
      // Whether the current data has been tampered with
      if(blockToValidate.hash ! == blockToValidate.computeHash()) {console.log("Data tampering");
        return false;
      }
      // We verify that the previousHash of the block is equal to the hash of the previous block
      const previousBlock = this.chain[i - 1];
      if(blockToValidate.previousHash ! == previousBlock.hash) {console.log("The link between front and back blocks is broken");
        return false; }}return true; }}const chain = new Chain();

const block1 = new Block("Transfer 10 yuan"."");
const block2 = new Block("Transfer 20 yuan"."");
const block3 = new Block("Transfer 30 yuan"."");
const block4 = new Block("Transfer 40 yuan"."");

chain.addBlocktoChain(block1);
chain.addBlocktoChain(block2);
chain.addBlocktoChain(block3);
chain.addBlocktoChain(block4);

// Try to tamper with the blockchain
chain.chain[1].data = "Transfer a hundred tens.";
console.log(chain);
console.log(chain.validateChain())
Copy the code

 

Source of learning

www.bilibili.com/video/av783…

 

 

 

 

 

Learn together and make progress together. If there are any mistakes, please comment