ブロックチェーン--nodejsで簡単なP 2 Pネットワークを実現します.


最近200行のコードを勉強しました.簡単なブロックチェーンを実現します.https://github.com/lhartikk/naivechain
まずnodejsを勉強して、P 2 Pネットワークの簡単なモードを実現して、多点情報の同時更新を追加しました.
ノード機能の実装:

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));//    

}
 
P 2 Pネットワーク:
//---  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 {//          

    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