msdou45 2023. 2. 13. 08:42

________________________________________________________________________

 

TypeScript 블록체인 <5> - 블록체인 완성하기

 

 

< 타입스크립트로 블록체인 만들어보기 -  블록체인 기능을 빌드해보자. >

 

폴더 : kimminsoo -> NomadCoders -> typechain_2

 

 

 

 

 

 

1.

________________________________

< 필요한 셋팅은 완료. 블록체인을 마저 완성해 보자. >

 

 

 

——

import crypto from "crypto";

 

interface BlockShape {

    hash: string;       // 해당 블록이 가지게 될 해쉬값. 해당 블록만의 고유한 서명과도 같아. 결정론적 값.

    prevHash: string;   // 이전 해쉬값

    height:number;      // 1, 2, 3, 4, 5 같이 블록의 위치를 표시해주는 숫자.

    data: string;       // 해당 블록이 가지고 있을 데이터

}

 

class Block implements BlockShape {

    public hash: string;

 

    constructor (

        public prevHash: string,

        public height: number,

        public data: string

    ) {

        this.hash = Block.calculateHash(prevHash, height, data);

    }

 

    static calculateHash (prevHash:string, height:number, data:string) {

        const toHash = `${prevHash}${height}${data}`;

        return crypto.createHash("sha256").update(toHash).digest("hex");

    }

}

 

class BlockChain {

    private blocks: Block[]

 

    constructor () {

        this.blocks = [];

    }

 

    // 새로운 블록을 추가할 때, 이전 블록의 해쉬값을 가져오는 메소드

    private getPrevHash () {

        if (this.blocks.length === 0) return "";

        return this.blocks[this.blocks.length - 1].hash;

    }

 

    // 새로운 블록을 추가하고 싶을 때, 블록에 저장하고 싶은 데이터를 보내줘야.

    public addBlock (data:string) {

        const newBlock = new Block(this.getPrevHash(), this.blocks.length + 1, data);

        this.blocks.push(newBlock);

    }

 

    // 블록에 접근할 수 있는 메소드

    public getBlocks () {

        return this.blocks;

    }

}

 

const blockchain = new BlockChain();

blockchain.addBlock("First one");

blockchain.addBlock("second one");

blockchain.addBlock("third one");

 

console.log(blockchain.getBlocks());

——

 

=> 문제가 있어! 누구나가 블록 체인의 내용을 getBlocks() 로 확인할 수 있다는 것.

따라서 getBlocks() 할 때 깊은 복사로 하나를 복사해서 줘야지, 누군가가 래퍼런스 참조로 새롭게 push 나 Remove 를 하지 못하도록 해.

 

 

——

public getBlocks () {

        return [...this.blocks];    // 전개 연산자를 사용하여 깊은 복사로 배열을 하나 만들어서 리턴. 보안성을 위해.

    }

——

=> 이렇게!