728x90
반응형
이제 새로운 블록을 만들어보자.
새로운 블록을 만들기 위해서는 해쉬를 계산해야한다.
먼저 crypto-js를 설치하자.
$ npm i crypto-js
그다음 블록체인이 추가될 때 사용할 함수를 static으로 선언하고 return값을 지정해준다.
static으로 선언한 메소드를 사용하면 별도의 인스턴스 없이 바로 클래스의 메소드를 쓸 수 있다.
index.ts
import * as CryptoJS from "crypto-js"
class Block {
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
static calculateBlockHash = (
index: number,
previousHash: string,
timestamp: number,
data: string
):string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()
constructor(
index: number,
hash: string,
previousHash: string,
data: string,
timestamp: number
) {
this.index = index;
this.hash = hash;
this.previousHash = previousHash;
this.data = data;
this.timestamp = timestamp;
}
}
const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);
let blockchain: Block[] = [TeepoBlock];
console.log(blockchain)
export {};
이제 나중에 사용할 함수들을 추가하자.
import * as CryptoJS from "crypto-js"
class Block {
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
static calculateBlockHash = (
index: number,
previousHash: string,
timestamp: number,
data: string
):string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString()
constructor(
index: number,
hash: string,
previousHash: string,
data: string,
timestamp: number
) {
this.index = index;
this.hash = hash;
this.previousHash = previousHash;
this.data = data;
this.timestamp = timestamp;
}
}
const TeepoBlock: Block = new Block(0, "20202020202", "", "Hello", 123456);
let blockchain: Block[] = [TeepoBlock];
const getBlockchain = (): Block[] => blockchain;
const getLatestBlock = (): Block => blockchain[blockchain.length -1];
const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);
console.log(blockchain)
export {};
getBlockchain 함수는 말 그대로 Block을 반환한다.
getLatestBlock 함수는 가장최근의 블록을 반환한다.
getNewTimeStamp 함수는 timestamp 속성을 새로 지정해주기 위한 함수이다.
728x90
반응형
'Typescript > 블록체인' 카테고리의 다른 글
TypeScript | 블록체인 | 결과 (0) | 2021.10.05 |
---|---|
TypeScript | 블록체인 | 블록 검증하기 (0) | 2021.10.05 |
TypeScript | 블록체인 | 블록 만들기(3) (0) | 2021.10.05 |
TypeScript | 블록체인 | 블록 만들기(1) (0) | 2021.10.05 |