Creating a Blockchain | Task

Ole Ersoy
Mar - 17  -  1 min

Scenario

We have created a Block implementation.

Now we want to create a Blockchain.

Approach

The method initializeChain() will create the genesis block and put it on the blockchain array.

The lastBlock method retrieves the most recent block added to the chain. We use this method to retrieve the current hash when creating a new block.

To create a new Block instance we can call createBlock().

We can then post (Add) this block to the chain using postBlock().

class BlockChain {
  index: number = 0;
  blockchain: Block[];
  constructor() {
    this.initializeChain();
  }
  initializeChain() {
    const block: Block = new Block(
      this.index,
      "02/21/2021",
      "Our first ever block",
      "Block 0"
    );
    this.blockchain = [block];
    this.index++;
  }
  lastBlock(): Block {
    return this.blockchain[this.blockchain.length - 1];
  }
  createBlock(timestamp: string, data: any): Block {
    const b = new Block(this.index, timestamp, data, this.lastBlock().hash);
    this.index++;
    return b;
  }
  postBlock(block: Block) {
    this.blockchain.push(block);
  }
}

Demo