[노마드코더 무료강좌] 타입스크립트로 블록체인 만들기 (7) 체인완료

Seong Hyeon Kim·2024년 1월 18일
0

import crypto from "crypto"

interface BlockShape {
    hash : string;
    prevHash : string;
    height : number;
    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");
  blockchain.addBlock("Fourth one");
  blockchain.addBlock("4번째 블록을 만들어보자");
  
  console.log(blockchain.getBlocks());
profile
삽질도 100번 하면 요령이 생긴다. 부족한 건 경험으로 채우는 개발자

0개의 댓글