區塊鏈--用nodejs實現簡單的P2P網路
阿新 • • 發佈:2019-01-22
最近學習了200行程式碼實現一個簡單的區塊鏈https://github.com/lhartikk/naivechain
初步學習nodejs,實現P2P網路的簡單模式,添加了多點資訊同步更新。
節點功能實現:
var initHttpServer = () =>{//控制節點的HTTP伺服器 類似節點操作 var app = express(); app.use(bodyParser.json()); app.get('/peers', (req, res) => {//獲取顯示網路中存在的節點, res.send(sockets.map(s => s._socket.remoteAddress + ':' + s._socket.remotePort)); }); app.post('/addPeer', (req, res) => {//請求新增新的節點{"peer" : "ws://localhost:6001"} connectToPeers([req.body.peer]);//新增新節點 res.send([req.body.peer]); }); app.get('/getNum', (req, res) => res.send(num));//顯示num值 app.post('/numAdd', (req, res) => {//執行操作num++ num++; broadcast(responseLatestMsg());//廣播 console.log('block added: ' + num);//終端實時打印出新增區塊 res.send(); }); app.listen(http_port, () => console.log('Listening http on port: ' + http_port));//監聽埠 }
P2P網路:
//---建立P2P網路 var initP2PServer = () => {//P2P websocket全雙工 伺服器 var server = new WebSocket.Server({port: p2p_port}); server.on('connection', ws => initConnection(ws)); console.log('listening websocket p2p port on: ' + p2p_port); }; var initConnection = (ws) => {//初始化連線 sockets.push(ws);//壓入已連線的節點堆疊 initMessageHandler(ws);//資訊處理 initErrorHandler(ws);//錯誤狀態處理 write(ws,responseLatestMsg());//廣播 console.log('new peer:'+ws._socket.remoteAddress + ':' + ws._socket.remotePort) }; var initMessageHandler = (ws) => {//同步資訊處理 ws.on('message', (data) => { var message = JSON.parse(data); console.log('Received message' + JSON.stringify(message)); switch (message.type) { case MessageType.QUERY_LATEST: handleNum(message);//寫入最新的num break; } }); }; var initErrorHandler = (ws) => {//錯誤資訊處理 var closeConnection = (ws) => { console.log('connection failed to peer: ' + ws.url +" "+ws._socket.remoteAddress + ':' + ws._socket.remotePort); sockets.splice(sockets.indexOf(ws), 1); }; ws.on('close', () => closeConnection(ws)); ws.on('error', () => closeConnection(ws)); }; var handleNum = (message) => {//同步區塊鏈資訊 if (num<message.data) { num = message.data; console.log('We got new number ' + message.data); broadcast(responseLatestMsg());//有更新,向臨近節點廣播 } else { console.log('received num is not max. Do nothing'); } }; var connectToPeers = (newPeers) => {//連線新節點 客戶端 newPeers.forEach((peer) => { var ws = new WebSocket(peer); ws.on('open', () => initConnection(ws)); ws.on('error', () => { console.log('connection failed') }); }); };
參考:https://github.com/zfzGit/P2PNodejs