블록구조를 이해하고 블록을 만든다.
블록을 연결하는구조 , 다른사람이 가지고 있는 블록을 소통할수 있는 노드의 정보를 주고 받기
그런 노드를 제어할수 있는 http 페이지 제작
트랜잭션(거래)를 처리하는 방법
main.js
p2p 서버 초기화, 사용
http 서버 초기화, 사용
블록체인 함수 사용
httpServer.js
웹에 명령어를 입력해서 내 노드를 제어하는 서버
p2pServer.js
peer to peer = p2p, 노드 vs 노드, 개인과 개인, 서로가 필요한 정보를 복사해주며 공유해가며 통신
다른노드와 통신을 위한 서버
block.js
블록체인 관련 함수
블록 구조 설계
main.js
// p2p 서버 초기화, 사용
// http 서버 초기화, 사용
// 블록체인 함수 사용
import { initHttpServer } from "./httpServer.js";
import { initP2PServer } from "./p2pServer.js";
const httpPort = parseInt(process.env.HTTP_PORT) || 3001;
const p2pPort = parseInt(process.env.P2P_PORT) || 6001;
initHttpServer(httpPort);
initP2PServer(p2pPort);
httpServer.js
// 웹에 명령어를 입력해서 내 노드를 제어하는 서버
// const epress = require('express') // 전부다 가져온다.
import express from 'express'; // 필요한 것만 가져와서 간결하게 쓸수 있다.
import bodyParser from 'body-parser';
import { getBlocks, createBlock } from './block.js';
// 초기화 함수
const initHttpServer = (myHttpPoryt) => {
const app = express();
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello, World!');
})
app.get('/blocks', (req, res) => {
res.send(getBlocks());
})
// app.post('/createblock', (req, res) => {
// const data = req.body.data
// res.send(createBlock(data));
// })
app.post('/createblock', (req, res) => {
res.send(createBlock(req.body.data));
})
app.listen(myHttpPoryt, () => {
console.log('listening httpServer Port : ', myHttpPoryt);
})
}
export { initHttpServer }
p2pServer.js
// peer to peer = p2p, 노드 vs 노드, 개인과 개인, 서로가 필요한 정보를 복사해주며 공유해가며 통신
// 다른노드와 통신을 위한 서버
import WebSocket from 'ws'
import { WebSocketServer } from 'ws'; // 포트만 넣어주면 서버만들어주는 친구
const sockets = []; //
const initP2PServer = (p2pPort) => {
const server = new WebSocketServer({port:p2pPort})
server.on('connection', (ws) => {
initConnection(ws);
})
console.log('listening P2PServer Port : ', p2pPort);
}
const initConnection = (ws) => {
sockets.push(ws);
}
export { initP2PServer }
block.js
// 블록체인 관련 함수
// 블록 구조 설계
/*
index : 블록체인의높이 height
data : 블록에 포함된 모든데이터 (트랜잭션 포함)
timestamp : 블록이 생성된 시간
hash : 블록 내부 데이터로 생성한 sha256 값 (블록의 유일성 보장)
previousHash : 이전 블록의 해쉬(이전 블록을 참조한다)
*/
import CryptoJS from 'crypto-js' // 모듈이 없다고 나오면 npm install
class Block {
constructor(index, data, timestamp, hash, previousHash)
{
this.index = index;
this.data = data;
this.timestamp = timestamp;
this.hash = hash;
this.previousHash = previousHash;
}
}
// function getBlocks() {
// return blocks;
// }
const getBlocks = () => {
return blocks;
}
const calculateHash = (index, data, timestamp, previousHash) => {
// return CryptoJS.SHA256(index + data + timestamp + previousHash).toString();
return CryptoJS.SHA256((index + data + timestamp + previousHash).toString()).toString();
// return CryptoJS.SHA256((2).toString()).toString();
}
const createGenesisBlock = () => {
const genesisBlock = new Block(0, 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks', new Date().getTime() / 1000, 0 , 0);
genesisBlock.hash = calculateHash(genesisBlock.index, genesisBlock.data, genesisBlock.timestamp, genesisBlock.previousHash);
return genesisBlock;
}
const createBlock = (blockdata) => {
const previousBlock = blocks[blocks.length - 1];
const nextIndex = previousBlock.index + 1;
const nextTimestamp = new Date().getTime() / 1000;
const nextHash = calculateHash(nextIndex, blockdata, nextTimestamp, previousBlock.hash);
const newBlock = new Block(nextIndex, blockdata, nextTimestamp, nextHash, previousBlock.hash);
if (isValidNewBlock(newBlock, previousBlock))
{
blocks.push(newBlock);
return newBlock;
}
console.log('fail to create newblock');
return null;
}
// 블록의 무결성 검증
/*
블록의 인덱스가 이전 블록인덱스보다 1 크다.
블록의 previousHash가 이전 블록의 hash 이다.
블록의 구조가 일치해야 한다.
*/
const isValidBlockStructure = (newBlock) => {
if (typeof (newBlock.index) === 'number'
&& typeof (newBlock.data) === 'string'
&& typeof (newBlock.timestamp) === 'number'
&& typeof (newBlock.hash) === 'string'
&& typeof (newBlock.previousHash) === 'string' ) {
return true;
}
return false;
}
/*
(typeof (newBlock.index) !== 'number'
|| typeof (newBlock.data) !== 'string'
|| typeof (newBlock.timestamp) !== 'number'
|| typeof (newBlock.hash) !== 'string'
|| typeof (newBlock.previousHash) !== 'string' )
*/
const isValidNewBlock = (newBlock, previousBlock) => {
if (newBlock.index !== previousBlock.index + 1) // !== 타입까지 비교해준다.
{
console.log('invalid index');
return false;
}
else if (newBlock.previousHash !== previousBlock.hash)
{
console.log('invalid previous hash');
return false;
}
else if(isValidBlockStructure(newBlock) == false) {
console.log('invalid previous structure')
return false;
}
return true;
}
// let testHash = calculateHash(10, 20, 30, 40);
// console.log(testHash);
// console.log(testHash.length); new Block();
const blocks = [createGenesisBlock()];
export { getBlocks, createBlock };
npm install express crypto-js ws
import 에러시 package.json 에서 "dependencies" 위에 "type": "module", 추가
포스트맨으로 확인해보기




