区块链--用nodejs实现简单的P2P网络

最近学习了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

阅读更多

没有更多推荐了,返回首页