The Block Class

The idea

Our block class is designed to be a simple and easy to understand class that can be used to create and manage blocks in our blockchain.

To start we need to import the crypto-js library and the Transaction class (don't worry about it for now, we'll cover it later in the Wallet Class page).

The constructor

Now we can start coding the class, first we define the properties of the class for type safety. Then, inside the constructor we check if the number of transactions is valid (we can't have more than 10 transactions per block). After that, we initialize the properties of the class.

index

to calculate positon in the chain

timestamp

inserted when transaction is done

transactions

data of the Block

previousHash

hash value of the prev. Block

hash

hash value of the block

nonce

used by the mineBlock() to find the correct hash to mine the block (and so to confirm it)

📄main.ts
1import { SHA256 } from 'crypto-js';
2import { Transaction } from './transaction';
3
4export class Block {
5  index: number;
6  timestamp: string;
7  transactions: Transaction[];
8  previousHash: string;
9  hash: string;
10  nonce: number;
11  fee: number;
12
13  constructor(timestamp: string, transactions: Transaction[]) {
14    // check if the number of transactions is valid
15    if (transactions.length > 10) {
16      throw new Error("Each block can contain a maximum of 10 transactions.");
17    }
18    this.index = 0;
19    this.timestamp = timestamp;
20    this.transactions = transactions;
21    this.previousHash = "0";
22    this.hash = this.calculateHash();
23    this.nonce = 0;
24    this.fee = 0;
25  }
26}

The calculateHash() method

This method is used to calculate the hash of the block. Using the crypto-js library we can create a joined string of all the properties of the block. Finally we need to return the hash of the string.

📄main.ts
1// calculate the hash of the block
2  calculateHash() {
3    return SHA256(
4      this.index +
5      this.previousHash +
6      this.timestamp +
7      JSON.stringify(this.transactions) +
8      this.nonce
9    ).toString();
10  }

The mineBlock() method

This method is used to mine the block. First we need to create a loop that will try to find a hash that starts with the correct number of zeros. Once we find the correct hash, we can return the block.

📄main.ts
1// mine the block
2  mineBlock(difficulty: number) {
3    // calculate the target hash
4    const target = Array(difficulty + 1).join("0"); // e.g. "0000" if difficulty is 4
5    // mine the block
6    while (this.hash.substring(0, difficulty) !== target) {
7      this.nonce++;
8      this.hash = this.calculateHash(); // update the hash until a valid one is found
9    }
10  }