- Foundations of Blockchain
- Koshik Raj
- 411字
- 2021-07-02 14:17:23
Running the blockchain nodes
Although each node has two handlers, one each for the HTTP and WebSocket interfaces. A single web server application instance is sufficient to serve both of them. Sanic uses uvloop as a scheduler. It asynchronously handles the requests:
if __name__ == '__main__': server = Server() server.app.add_task(server.connect_to_peers(initialPeers)) server.app.run(host='0.0.0.0', port=port, debug=True)
The server application is instantiated, and a task is created to connect the node to initialPeers, which is hardcoded by each node. The application will use the default port to create a web server.
Each node will run the server application to join the network. As soon as the node connects to one of the peers, its blockchain syncs with the updated blockchain of the network.
We're now going to run the application by creating three node instances: node1, node2, and node3. Node2 has node1 as its initial peer, and node3 has node2 as its initial peer. When we run all three node instances, they form a ring-like network.
Let's check the peer information of each node by calling the HTTP API endpoint /peers for each node:
- Node1: ["127.0.0.1:51160"]
- Node2: ["127.0.0.1:3001","127.0.0.1:35982"]
- Node3: ["127.0.0.1:3002"]
3001 is the port number assigned to node1. Node2 has port number 3002, and node3 has port number 3003. The random port number is the port number of the peer that tried to communicate with the node2. The preceding information clearly shows that node2 has added node1 as its peer and node3 has added node2 as its peer.
All the nodes return the following result when we invoke the /blocks HTTP API endpoint:
[ { "data": "my genesis block!!", "hash":
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", "index": 0, "previous_hash": "0", "timestamp": 1465154705 } ]
Let's mine a new block at node2 by using the /mineBlock HTTP API endpoint by sending a POST request with the payload {"data": "created at node2"}. Since all the nodes are interconnected, forming a mesh, each node will receive the newly broadcasted block and will update its local blockchain ledger. Now, each node reflects the following blockchain:
[ { "data": "my genesis block!!", "hash":
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", "index": 0, "previous_hash": "0", "timestamp": 1465154705 }, { "data": "created at node2", "hash":
"29630fab36aa1e3abf85b62aee8f84b08438b90e9e19f39d18766cc9208b585c", "index": 1, "previous_hash":
"816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7", "timestamp": "1522069707" } ]