Blockchain Development from Scratch with Typescript #2: Setup Mining

in #utopian-io8 years ago (edited)

In this video tutorial, I will be setting up the mining part of the blockchain with the hashing algorithm SHA256 which is also used by BitCoin.

a.png

What Will I Learn?

  • Make use of js-sha256 library
  • Create a basic mining with SHA256 library

Requirements

  • Basic understanding of BlockChain
  • Understanding of Typescript
  • Understanding basic of Object Oriented Programming and Data Structure

Difficulty

Advanced

Description

The project started with the branch: blockchain-1 and end with branch: blockchain-2

1: Install js-sha256 library

First, install js-sha256 library with npm install --save js-sha256 or yarn add js-sha256

Using js-sha256 library

You can try out js-sha256 library in Node REPL.

> node
> let sha256 = require('js-sha256');
> console.log(sha256('abc'));

Create typings

in types.d.ts, declare a module for js-sha256, since this library is not in typings

// js-sha256
declare module 'js-sha256' {
    function sha256(data: string): string;

    export default sha256;
}

2: Add in more function for blockchain class

get previous block

This function will get the previous block

public getPreviousBlock(): BlockData {
    return this.blocks[this.blocks.length - 1];
}

get next block

This function will get the next block. However, this step is a bit tricky because in order to get next block, it involves of mining.

Before implementing this method, we need a generateHash function.

public generateHash(block: BlockData): string {
    let hash = sha256(block.key);
    
    // mining
    while(!hash.startsWith('7a7')) {
        block.nonce += 1;
        hash = sha256(block.key);
        console.log(hash);
    }

    return hash;
}

This function expect to pass in a BlockData and return a string. The line while(!hash.startsWith('7a7')) stated that if the hash starts with '7a7', then the mining is complete.

The generated hash will be started with '7a7'.

The hash generated is always the same, therefore a small change in the data or transaction will make different hashes, hence making that transaction to be invalid.

Then, we implement generateHash into getNextBlock

public getNextBlock(transactions: TransactionData[]) {
    let block = new Block();

    transactions.map(function(t: TransactionData) {
        block.addTransaction(t);
    })

    let previousBlock = this.getPreviousBlock();
    block.index = this.blocks.length;
    block.previousHash = previousBlock.hash;
    block.hash = this.generateHash(block);

    return block;

}

In order to get the next block, we add in transaction, index and previous hash to the block, and then generateHash will generate hash for the current block.

The next step after generate the block, is to save the block with addBlock, which I will explain later.

3: Testing out the code

In app.ts file, we will test out the code we had written. The current setting for this blockchain is 1 transaction per block.

First, import all the necessary classes.

import Blockchain from './blockchain';
import Block from './block';
import Transaction from './transaction';

Then, create a genesis block (first block) by declaring new Block class.

// create a genesis block
let b = new Block();

Next, Initialize Blockchain class by passing in the block.

// initialize blockchain with genesis block
let bc = new Blockchain(b);

Now, create a transaction by passing in 'from', 'to', 'amount' parameters into Transaction class.

// create a transaction
let t = new Transaction('me', 'you', 7);

Last, generate new block with the Blockchain.

// mining part
let newB = bc.getNextBlock([t]);
bc.addBlock(newB);

You can check the transaction of the blockchain in the second block.

console.log(bc.blocks[1].transactions);

Full source code

The full source code is located at my github with the branch blockchain-2

Next tutorial

In the next tutorial, I will make all the blockchain feature into an API with Expreess.js.

Video Tutorial

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution @superoo7. It has been approved.

This is a very interesting tutorial. I am sure many learners appreciate you taking the effort to make this.

I have only 1 suggestion: You cover a great deal of content in one tutorial. Take your time. There is no rush. For a tutorial of this complexity you could slow it down and break it into a couple of lessons. Your call entirely.

Great work. I look forward to more of your excellent work.

You can contact us on Discord.
[utopian-moderator]

Thanks moderator, I'm still learning to create video tutorial, thanks for the suggestions

You've been upvoted by TeamMalaysia community. Do checkout other posts made by other TeamMalaysia authors at http://steemit.com/created/teammalaysia

To support the growth of TeamMalaysia Follow our upvotes by using steemauto.com and follow trail of @myach

Vote TeamMalaysia witness bitrocker2020 using this link vote for witness

Thanks ❤️

So now creating your own mining system?

basic mining, haha.

I am doing a project for using blockchain to solve counterfeit certificate, I made these video series to showcase how I achieve these.

Awesome! Thanks for sharing!

Hey @superoo7 I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60578.05
ETH 1558.21
USDT 1.00
SBD 0.50