index.ts
// Module '"crypto"' has no default export.
import crypto from "crypto"
// import * as crypto from "crypto"
interface BlockShape {
hash: string
prevHash: string
height: number
data: string
}
class Block implements BlockShape {
public hash: string
constructor(
// no readonly => 접근 및 수정 가능
public readonly prevHash: string,
public readonly height: number,
public readonly 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 block = new Block(this.getPrevHash(), this.blocks.length+1, data)
this.blocks.push(block)
}
public getBlocks() {
// this.blocks => 접근 및 수정 가능
return [...this.blocks]
}
}
const blockchain = new BlockChain()
blockchain.addBlock('first one')
blockchain.addBlock('second one')
blockchain.addBlock('third one')
// 보안 취약 경우1
// getBlocks() { return this.blocks } 라면, 아래 해킹된 블럭 추가됨
blockchain.getBlocks().push(new Block('xxx', 111, 'hacked'))
// 보안 취약 경우2
// Block constructor(public property: type) 라면, data 접근 가능
// blockchain.getBlocks()[blockchain.getBlocks().length-1].data = 'hellllll'
blockchain.addBlock('fourth one')
console.log(blockchain.getBlocks());
tsconfig.json
{
// VSC가 우리가 TS를 사용한다고 추측
"include": [ // 우리가 JS로 컴파일하고 싶은 모든 디렉터리
"src" // TS가 src의 모든 파일을 확인한다
],
"compilerOptions": {
"outDir": "build", // JS 파일이 생성될 디렉터리
"target": "ES6", // TS가 컴파일할 JS 버전 (ES6 권장-안정적)
"lib": ["ES6"], // 타겟 런타임 환경 -> 자동완성
"strict": true, // 정의 파일 없는 경우 에러
"esModuleInterop": true,
"module": "commonJS"
}
}
'Front-end > 타입스크립트로 블록체인 만들기' 카테고리의 다른 글
HW - Class (0) | 2024.01.20 |
---|---|
[TS] tsconfig.json (0) | 2024.01.04 |
[TS] Polymorphism + Generic Type + Interface (1) | 2024.01.04 |
[TS] Interfaces (1) | 2024.01.02 |
[TS] Classes (1) | 2024.01.02 |