当前位置:   article > 正文

GO语言实现区块链Part7 Network_【区块链go语言实现】part 3:持久化和cli

【区块链go语言实现】part 3:持久化和cli

Introduction

So far, we’ve build a blockchain that has all key features: anonymous, secure, and randomly generated addresses; blockchain data storage; Proof-of-Work system; reliable way to store transactions. While these features are crucial, it’s not enough. What makes these features really shine, and what make cryptocurrencies possible, is network. What’s the use of having such blockchain implementation running just on a single computer? What’s the use of those cryptography based features, when there’s just one user? It’s network that make all these mechanism work and be useful.

You can think of those blockchain features as rules, similar to the rules that people establish when they want to live and thrive together. A kind of social arrangements. Blockchain network is a community of programs that follow the same rules, and it’s this following the rules that makes the network alive. Similarly, when people share identical ideas, they become stronger and can together build a better life. If there are people that follow a different set of rules, they’ll live in a separate society (state, commune, etc.). Identically, if there’re blockchain nodes that follow different rules, they’ll form a separate network.

This is very important: without a network and without a majority of nodes sharing identical rules, these rules are useless!

DISCLAIMER: Unfortunately, I didn’t have enough time to implement a real P2P network prototype. In this article I’ll demonstrate a most common scenario, that involves nodes of different types. Improving this scenario and making this a P2P network can be a good challenge and practice for you! Also I cannot guarantee that other scenarios besides the one implemented in this article, will work. Sorry!

This part introduces significant code changes, so it makes no sense explaining all of them here. Please refer to this page to see all the changes since the last article.

Blockchain Network

Blockchain network is decentralized, which means there’re no servers that do stuff and clients that use servers to get or process data. In blockchain network there are nodes, and each node is a full-fledged member of the network. A node is everything: it’s both a client and a server. This is very important to keep in mind, because it’s very different from usual web applications.

Blockchain network is a P2P (Peer-to-Peer) network, which means that nodes are connected directly to each other. It’s topology is flat, since there are no hierarchy in node roles. Here its schematic representation:

(Business vector created by Dooder - Freepik.com)

Nodes in such network are more difficult to implement, because they have to perform a lot of operations. Each node must interact with multiple other nodes, it must request other node’s state, compare it with it’s own state, and update its state when it’s outdated.

Node Roles

Despite being full-fledged, blockchain nodes can play different roles in the network. Here they are:

  1. Miner.
    Such nodes are run on powerful or specialized hardware (like ASIC), and their only goal is to mine new blocks as fast as possible. Miners are only possible in blockchains that use Proof-of-Work, because mining actually means solving PoW puzzles. In Proof-of-Stake blockchains, for example, there’s no mining.
  2. Full node.
    These nodes validate blocks mined by miners and verify transactions. To do this, they must have the whole copy of blockchain. Also, such nodes perform such routing operations, like helping other nodes to discover each other.
    It’s very crucial for network to have many full nodes, because it’s these nodes that make decisions: they decide if a block or transaction is valid.
  3. SPV.
    SPV stands for Simplified Payment Verification. These nodes don’t store a full copy of blockchain, but they still able to verify transactions (not all of them, but a subset, for example, those that were sent to specific address). An SPV node depends on a full node to get data from, and there could be many SPV nodes connected to one full node. SPV makes wallet applications possible: one don’t need to download full blockchain, but still can verify their transactions.

Network simplification

To implement network in our blockchain, we have to simplify some things. The problem is that we don’t have many computers to simulate a network with multiple nodes. We could’ve used virtual machines or Docker to solve this problem, but it could make everything more difficult: you would have to solve possible virtual machine or Docker issues, while my goal is to concentrate on blockchain implementation only. So, we want to run multiple blockchain nodes on a single machine and at the same time we want them to have different addresses. To achieve this we’ll use ports as node identifiers, instead of IP addresses. E.g., there will be nodes with addresses: 127.0.0.1:3000127.0.0.1:3001127.0.0.1:3002, etc. We’ll call the port node ID and use NODE_IDenvironment variable to set them. Thus, you can open multiple terminal windows, set different NODE_IDs and have different nodes running.

This approach also requires having different blockchains and wallet files. They now must depend on the node ID and be named like blockchain_3000.dbblockchain_30001.db and wallet_3000.dbwallet_30001.db, etc.

Implementation

So, what happens when you download, say, Bitcoin Core and run it for the first time? It has to connect to some node to downloaded the latest state of the blockchain. Considering that your computer is not aware of all, or some, Bitcoin nodes, what’s this node?

Hardcoding a node address in Bitcoin Core would’ve been a mistake: the node could be attacked or shut down, which could result in new nodes not being able to join the network. Instead, in Bitcoin Core, there are DNS seeds hardcoded. These are not nodes, but DNS servers that know addresses of some nodes. When you start a clean Bitcoin Core, it’ll connect to one of the seeds and get a list of full nodes, which it’ll then download the blockchain from.

In our implementation, there will be centralization though. We’ll have three nodes:

  1. The central node. This is the node all other nodes will connect to, and this is the node that’ll sends data between other nodes.
  2. A miner node. This node will store new transactions in mempool and when there’re enough of transactions, it’ll mine a new block.
  3. A wallet node. This node will be used to send coins between wallets. Unlike SPV nodes though, it’ll store a full copy of blockchain.

The Scenario

The goal of this article is to implement the following scenario:

  1. The central node creates a blockchain.
  2. Other (wallet) node connects to it and downloads the blockchain.
  3. One more (miner) node connects to the central node and downloads the blockchain.
  4. The wallet node creates a transaction.
  5. The miner nodes receives the transaction and keeps it in its memory pool.
  6. When there are enough transactions in the memory pool, the miner starts mining a new block.
  7. When a new block is mined, it’s send to the central node.
  8. The wallet node synchronizes with the central node.
  9. User of the wallet node checks that their payment was successful.

This is what it looks like in Bitcoin. Even though we’re not going to build a real P2P network, we’re going to implement a real, and the main and most important, use case of Bitcoin.

version

Nodes communicate by the means of messages. When a new node is run, it gets several nodes from a DNS seed, and sends them version message, which in our implementation will look like this:

  1. type version struct {
  2. Version int
  3. BestHeight int
  4. AddrFrom string
  5. }

We have only one blockchain version, so the Version field won’t keep any important information. BestHeight stores the length of the node’s blockchain. AddFrom stores the address of the sender.

What should a node that receives a version message do? It’ll respond with its own version message. This is a kind of a handshake: no other interaction is possible without prior greeting of each other. But it’s not just politeness: version is used to find a longer blockchain. When a node receives a version message it checks if the node’s blockchain is longer than the value of BestHeight. If it’s not, the node will request and download missing blocks.

In order to receive message, we need a server:

  1. var nodeAddress string
  2. var knownNodes = []string{"localhost:3000"}
  3. func StartServer(nodeID, minerAddress string) {
  4. nodeAddress = fmt.Sprintf("localhost:%s", nodeID)
  5. miningAddress = minerAddress
  6. ln, err := net.Listen(protocol, nodeAddress)
  7. defer ln.Close()
  8. bc := NewBlockchain(nodeID)
  9. if nodeAddress != knownNodes[0] {
  10. sendVersion(knownNodes[0], bc)
  11. }
  12. for {
  13. conn, err := ln.Accept()
  14. go handleConnection(conn, bc)
  15. }
  16. }

First, we hardcode the address of the central node: every node must know where to connect to initially. minerAddress argument specifies the address to receive mining rewards to. This piece:

  1. if nodeAddress != knownNodes[0] {
  2. sendVersion(knownNodes[0], bc)
  3. }

Means that if current node is not the central one, it must send version message to the central node to find out if its blockchain is outdated.

  1. func sendVersion(addr string, bc *Blockchain) {
  2. bestHeight := bc.GetBestHeight()
  3. payload := gobEncode(version{nodeVersion, bestHeight, nodeAddress})
  4. request := append(commandToBytes("version"), payload...)
  5. sendData(addr, request)
  6. }

Our messages, on the lower level, are sequences of bytes. First 12 bytes specify command name (“version” in this case), and the latter bytes will contain gob-encoded message structure. commandToBytes looks like this:

  1. func commandToBytes(command string) []byte {
  2. var bytes [commandLength]byte
  3. for i, c := range command {
  4. bytes[i] = byte(c)
  5. }
  6. return bytes[:]
  7. }

It creates a 12-byte buffer and fills it with the command name, leaving rest bytes empty. There’s an opposite function:

  1. func bytesToCommand(bytes []byte) string {
  2. var command []byte
  3. for _, b := range bytes {
  4. if b != 0x0 {
  5. command = append(command, b)
  6. }
  7. }
  8. return fmt.Sprintf("%s", command)
  9. }

When a node receives a command, it runs bytesToCommand to extract command name and processes command body with correct handler:

  1. func handleConnection(conn net.Conn, bc *Blockchain) {
  2. request, err := ioutil.ReadAll(conn)
  3. command := bytesToCommand(request[:commandLength])
  4. fmt.Printf("Received %s command\n", command)
  5. switch command {
  6. ...
  7. case "version":
  8. handleVersion(request, bc)
  9. default:
  10. fmt.Println("Unknown command!")
  11. }
  12. conn.Close()
  13. }

Ok, this is what the version command handler looks like:

  1. func handleVersion(request []byte, bc *Blockchain) {
  2. var buff bytes.Buffer
  3. var payload verzion
  4. buff.Write(request[commandLength:])
  5. dec := gob.NewDecoder(&buff)
  6. err := dec.Decode(&payload)
  7. myBestHeight := bc.GetBestHeight()
  8. foreignerBestHeight := payload.BestHeight
  9. if myBestHeight < foreignerBestHeight {
  10. sendGetBlocks(payload.AddrFrom)
  11. } else if myBestHeight > foreignerBestHeight {
  12. sendVersion(payload.AddrFrom, bc)
  13. }
  14. if !nodeIsKnown(payload.AddrFrom) {
  15. knownNodes = append(knownNodes, payload.AddrFrom)
  16. }
  17. }

First, we need to decode the request and extract the payload. This is similar to all the handlers, so I’ll omit this piece in the future code snippets.

Then a node compares its BestHeight with the one from the message. If the node’s blockchain is longer, it’ll reply with version message; otherwise, it’ll send getblocksmessage.

getblocks

  1. type getblocks struct {
  2. AddrFrom string
  3. }

getblocks means “show me what blocks you have” (in Bitcoin, it’s more complex). Pay attention, it doesn’t say “give me all your blocks”, instead it requests a list of block hashes. This is done to reduce network load, because blocks can be downloaded from different nodes, and we don’t want to download dozens of gigabytes from one node.

Handling the command as easy as:

  1. func handleGetBlocks(request []byte, bc *Blockchain) {
  2. ...
  3. blocks := bc.GetBlockHashes()
  4. sendInv(payload.AddrFrom, "block", blocks)
  5. }

In our simplified implementation, it’ll return all block hashes.

inv

  1. type inv struct {
  2. AddrFrom string
  3. Type string
  4. Items [][]byte
  5. }

Bitcoin uses inv to show other nodes what blocks or transactions current node has. Again, it doesn’t contain whole blocks and transactions, just their hashes. The Type field says whether these are blocks or transactions.

Handling inv is more difficult:

  1. func handleInv(request []byte, bc *Blockchain) {
  2. ...
  3. fmt.Printf("Recevied inventory with %d %s\n", len(payload.Items), payload.Type)
  4. if payload.Type == "block" {
  5. blocksInTransit = payload.Items
  6. blockHash := payload.Items[0]
  7. sendGetData(payload.AddrFrom, "block", blockHash)
  8. newInTransit := [][]byte{}
  9. for _, b := range blocksInTransit {
  10. if bytes.Compare(b, blockHash) != 0 {
  11. newInTransit = append(newInTransit, b)
  12. }
  13. }
  14. blocksInTransit = newInTransit
  15. }
  16. if payload.Type == "tx" {
  17. txID := payload.Items[0]
  18. if mempool[hex.EncodeToString(txID)].ID == nil {
  19. sendGetData(payload.AddrFrom, "tx", txID)
  20. }
  21. }
  22. }

If blocks hashes are transferred, we want to save them in blocksInTransit variable to track downloaded blocks. This allows us to download blocks from different nodes. Right after putting blocks into the transit state, we send getdata command to the sender of the inv message and update blocksInTransit. In a real P2P network, we would want to transfer blocks from different nodes.

In our implementation, we’ll never send inv with multiple hashes. That’s why when payload.Type == "tx" only the first hash is taken. Then we check if we already have the hash in our mempool, and if not, getdata message is sent.

getdata

  1. type getdata struct {
  2. AddrFrom string
  3. Type string
  4. ID []byte
  5. }

getdata is a request for certain block or transaction, and it can contain only one block/transaction ID.

  1. func handleGetData(request []byte, bc *Blockchain) {
  2. ...
  3. if payload.Type == "block" {
  4. block, err := bc.GetBlock([]byte(payload.ID))
  5. sendBlock(payload.AddrFrom, &block)
  6. }
  7. if payload.Type == "tx" {
  8. txID := hex.EncodeToString(payload.ID)
  9. tx := mempool[txID]
  10. sendTx(payload.AddrFrom, &tx)
  11. }
  12. }

The handler is straightforward: if they request a block, return the block; if they request a transaction, return the transaction. Notice, that we don’t check if we actually have this block or transaction. This is a flaw :)

block and tx

  1. type block struct {
  2. AddrFrom string
  3. Block []byte
  4. }
  5. type tx struct {
  6. AddFrom string
  7. Transaction []byte
  8. }

It’s these messages that actually transfer the data.

Handling the block message is easy:

  1. func handleBlock(request []byte, bc *Blockchain) {
  2. ...
  3. blockData := payload.Block
  4. block := DeserializeBlock(blockData)
  5. fmt.Println("Recevied a new block!")
  6. bc.AddBlock(block)
  7. fmt.Printf("Added block %x\n", block.Hash)
  8. if len(blocksInTransit) > 0 {
  9. blockHash := blocksInTransit[0]
  10. sendGetData(payload.AddrFrom, "block", blockHash)
  11. blocksInTransit = blocksInTransit[1:]
  12. } else {
  13. UTXOSet := UTXOSet{bc}
  14. UTXOSet.Reindex()
  15. }
  16. }

When we received a new block, we put it into our blockchain. If there’re more blocks to download, we request them from the same node we downloaded the previous block. When we finally downloaded all the blocks, the UTXO set is reindexed.

TODO: Instead of trusting unconditionally, we should validate every incoming block before adding it to the blockchain.

TODO: Instead of running UTXOSet.Reindex(), UTXOSet.Update(block) should be used, because if blockchain is big, it’ll take a lot of time to reindex the whole UTXO set.

Handling tx messages is the most difficult part:

  1. func handleTx(request []byte, bc *Blockchain) {
  2. ...
  3. txData := payload.Transaction
  4. tx := DeserializeTransaction(txData)
  5. mempool[hex.EncodeToString(tx.ID)] = tx
  6. if nodeAddress == knownNodes[0] {
  7. for _, node := range knownNodes {
  8. if node != nodeAddress && node != payload.AddFrom {
  9. sendInv(node, "tx", [][]byte{tx.ID})
  10. }
  11. }
  12. } else {
  13. if len(mempool) >= 2 && len(miningAddress) > 0 {
  14. MineTransactions:
  15. var txs []*Transaction
  16. for id := range mempool {
  17. tx := mempool[id]
  18. if bc.VerifyTransaction(&tx) {
  19. txs = append(txs, &tx)
  20. }
  21. }
  22. if len(txs) == 0 {
  23. fmt.Println("All transactions are invalid! Waiting for new ones...")
  24. return
  25. }
  26. cbTx := NewCoinbaseTX(miningAddress, "")
  27. txs = append(txs, cbTx)
  28. newBlock := bc.MineBlock(txs)
  29. UTXOSet := UTXOSet{bc}
  30. UTXOSet.Reindex()
  31. fmt.Println("New block is mined!")
  32. for _, tx := range txs {
  33. txID := hex.EncodeToString(tx.ID)
  34. delete(mempool, txID)
  35. }
  36. for _, node := range knownNodes {
  37. if node != nodeAddress {
  38. sendInv(node, "block", [][]byte{newBlock.Hash})
  39. }
  40. }
  41. if len(mempool) > 0 {
  42. goto MineTransactions
  43. }
  44. }
  45. }
  46. }

First thing to do is to put new transaction in the mempool (again, transactions must be verified before being placed into the mempool). Next piece:

  1. if nodeAddress == knownNodes[0] {
  2. for _, node := range knownNodes {
  3. if node != nodeAddress && node != payload.AddFrom {
  4. sendInv(node, "tx", [][]byte{tx.ID})
  5. }
  6. }
  7. }

Checks whether the current node is the central one. In our implementation, the central node won’t mine blocks. Instead, it’ll forward the new transactions to other nodes in the network.

The next big piece is only for miner nodes. Let’s split it into smaller pieces:

if len(mempool) >= 2 && len(miningAddress) > 0 {

miningAddress is only set on miner nodes. When there are 2 or more transactions in the mempool of the current (miner) node, mining begins.

  1. for id := range mempool {
  2. tx := mempool[id]
  3. if bc.VerifyTransaction(&tx) {
  4. txs = append(txs, &tx)
  5. }
  6. }
  7. if len(txs) == 0 {
  8. fmt.Println("All transactions are invalid! Waiting for new ones...")
  9. return
  10. }

First, all transactions in the mempool are verified. Invalid transactions are ignored, and if there are no valid transactions, mining is interrupted.

  1. cbTx := NewCoinbaseTX(miningAddress, "")
  2. txs = append(txs, cbTx)
  3. newBlock := bc.MineBlock(txs)
  4. UTXOSet := UTXOSet{bc}
  5. UTXOSet.Reindex()
  6. fmt.Println("New block is mined!")

Verified transactions are being put into a block, as well as a coinbase transaction with the reward. After mining the block, the UTXO set is reindexed.

TODO: Again, UTXOSet.Update should be used instead of UTXOSet.Reindex

  1. for _, tx := range txs {
  2. txID := hex.EncodeToString(tx.ID)
  3. delete(mempool, txID)
  4. }
  5. for _, node := range knownNodes {
  6. if node != nodeAddress {
  7. sendInv(node, "block", [][]byte{newBlock.Hash})
  8. }
  9. }
  10. if len(mempool) > 0 {
  11. goto MineTransactions
  12. }

After a transaction is mined, it’s removed from the mempool. Every other nodes the current node is aware of, receive inv message with the new block’s hash. They can request the block after handling the message.

Result

Let’s play the scenario we defined earlier.

First, set NODE_ID to 3000 (export NODE_ID=3000) in the first terminal window. I’ll use badges like NODE 3000 or NODE 3001 before next paragraphs, for you to know what node to perform actions on.

NODE 3000
Create a wallet and a new blockchain:

  1. $ blockchain_go createblockchain -address CENTREAL_NODE

(I’ll use fake addresses for clarity and brevity)

After that, the blockchain will contain single genesis block. We need to save the block and use it in other nodes. Genesis blocks serve as identifiers of blockchains (in Bitcoin Core, the genesis block is hardcoded).

  1. $ cp blockchain_3000.db blockchain_genesis.db

NODE 3001
Next, open a new terminal window and set node ID to 3001. This will be a wallet node. Generate some addresses with blockchain_go createwallet, we’ll call these addresses WALLET_1WALLET_2WALLET_3.

NODE 3000
Send some coins to the wallet addresses:

  1. $ blockchain_go send -from CENTREAL_NODE -to WALLET_1 -amount 10 -mine
  2. $ blockchain_go send -from CENTREAL_NODE -to WALLET_2 -amount 10 -mine

-mine flag means that the block will be immediately mined by the same node. We have to have this flag because initially there are no miner nodes in the network.
Start the node:

  1. $ blockchain_go startnode

The node must be running until the end of the scenario.

NODE 3001
Start the node’s blockchain with the genesis block saved above:

  1. $ cp blockchain_genesis.db blockchain_3001.db

Run the node:

  1. $ blockchain_go startnode

It’ll download all the blocks from the central node. To check that everything’s ok, stop the node and check the balances:

  1. $ blockchain_go getbalance -address WALLET_1
  2. Balance of 'WALLET_1': 10
  3. $ blockchain_go getbalance -address WALLET_2
  4. Balance of 'WALLET_2': 10

Also, you can check the balance of the CENTRAL_NODE address, because the node 3001 now has its blockchain:

  1. $ blockchain_go getbalance -address CENTRAL_NODE
  2. Balance of 'CENTRAL_NODE': 10

NODE 3002
Open a new terminal window and set its ID to 3002, and generate a wallet. This will be a miner node. Initialize the blockchain:

  1. $ cp blockchain_genesis.db blockchain_3002.db

And start the node:

  1. $ blockchain_go startnode -miner MINER_WALLET

NODE 3001
Send some coins:

  1. $ blockchain_go send -from WALLET_1 -to WALLET_3 -amount 1
  2. $ blockchain_go send -from WALLET_2 -to WALLET_4 -amount 1

NODE 3002
Quickly! Switch to the miner node and see it mining a new block! Also, check the output of the central node.

NODE 3001
Switch to the wallet node and start it:

  1. $ blockchain_go startnode

It’ll download the newly mined block!

Stop it and check balances:

  1. $ blockchain_go getbalance -address WALLET_1
  2. Balance of 'WALLET_1': 9
  3. $ blockchain_go getbalance -address WALLET_2
  4. Balance of 'WALLET_2': 9
  5. $ blockchain_go getbalance -address WALLET_3
  6. Balance of 'WALLET_3': 1
  7. $ blockchain_go getbalance -address WALLET_4
  8. Balance of 'WALLET_4': 1
  9. $ blockchain_go getbalance -address MINER_WALLET
  10. Balance of 'MINER_WALLET': 10

That’s it!

Conclusion

This was the final part of the series. I could’ve publish some more posts implementing a real prototype of a P2P network, but I just don’t have time for this. I hope this article answers some of your questions about the Bitcoin technology and raises new ones, for which you can find answers yourself. There are more interesting things hidden in the Bitcoin technology! Good luck!

P.S. You can start improving the network with implementing the addr message, as described in the Bitcoin network protocol (link is below). This is a very important message, because it allows nodes to discover each other. I started implementing it, but haven’t finished!

Links:

  1. Source codes
  2. Bitcoin protocol documentation
  3. Bitcoin network
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1019796
推荐阅读
相关标签
  

闽ICP备14008679号