728x90
반응형

새로운 블록을 만드는 함수를 만들어보자. 만들어두었던 블록체인에 새 블록을 추가하는 과정은 다음글에서 검증하고 추가하도록 하겠다.

 

index.ts

import * as CryptoJS from "crypto-js"

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockHash = (
        index: number,
        previousHash: string,
        timestamp: number,
        data: string
    ): string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()

    constructor(
        index: number,
        hash: string,
        previousHash: string,
        data: string,
        timestamp: number
    ) {
        this.index = index;
        this.hash = hash;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
    }
}

const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);

let blockchain: Block[] = [TeepoBlock];

const getBlockchain = (): Block[] => blockchain;

const getLatestBlock = (): Block => blockchain[blockchain.length - 1];

const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data);
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp);
    return newBlock
}


console.log(createNewblock("hello"), createNewblock("bye bye"))

export { };

 

 

createNewblock 함수를 자세히 들여다 보자.

const createNewblock = (data: string): Block => {
    const previousBlock: Block = getLatestBlock();
    const newIndex: number = previousBlock.index + 1;
    const newTimestamp: number = getNewTimeStamp();
    const newHash: string = Block.calculateBlockHash(
        newIndex,
        previousBlock.hash,
        newTimestamp,
        data);
    const newBlock: Block = new Block(
        newIndex,
        newHash,
        previousBlock.hash,
        data,
        newTimestamp);
    return newBlock
}

 

 

1. previouseBlock으로 가장 최근의 블록을 가져온다.

 

2. previousBlock에서의 index에 1을 더한 값으로 newIndex를 선언한다.

 

3. 전 글에서 설명했던 getNewTimeStamp 함수로 newTimeStamp를 선언한다.

 

4. static으로 선언했던 calculateBlockHash로 새로운 Hash를 만든다.

 

5. 선언했던 자료들과 인자값인 data를 가지고 새로운 블록을 만들어준다.

728x90
반응형

+ Recent posts