Browse Source

Add Update Chain Method

pull/9/head
garritfra 5 years ago
parent
commit
5ffd1c5de6
  1. 4
      core/Block.go
  2. 29
      core/Blockchain.go
  3. 4
      server/webserver.go

4
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}
}

29
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

4
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())
}

Loading…
Cancel
Save