-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathhandler.go
171 lines (140 loc) · 4.38 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package gochain
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
func NewHandler(blockchain *Blockchain, nodeID string) http.Handler {
h := handler{blockchain, nodeID}
mux := http.NewServeMux()
mux.HandleFunc("/nodes/register", buildResponse(h.RegisterNode))
mux.HandleFunc("/nodes/resolve", buildResponse(h.ResolveConflicts))
mux.HandleFunc("/transactions/new", buildResponse(h.AddTransaction))
mux.HandleFunc("/mine", buildResponse(h.Mine))
mux.HandleFunc("/chain", buildResponse(h.Blockchain))
return mux
}
type handler struct {
blockchain *Blockchain
nodeId string
}
type response struct {
value interface{}
statusCode int
err error
}
func buildResponse(h func(io.Writer, *http.Request) response) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp := h(w, r)
msg := resp.value
if resp.err != nil {
msg = resp.err.Error()
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(resp.statusCode)
if err := json.NewEncoder(w).Encode(msg); err != nil {
log.Printf("could not encode response to output: %v", err)
}
}
}
func (h *handler) AddTransaction(w io.Writer, r *http.Request) response {
if r.Method != http.MethodPost {
return response{
nil,
http.StatusMethodNotAllowed,
fmt.Errorf("method %s not allowd", r.Method),
}
}
log.Printf("Adding transaction to the blockchain...\n")
var tx Transaction
err := json.NewDecoder(r.Body).Decode(&tx)
index := h.blockchain.NewTransaction(tx)
resp := map[string]string{
"message": fmt.Sprintf("Transaction will be added to Block %d", index),
}
status := http.StatusCreated
if err != nil {
status = http.StatusInternalServerError
log.Printf("there was an error when trying to add a transaction %v\n", err)
err = fmt.Errorf("fail to add transaction to the blockchain")
}
return response{resp, status, err}
}
func (h *handler) Mine(w io.Writer, r *http.Request) response {
if r.Method != http.MethodGet {
return response{
nil,
http.StatusMethodNotAllowed,
fmt.Errorf("method %s not allowd", r.Method),
}
}
log.Println("Mining some coins")
// We run the proof of work algorithm to get the next proof...
lastBlock := h.blockchain.LastBlock()
lastProof := lastBlock.Proof
proof := h.blockchain.ProofOfWork(lastProof)
// We must receive a reward for finding the proof.
// The sender is "0" to signify that this node has mined a new coin.
newTX := Transaction{Sender: "0", Recipient: h.nodeId, Amount: 1}
h.blockchain.NewTransaction(newTX)
// Forge the new Block by adding it to the chain
block := h.blockchain.NewBlock(proof, "")
resp := map[string]interface{}{"message": "New Block Forged", "block": block}
return response{resp, http.StatusOK, nil}
}
func (h *handler) Blockchain(w io.Writer, r *http.Request) response {
if r.Method != http.MethodGet {
return response{
nil,
http.StatusMethodNotAllowed,
fmt.Errorf("method %s not allowd", r.Method),
}
}
log.Println("Blockchain requested")
resp := map[string]interface{}{"chain": h.blockchain.chain, "length": len(h.blockchain.chain)}
return response{resp, http.StatusOK, nil}
}
func (h *handler) RegisterNode(w io.Writer, r *http.Request) response {
if r.Method != http.MethodPost {
return response{
nil,
http.StatusMethodNotAllowed,
fmt.Errorf("method %s not allowd", r.Method),
}
}
log.Println("Adding node to the blockchain")
var body map[string][]string
err := json.NewDecoder(r.Body).Decode(&body)
for _, node := range body["nodes"] {
h.blockchain.RegisterNode(node)
}
resp := map[string]interface{}{
"message": "New nodes have been added",
"nodes": h.blockchain.nodes.Keys(),
}
status := http.StatusCreated
if err != nil {
status = http.StatusInternalServerError
err = fmt.Errorf("fail to register nodes")
log.Printf("there was an error when trying to register a new node %v\n", err)
}
return response{resp, status, err}
}
func (h *handler) ResolveConflicts(w io.Writer, r *http.Request) response {
if r.Method != http.MethodGet {
return response{
nil,
http.StatusMethodNotAllowed,
fmt.Errorf("method %s not allowd", r.Method),
}
}
log.Println("Resolving blockchain differences by consensus")
msg := "Our chain is authoritative"
if h.blockchain.ResolveConflicts() {
msg = "Our chain was replaced"
}
resp := map[string]interface{}{"message": msg, "chain": h.blockchain.chain}
return response{resp, http.StatusOK, nil}
}