Blockchain Development from Scratch with Typescript #3: Resolve Type error and Setup Express API Server

qaq.png

What Will I Learn?

  • Resolve Type Error from the previous video
  • Setup basic REST API with Express alongside with BlockChain classes

Requirements

  • Basic understanding on how Express.js and REST API works
  • Installed PostMan
  • Basic understanding of BlockChain
  • Understanding of Typescript
  • Understanding basic of Object Oriented Programming and Data Structure

Difficulty

Advanced

Description

In this video, I will first resolve the type error from the previous video, and start to make a REST API with Express. I will be using PostMan to do HTTP GET and POST request.

Changed in code [Reference]

Install required dependencies

  • yarn add --dev @types/express @types/node
  • yarn add express

Resolved Type Error

github commit

in src/types/class.ts, export out all the class interface

export interface TransactionData {
    from: string;
    to: string;
    amount: number;
}
export interface BlockData {
    index: number;
    hash: string;
    previousHash: string;
    nonce: number;
    transactions: TransactionData[];
    key: string;
    addTransaction(transaction: TransactionData): void;
}
export interface BlockChainData {
    blocks: BlockData[];
    difficulty: number;
    addBlock(block: BlockData): void;
    getNextBlock(transations: TransactionData[]): BlockData;
    getPreviousBlock(): BlockData;
    generateHash(block: BlockData): string;
}

in src/types/lib.ts, export out sha256 library. (Since there is no typings for js-sha256)

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

Setup difficulty in BlockChain class

In the class constructor, setup the difficulty to be 1 for the ease of development.

In production, need to make sure that the difficulty is hard enough that you need a lot of computing power to hack it.

export default class Blockchain implements BlockChainData {
    public blocks: BlockData[];
    public difficulty: number;
    constructor(genesisBlock: BlockData) {
        this.blocks = [];
        this.difficulty = 1;

In the mining part / generateHash

  public generateHash(block: BlockData) {
        let hash = sha256(block.key);
        
        // mining
        while(!hash.startsWith(Array(this.difficulty + 1).join('0'))) {
            block.nonce += 1;
            hash = sha256(block.key);
            console.log(hash);
        }

        return hash;
    }

Setup an API Server

Import necessary library, express for setting up Node.js REST API server, body-parser allow us to parse the incoming json file.

// external library
import * as express from 'express';
import * as bodyParser from 'body-parser';

Import all our classes (Blockchain, Block, Transaction)

// Our classes
import Blockchain from './blockchain';
import Block from './block';
import Transaction from './transaction';
import { TransactionData } from './types/class';

Initialize express server

// Setup express REST API
const app = express();
app.use(bodyParser.json());

Initialize Blockchain by passing in a genesis block. The transaction is set to be empty.

// Initialize Blockchain
// create a genesis block
let genesisBlock = new Block();
// initialize blockchain with genesis block
let bc = new Blockchain(genesisBlock);
// Transactions
let transactions: TransactionData[] = [];

Start a route with a GET request to 'localhost:3000/'

app.get('/', function(req, res){
    res.json(bc.blocks);
})

Create a transaction with POST method

app.post('/transaction', function(req, res) {
    let {from, to, amount} = req.body;
    // create a transaction
    let t = new Transaction(from, to, amount);
    transactions = [...transactions, t];    
    res.json(t);
})

Mine the block

app.get('/mine', function(req, res) {
    // mining part
    let newB = bc.getNextBlock(transactions);
    transactions = [];
    bc.addBlock(newB);
    res.json(bc);
})

Start the server on port 3000

// Start the server at port 3000
app.listen(3000, function() {
    console.log('post started at 3000')
})

Next video

In the next video, I will make this server into decentralized database. Later on, I will build an UI front end with React.js.

Video Tutorial

DTube

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
Upload from PC
Video gallery
3 columns
2 columns
1 column
6 Comments