Tuesday, October 4
Shadow

Simple example of how BlockChain works.

const SHA256 = require('crypto-js/sha256');

class Transaction {
    constructor(public from: string, public to: string, public amount: number) {}
}
const sampleTransaction1 = {from: "Mehmet", to: "D++", amount: 100};
const sampleTransaction2 = {from: "D++", to: "Mehmet", amount: 100};

class Block {
    public timestamp: number;
    public hash: string;
    constructor(public index: number, public data: object, public prevHash: string = "0000") {
        this.timestamp = Date.now();
        this.hash = this.calculateHash();
    }

    public calculateHash() {
        return SHA256(this.prevHash + this.timestamp + JSON.stringify(this.data)).toString();
    }
}

class BlockChain {
    public chain: Block[];

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

    createGenesisBlock(): Block {
        return new Block(0, new String("Genesis Block"));
    }

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

    addBlock(block: Block): void {
        if (this.isChainValid()) {
            block.prevHash = this.getLatestBlock().hash;
            block.hash = block.calculateHash();
            this.chain.push(block);
        }
    }

    isChainValid(): boolean {
        for (let i = 1; i < this.chain.length; i++) {
            const current = this.chain[i];
            const previous = this.chain[i - 1];

            if (current.hash !== current.calculateHash()) return false;
            if (current.prevHash !== previous.hash) return false;
        }
        return true;
    }
}

const myBlockChain: BlockChain = new BlockChain();
myBlockChain.addBlock(new Block(1, sampleTransaction1));
myBlockChain.addBlock(new Block(2, sampleTransaction2));
console.log(JSON.stringify(myBlockChain, null, 4));

console.log(`Is chain valid? ${myBlockChain.isChainValid()}`);

myBlockChain.chain[1].data = new String("Altered Block Data");
console.log(`Is chain valid? ${myBlockChain.isChainValid()}`);

Leave a Reply