음,,, 일단 이걸 하게된 과정은
1. 요새 코인에 관심이 간다
2. 그래서 블록체인에도 관심이 생겼다.
3. 자바스크립트를 주로 쓰는 와중에 타입스크립트가 요새 핫하단다.
그래서 두개 동시에 써보자는 생각으로 만들어따.
블록체인에 대해 간단하게 설명하자면
관리 대상 = 데이터 = 블록 (내생각)
이걸 p2p방식으로 체인형태의 연결고리 기반 분산 데이터 저장 환경에 저장하여 관리하는 것이다.
누구라도 임의로 수정할 수 없고 참여자들 누구나 변경의 결과를 열람할 수 있는 것이 특징이다.
즉, 블록체인이란 블록(데이터)들이 체인형태로 묶여있는 것
블록체인은 블록들로 이루어져 있단따. 그럼 블록은 뭐로 이루어져있을까?!
크게 헤더와 바디이다.
1. 헤더
헤더는(버전 + 이전 블록 해시 + 머클 루트 + 타임 + bits + nonce)의 합을 구한후 SHA256으로 변환한 값이다.
2. 바디
트랜잭션 정보들
이다.
너무 너무 어렵다. 개발 삐꾸인 내가 이걸 다 만들면 삼성 문 부수고 들어갔을거다.
(ㅠㅠ 취업하고 싶다)
그래서 이번에 타입스크립트로 만들어 본것은 버전, 이전블록 해시, 타임 정도만 만들어 보았따
먼저, 타임스크립트를 쓰려면
1. yarn global add typescript
2. tsconfig.json
{
"compilerOptions" : {
"module" : "commonjs",
"target" : "ES2015",
"sourceMap": true,
"outDir": "dist",
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
3. 폴더 구조
4. tsc-watch 설치 및 scripts 수정
yarn add tsc-watch --dev
{
"private": true,
"scripts": {
"start": "tsc-watch --onSuccess \" node dist/index.js\" "
},
"devDependencies": {
"@types/node": "^17.0.8",
"ts-node": "^10.4.0",
"tsc-watch": "^4.6.0",
"typescript": "^4.5.4"
},
"dependencies": {
"crypto-js": "^4.1.1"
}
}
(index.ts에 테스트코드치고 터미널에 yarn start 쳐서 잘되면 초기 설정 끝!)
5. 본격적인 코드
import * as CryptoJS from "crypto-js";
class Block {
static calculateBlockHash = (
index : number,
previousHash:string,
timestamp:number,
data:string
): string =>
CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
static validateStructure = (aBlock : Block) : boolean =>
typeof aBlock.index === "number" &&
typeof aBlock.hash === "string" &&
typeof aBlock.previosHash === "string" &&
typeof aBlock.timestamp === "number" &&
typeof aBlock.data ==="string";
public index:number;
public hash: string;
public previosHash : string;
public data : string;
public timestamp : number;
constructor(
index:number,
hash: string,
previosHash : string,
data : string,
timestamp : number,
){
this.index = index;
this.hash = hash;
this.previosHash = previosHash;
this.data = data;
this.timestamp = timestamp;
}
}
const genesisBlock:Block = new Block(0,"20202002020202020", "", "Hello", 123456);
let blockchain: Block[] = [genesisBlock];
const getBlockchain = ():Block[] => blockchain;
const getLatesBlock = (): Block => blockchain[blockchain.length-1];
const getNewTimeStamp = (): number => Math.round(new Date().getTime() / 1000);
const createNewBlock = (data:string) : Block => {
const previousBlock : Block = getLatesBlock();
const newIndex : number = previousBlock.index + 1;
const newTimestamp : number = getNewTimeStamp();
const newHash : string = Block.calculateBlockHash(newIndex, previousBlock.hash, newTimestamp, data);
const newBlock : Block = new Block(newIndex, newHash, previousBlock.hash, data, newTimestamp);
addBlock(newBlock)
return newBlock;
};
const getHashforBlock = (aBlock : Block) : string => Block.calculateBlockHash(aBlock.index, aBlock.previosHash, aBlock.timestamp, aBlock.data);
const isBlockValid = (candidateBlock : Block, previousBlock:Block) : boolean => {
if(!Block.validateStructure(candidateBlock)){
return false;
}else if(previousBlock.index + 1 !== candidateBlock.index){
return false;
}else if(previousBlock.hash !== candidateBlock.previosHash){
return false;
}else if(getHashforBlock(candidateBlock) !== candidateBlock.hash) {
return false;
}else {
return true;
}
};
const addBlock =(candidateBlock : Block) : void => {
if(isBlockValid(candidateBlock, getLatesBlock())){
blockchain.push(candidateBlock);
};
};
createNewBlock("second Blockchain");
createNewBlock("third Blockchain");
createNewBlock("fourth Blockchain");
console.log(blockchain);
export{};
6. END
잘 나오는 걸 확인할 수 있다.
모두 다 열코하세요 ~~~~~~~~ 새해복 많이 받으333
참고 사이트
https://steemit.com/kr/@yahweh87/3
'React' 카테고리의 다른 글
[React] node router설정 (0) | 2022.01.11 |
---|---|
[React] Mongo + Node + React 회원가입, 로그인 (2) | 2022.01.11 |
[React] 로그인 시 사용자 정보 storage(저장소)에 넣기 (localstorage VS sessionstrorage) (0) | 2022.01.07 |
[React] 절대경로 설정하기 (0) | 2022.01.06 |
[React] react router (v6) (1) | 2021.12.16 |