diff --git a/core/Block.go b/core/Block.go index 9d059fb..9946f48 100644 --- a/core/Block.go +++ b/core/Block.go @@ -32,3 +32,7 @@ func (block *Block) Hash() string { func (block *Block) AsJSON() JSONBlock { return JSONBlock{Timestamp: block.Timestamp, Hash: block.Hash(), PreviousHash: block.PreviousHash, Data: block.Data, Proof: block.Proof} } + +func (block *JSONBlock) FromJSON() Block { + return Block{Timestamp: block.Timestamp, PreviousHash: block.PreviousHash, Data: block.Data, Proof: block.Proof} +} diff --git a/core/Blockchain.go b/core/Blockchain.go index 2e6ac7a..ea3b430 100644 --- a/core/Blockchain.go +++ b/core/Blockchain.go @@ -1,6 +1,7 @@ package core import ( + "encoding/json" "log" "net/http" "strings" @@ -100,6 +101,34 @@ func (bc *Blockchain) IsValid() bool { return true } +func (bc *Blockchain) Update() bool { + + var hasBeenReplaced = false + + for _, peer := range bc.Peers { + resp, err := http.Get("http://" + peer) + + decoder := json.NewDecoder(resp.Body) + var receivedBlockchain JSONBlockchain + err = decoder.Decode(&receivedBlockchain) + if err == nil { + if receivedBlockchain.Blockcount > bc.AsJSON().Blockcount { + + newBlocks := make([]Block, 0) + for _, block := range receivedBlockchain.Blocks { + newBlocks = append(newBlocks, block.FromJSON()) + } + + bc.Blocks = newBlocks + + log.Println("Blockchain has been updated by " + peer) + hasBeenReplaced = true + } + } + } + return hasBeenReplaced +} + // JSONBlockchain is needed, because the hash of each block is calculated dynamically, and therefore is not stored in the `Block` struct type JSONBlockchain struct { Blocks []JSONBlock diff --git a/server/webserver.go b/server/webserver.go index eac4632..659bd06 100644 --- a/server/webserver.go +++ b/server/webserver.go @@ -33,6 +33,7 @@ func registerRouteHandlers() { http.HandleFunc("/pending_transactions", handleListPendingTransactions) http.HandleFunc("/add_transaction", handleAddTransaction) http.HandleFunc("/is_valid", handleIsValid) + http.HandleFunc("/update", handleUpdate) http.HandleFunc("/add_peers", handleAddPeers) } @@ -91,5 +92,8 @@ func handleAddPeers(w http.ResponseWriter, r *http.Request) { } json.NewEncoder(w).Encode(blockchain.Peers) +} +func handleUpdate(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(blockchain.Update()) }