블록을 생성해 보자.
calculateBlockHash 는 굳이 Block안에 안 넣어도 됨 생각 해보면 음 디자인의 관점인듯
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 genesisBlock: Block = new Block(0, 'abc123', '','genesis', 123456);
let blockchain: Block[] = [genesisBlock];
const getBlockchain = (): Block[] => blockchain;
const getLatestBlock = (): Block => blockchain[blockchain.length - 1];
const getNewTimestamp = (): number => Math.round(Date.now() / 1000);
const createNewBlock = (data: string): Block => {
const previousBlock: Block = getLatestBlock();
console.log(previousBlock);
const newIndex: number = previousBlock.index + 1;
const newTimestamp: number = getNewTimestamp();
const newHash: string = Block.calculateBlockHash(newIndex, previousBlock.hash, newTimestamp, data);
return new Block(newIndex, newHash, previousBlock.hash, data, newTimestamp);
};
console.log(createNewBlock("hi"));
console.log(createNewBlock("hello"));
// console.log(getBlockchain());