Skip to content

Commit e26eeb1

Browse files
committed
added consensus mechanism
1 parent 266f50b commit e26eeb1

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

block/blockchain.go

+10
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ func (bc *Blockchain) Chain() []*Block {
131131

132132
func (bc *Blockchain) Run() {
133133
bc.StartSyncNeighbors()
134+
bc.ResolveConflicts()
134135
}
135136

136137
func (bc *Blockchain) SetNeighbors() {
@@ -301,6 +302,15 @@ func (bc *Blockchain) Mining() bool {
301302
previousHash := bc.LastBlock().Hash()
302303
bc.CreateBlock(nonce, previousHash)
303304
log.Println("action=mining, status=success")
305+
306+
for _, n := range bc.neighbors {
307+
endpoint := fmt.Sprintf("http://%s/consensus", n)
308+
client := &http.Client{}
309+
req, _ := http.NewRequest("PUT", endpoint, nil)
310+
resp, _ := client.Do(req)
311+
log.Printf("%v", resp)
312+
}
313+
304314
return true
305315
}
306316

blockchain_server/blockchain_server.go

+19
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,24 @@ func (bcs *BlockchainServer) Amount(w http.ResponseWriter, req *http.Request) {
189189
}
190190
}
191191

192+
func (bcs *BlockchainServer) Consensus(w http.ResponseWriter, req *http.Request) {
193+
switch req.Method {
194+
case http.MethodPut:
195+
bc := bcs.GetBlockchain()
196+
replaced := bc.ResolveConflicts()
197+
198+
w.Header().Add("Content-Type", "application/json")
199+
if replaced {
200+
io.WriteString(w, string(utils.JsonStatus("success")))
201+
} else {
202+
io.WriteString(w, string(utils.JsonStatus("fail")))
203+
}
204+
default:
205+
log.Printf("ERROR: Invalid HTTP Method")
206+
w.WriteHeader(http.StatusBadRequest)
207+
}
208+
}
209+
192210
func (bcs *BlockchainServer) Run() {
193211
bcs.GetBlockchain().Run()
194212

@@ -197,5 +215,6 @@ func (bcs *BlockchainServer) Run() {
197215
http.HandleFunc("/mine", bcs.Mine)
198216
http.HandleFunc("/mine/start", bcs.StartMine)
199217
http.HandleFunc("/amount", bcs.Amount)
218+
http.HandleFunc("/consensus", bcs.Consensus)
200219
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(bcs.Port())), nil))
201220
}

0 commit comments

Comments
 (0)