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

in utopian-io •  7 years ago  (edited)

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

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for sharing your posts with us. This post was curated by TeamMalaysia as part of our community support. Looking forward for more posts from you.

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 bitrocker2020 witness

Thank you for the contribution. It has been approved.

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

Thank you moderator, really appreciate it 🙌

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

Great tutorial, was easy to understand for a novice TypeScript coder.

You can use nodejs built in hashing library for making the sha256 hash so no need to import js-sha256 libraries ;)

var crypto = require('crypto');
var hash = crypto.createHash('sha256').update(block.key).digest("hex");

here is my complete generateHash method:

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

    return hash;
}

I din know that, was finding a library which supporr types haha. Thanks for sharing about this.