import * as 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
){
console.log(`Creating block with height ${height}${data}`);
this.hash = Block.calculateHashs(prevHash,height,data);
}
static calculateHashs(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());
완성 코드이나 이해하는데 약간 어려운부분이 있다.
하이트값이 어디서 생성되는지 크립토 라는 라이브러리 사용하는데 무엇을 가져오는지도.
기본적으로 헤쉬값을 만드는데 크립토에서 값을 가져오는지 의문이듬.
'TypeScript' 카테고리의 다른 글
타입스크립트 interface란?? (0) | 2023.10.16 |
---|---|
class 객체지향 프로그래밍 oop (1) | 2023.10.15 |
vsc 타입스크립트 환경설정방법 (0) | 2023.05.04 |
다형성 코드란? var.2 (api 가져오는 예시 구조) (0) | 2023.04.25 |
타입과 인터페이스 차이. (0) | 2023.04.25 |