[Typescript] 타입스크립트로 블록체인 만들기 강의 학습 #7

jhcha·2023년 8월 1일
0

Typescript

목록 보기
7/8
post-thumbnail

ts-node

npm i -D ts-node

ts-node는 빌드 없이 타입스크립트를 실행할 수 있게 해준다.
프로덕션 환경에서 사용하는 것이 아니라, 개발 단계에서 컴파일할 필요 없이 실행시켜주기 때문에 편리하다.

nodemon

npm i nodemon

nodemon은 자동으로 커맨드를 재실행하기 때문에 명령어를 다시 실행하거나 서버를 재시작하지 않아도 된다.

  "scripts": {
    "build": "tsc",
    "dev": "nodemon --exec ts-node src/index.ts",
    "start": "node build/index.js"
  },

package.json에 script를 추가하여 nodemon 명령어를 추가

npm run dev

nodemon을 통해 ts-node src/index.ts 명령어가 자동으로 재실행되고, index.ts 파일의 변경에 따라 스크립트가 실행된다.

// index.ts
// import crypto from "crypto"
import * as crypto from "crypto"
// tsconfig.json
{
    "compilerOptions": {
        "esModuleInterop": true
    }
}

자바스크립트에는 여러 시스템과 모듈이 존재한다. CommonJs, UMD,ESModule과 같은 여러 종류의 모듈이 존재한다.

import crypto from "crypto"

이 방식은 익숙한 표현 방식이지만 기본적인 동작은 아니다.

타입스크립트로 만들어지지 않은 패키지를 받았는데 타입 정의가 하나도 없어서 인식하지 못할 때 DefenitelyTyped Repository를 사용할 수 있다.

DefenitelyTyped Repository

DefenitelyTyped는 npm에 존재하는 거의 모든 패키지들에 대한 d.ts 파일이 존재한다.
url: https://github.com/DefinitelyTyped/DefinitelyTyped

npm i -D @types/node

Blockchain

블록체인은 블록이라는 데이터 구조를 체인 형태로 연결되어 있는 P2P 분산 원장 시스템이다.


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): string{
        const toHash = `${prevHash}${height}${data}`
        return crypto.createHash("sha256").update(toHash).digest("hex");
    }
}

class Blockchain {
    private block: Block[];
    constructor(){
        this.block = [];
    }
    private getPrevHash(){
        if(this.block.length === 0) return ""
        return this.block[this.block.length-1].hash;
    }
    public addBlock(data: string){
        const newBlock = new Block(this.getPrevHash(), this.block.length+1, data);
        this.block.push(newBlock);
    }
    public getBlock(){
        return [...this.block];
    }
}

const blockchain = new Blockchain();
blockchain.addBlock("First Block");
blockchain.addBlock("Second Block");
blockchain.addBlock("Third Block");

blockchain.getBlock().push(new Block("XXX", 111, "HACKED"));

console.log(blockchain.getBlock());

앞서 나왔던 타입스크립트 이론 및 기초 문법들을 기반으로 작성됐다.
특이사항은 getBlock() 함수에서 클래스 내부의 블록을 리턴하게 되면 외부에서 해당 프로퍼티에 접근할 수 있는 보안 이슈가 발생한다.

class Blockchain {
	...
    public getBlock(){
        return this.block;
    }
}
blockchain.getBlock().push(new Block("XXX", 111, "HACKED"));

따라서 ES6부터 지원하는 전개 연사자 (spread operator)를 사용한다. 해당 전개 연산자는 this.block을 복사한 새로운 객체를 반환함으로써 blockchain class 내부 프로퍼티 접근 이슈를 해결한다.

git remote add origin https://github.com/jh-cha/blockchain-typescript-lecture.git

마지막으로, 강의 수강 중 vscode로 따라 작성한 내용은 github에 업로드했다.
Github: https://github.com/jh-cha/blockchain-typescript-lecture

0개의 댓글