Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

19BCP096 HashPointers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Blockchain Technology Assignment:

Create Blocks with all the parameters and Link them with
Hash Pointers

Name: Preet Patel


Roll No: 19BCP096

What are Hash Pointers?

-
- Points to the where the data is stored and along with it, cryptographic hash of the data
is also stored.
- They are different from memory pointers as they don’t relate/connect blocks using
memory address, but instead do so by using hashes of the block.
- Every block except the Genesis block has a Hash Pointer, that is the hash of the
previous block.
- This enables the blocks to be chained/linked together.
- One can traverse the chain backwards all the way to the first block because of the
hash pointers.
- It’s major security benefit is Integrity.
o If one alters the data of a block, it’s hash changes.
o This changes the hash of all the forward blocks and invalidates them.
JS Code:
const SHA256 = require("crypto-js/sha256");

class Block {

  constructor(id, data, prevHash = null) {

    this.id = id;

    this.timestamp = new Date();

    this.prevHash = prevHash;
    this.nounce = this.chooseNounce();

    this.hash = this.blockHash(this.nounce);

  }

  blockHash(nounce) {

    return SHA256(

      this.id + nounce + this.timestamp + this.data + this.prevHash

    ).toString();

  }

  chooseNounce() {

    for (var nounce = 0; nounce < 10000; nounce++) {

      //If no value satisfies the condition then nounce value stays undefined

      if (this.blockHash(nounce).slice(0, 2) === "00") {

        return nounce;

      }

    }

  }

class Blockchain {

  constructor() {

    this.chain = [this.createGenesisBlock()];

  }

  createGenesisBlock() {

    return new Block(1, "This is the Genesis Block");

  }

  lastBlock() {

    return this.chain[this.chain.length - 1];

  }
  insertBlock(id, data) {

    this.chain.push(new Block(id, data, this.lastBlock().hash));

  }

let batChain = new Blockchain();

batChain.insertBlock(2, "This is the Third Block");

batChain.insertBlock(3, "This is the Second Block");

console.log(batChain);

- Class Block
o Constructor
 id = Block Id
 timestamp = Block creation time
 prevhash = Hash of the previous block
 nounce = Puzzle solving variable
 hash = Hash of the block
o Functions
 blockHash(nounce)
 Returns block of the hash
 chooseNounce()
 Returns a nounce value for which the first two values of the
hash are zeroes.
- Class Blockchain
o Constructor
 A list with genesis block gets created
o Functions
 createGenesisBlock()
 Returns a block with fixed value
 lastBlock()
 Returns the last block/element of the chain/list
 insertBlock(id,data)
 Appends a new block into the chain
Output:

You might also like