본문 바로가기

개발/JavaScript

[TS] 블록체인 만들기

 

1. ts-node: build와 start를 한번에 하기

npm i -D ts-node

2. nodemon: 코드 수정 시 서버 자동 재실행

npm i nodemon
{
  "name": "typechain",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "tsc",
    "dev": "nodemon --exec ts-node src/index.ts",
    "start": "node build/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4"
  },
  "dependencies": {
    "nodemon": "^2.0.19"
  }
}

 

 

DefinitelyTypes

- npm의 js 패키지의 타입 정의 파일(.d.ts) repository

npm i -D @types/[패키지명]

https://github.com/DefinitelyTyped/DefinitelyTyped

 

 

 

블록 만들기

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");

console.log(blockchain.getBlocks());
[
  Block {
    prevHash: '',
    height: 1,
    data: 'First one',
    hash: 'd90f2cc6ecdb63760af30f041a06e85e9a4d3376cccc09ff807e08c749e81ca9'
  },
  Block {
    prevHash: 'd90f2cc6ecdb63760af30f041a06e85e9a4d3376cccc09ff807e08c749e81ca9',
    height: 2,
    data: 'Second one',
    hash: '21625d153b9a2ba0996ac8a8ce85b78d5512a4c0bbf647548b0befab3e9b3cfe'
  },
  Block {
    prevHash: '21625d153b9a2ba0996ac8a8ce85b78d5512a4c0bbf647548b0befab3e9b3cfe',
    height: 3,
    data: 'Third one',
    hash: '33090390c5b209e1796881ef8aa55128e9beab0941cbc6f4989260d6f5bd961b'
  }
]

 

 

https://www.typescriptlang.org/docs/handbook/intro.html

 

Handbook - The TypeScript Handbook

Your first step to learn TypeScript

www.typescriptlang.org

 

'개발 > JavaScript' 카테고리의 다른 글

[JS] call, apply, bind 함수  (0) 2022.08.09
[JS] Object Methods  (0) 2022.08.08
[TS] declaration file, JSDoc  (0) 2022.08.07
[TS] 타입스크립트 프로젝트 설정  (0) 2022.08.05
[TS] Interfaces  (0) 2022.08.05