create account

Demystifying Blockchain: A Hive-Inspired Example with TypeScript by beggars

View this thread on: hive.blogpeakd.comecency.com
· @beggars ·
$3.82
Demystifying Blockchain: A Hive-Inspired Example with TypeScript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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.
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 212 others
properties (23)
authorbeggars
permlinkdemystifying-blockchain-a-hive-inspired-example-with-typescript
categoryhive-139531
json_metadata"{"tags":["hive-139531","hive","hivedevs","typescript","blockchain"],"app":"hiveblog/0.1","format":"markdown","description":"Learn how blockchains like Hive work using Typescript"}"
created2023-12-07 00:19:45
last_update2023-12-07 00:19:45
depth0
children3
last_payout2023-12-14 00:19:45
cashout_time1969-12-31 23:59:59
total_payout_value1.930 HBD
curator_payout_value1.886 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,992
author_reputation75,252,102,727,271
root_title"Demystifying Blockchain: A Hive-Inspired Example with TypeScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,471,773
net_rshares8,267,971,131,528
author_curate_reward""
vote details (276)
@hivebuzz ·
Congratulations @beggars! You received a personal badge!

<table><tr><td>https://images.hive.blog/70x70/http://hivebuzz.me/badges/birthday-6.png</td><td>Happy Hive Birthday! You are on the Hive blockchain for 6 years!</td></tr></table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@beggars) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>


**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/pum-202312-delegations"><img src="https://images.hive.blog/64x128/https://i.imgur.com/fg8QnBc.png"></a></td><td><a href="/hive-122221/@hivebuzz/pum-202312-delegations">Our Hive Power Delegations to the December PUM Winners</a></td></tr><tr><td><a href="/hive-122221/@hivebuzz/pud-202401-feedback"><img src="https://images.hive.blog/64x128/https://i.imgur.com/zHjYI1k.jpg"></a></td><td><a href="/hive-122221/@hivebuzz/pud-202401-feedback">Feedback from the January Hive Power Up Day</a></td></tr><tr><td><a href="/hivebuzz/@hivebuzz/yearly-author-202401"><img src="https://images.hive.blog/64x128/https://i.imgur.com/ogVqE0F.png"></a></td><td><a href="/hivebuzz/@hivebuzz/yearly-author-202401"> Announcing the Winners of HiveBuzz's Yearly Author Badge for 2023!</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-beggars-20240104t145922
categoryhive-139531
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2024-01-04 14:59:24
last_update2024-01-04 14:59:24
depth1
children0
last_payout2024-01-11 14:59:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,259
author_reputation368,399,342,643,196
root_title"Demystifying Blockchain: A Hive-Inspired Example with TypeScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,218,325
net_rshares0
@ijebest ·
This awesome,many lessons to learn here keep it up.
properties (22)
authorijebest
permlinkre-beggars-20231220t121847799z
categoryhive-139531
json_metadata{"type":"comment","tags":["hive-139531","hive","hivedevs","typescript","blockchain"],"app":"ecency/3.0.44-mobile","format":"markdown+html"}
created2023-12-20 11:19:03
last_update2023-12-20 11:19:03
depth1
children0
last_payout2023-12-27 11:19:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length51
author_reputation18,814,378,446,448
root_title"Demystifying Blockchain: A Hive-Inspired Example with TypeScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,816,299
net_rshares0
@stemsocial ·
re-beggars-demystifying-blockchain-a-hive-inspired-example-with-typescript-20231208t045032353z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> 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.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-beggars-demystifying-blockchain-a-hive-inspired-example-with-typescript-20231208t045032353z
categoryhive-139531
json_metadata{"app":"STEMsocial"}
created2023-12-08 04:50:33
last_update2023-12-08 04:50:33
depth1
children0
last_payout2023-12-15 04:50:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,468,239,130,863
root_title"Demystifying Blockchain: A Hive-Inspired Example with TypeScript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,500,260
net_rshares0