Demystifying Blockchain: A Hive-Inspired Example with TypeScript

in HiveDevs5 months ago

Hive, a vibrant blockchain ecosystem, is renowned for its three-second block times, fostering rapid transaction processing and a thriving content creation space. To unravel the complexities of such an innovative system, let's embark on a journey through a TypeScript-based simulation that captures the essence of Hive's swift block creation process.

In the process, we'll learn how blockchains work in a simplified manner. Many of the features that you would find in a real blockchain like Hive are noticeably absent, we're just scraping the surface.

The Anatomy of a Hive Block

In the Hive network, each block is a bundle of transactions, each stamped with a timestamp and securely linked to its predecessor through cryptographic hashing. The TypeScript class below encapsulates the structure of a Hive block:

import crypto from 'crypto';

class Block {
  readonly timestamp: number;
  readonly transactions: any[];
  readonly previousHash: string;
  public hash: string;

  constructor(transactions: any[], previousHash: string = '') {
    this.timestamp = Date.now();
    this.transactions = transactions;
    this.previousHash = previousHash;
    this.hash = this.calculateHash();
  }

  calculateHash(): string {
    const str = this.previousHash + this.timestamp + JSON.stringify(this.transactions);
    return crypto.createHash('sha256').update(str).digest('hex');
  }
}

Here, the calculateHash function is the digital fingerprint of the block, a SHA-256 hash derived from its contents. This hash ensures the block's immutability once it's part of the blockchain.

Constructing the Hive-Inspired Blockchain

Our blockchain simulation requires a robust system to manage the blocks, akin to the Hive blockchain. The HiveLikeBlockchain class below is responsible for initialising the blockchain with a genesis block and providing the infrastructure to append new blocks:

class HiveLikeBlockchain {
  private chain: Block[];
  private readonly genesisBlock: Block;

  constructor() {
    this.chain = [];
    this.genesisBlock = this.createGenesisBlock();
    this.chain.push(this.genesisBlock);
  }

  createGenesisBlock(): Block {
    return new Block([], '0');
  }

  addBlock(newBlock: Block) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    this.chain.push(newBlock);
  }

  getLatestBlock(): Block {
    return this.chain[this.chain.length - 1];
  }

  isValidChain(): boolean {
    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.previousHash !== previousBlock.hash) {
        return false;
      }
    }
    return true;
  }
}

Notably, the addBlock method ensures that each new block is tethered to the chain by referencing the hash of the last block, a process that is critical for maintaining the blockchain's integrity.

Emulating Hive's Three-Second Block Time

One of Hive's hallmark features is its three-second block time, which ensures a seamless user experience. Our simulation mimics this rapid block production using JavaScript's setInterval function, as shown below:

const hiveLikeBlockchain = new HiveLikeBlockchain();

setInterval(() => {
  const newBlock = new Block([{ from: 'User1', to: 'User2', amount: 50 }]);
  hiveLikeBlockchain.addBlock(newBlock);

  console.log(`Block #${hiveLikeBlockchain.chain.length} has been added to the blockchain!`);
  console.log(`Hash: ${newBlock.hash}\n`);
}, 3000);

This snippet illustrates the consistent pace at which new blocks are forged in our simulated blockchain, akin to the steady heartbeat of the Hive network.

Ensuring the Integrity of the Chain

A blockchain's trustworthiness hinges on its ability to resist tampering. The isValidChain method in our HiveLikeBlockchain class verifies that each block's hash is accurately computed and that the entire chain is free from unauthorised alterations:

isValidChain(): boolean {
  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.previousHash !== previousBlock.hash) {
      return false;
    }
  }
  return true;
}

This validation function is the cornerstone of our blockchain's security, albeit without the features of a real blockchain that secure it.

Wrapping Up

Our TypeScript example does not encompass the entire complexity of Hive's blockchain, such as the Delegated Proof of Stake (DPoS) consensus mechanism or the intricacies of witness selection and transaction verification. Nonetheless, it offers a conceptual framework for understanding the fundamental principles of blockchains like Hive.

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

This awesome,many lessons to learn here keep it up.

Congratulations @beggars! You received a personal badge!

Happy Hive Birthday! You are on the Hive blockchain for 6 years!

You can view your badges on your board and compare yourself to others in the Ranking

Check out our last posts:

Our Hive Power Delegations to the December PUM Winners
Feedback from the January Hive Power Up Day
Announcing the Winners of HiveBuzz's Yearly Author Badge for 2023!