-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.go
292 lines (251 loc) · 8.93 KB
/
handlers.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/grrrben/glog"
)
func (a *App) index(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusOK, "Hello world")
}
// wallet Shows some stats of a wallet, including the credits available
func (a *App) wallet(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hash := vars["hash"]
resp := map[string]interface{}{
"success": true,
"credit": getWalletCredits(hash),
}
respondWithJSON(w, http.StatusOK, resp)
}
// transactions shows all transactions made by a wallet with {hash}
// {hash} is given by POST data from the call
func (a *App) transactions(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hash := vars["hash"]
transactions := []Transaction{}
// check all blocks, see if the hash is the sender or receiver.
for _, block := range bc.Chain {
for _, transaction := range block.Transactions {
if transaction.Sender == hash || transaction.Recipient == hash {
transactions = append(transactions, transaction)
}
}
}
respondWithJSON(w, http.StatusOK, transactions)
}
// currentTransactions shows all transactions that are not in a block yet
func (a *App) currentTransactions(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusOK, bc.Transactions)
}
// distributedTransaction receives a transaction from another node in the network.
// It is used to distribute the _unmined_ transactions throughout the network
func (a *App) distributedTransaction(w http.ResponseWriter, r *http.Request) {
defer glog.Flush()
glog.Infof("starting distributedTransaction on Node: %s", me.getAddress())
type Payload struct {
Transaction Transaction `json:"transaction"`
Sender string `json:"sender"`
}
var payload Payload
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
glog.Warningf("Invalid Transaction (Unable to decode) on Node: %s", me.getAddress())
respondWithError(w, http.StatusUnprocessableEntity, "Invalid Transaction (Unable to decode)")
} else {
glog.Infof("payload: %v", payload)
if bc.isNonExistingTransaction(payload.Transaction) {
glog.Infof("transaction: %v", payload.Transaction)
_, err = bc.newTransaction(payload.Transaction)
if err != nil {
glog.Warningf("%s on Node: %s", err, me.getAddress())
respondWithError(w, http.StatusUnprocessableEntity, err.Error())
} else {
glog.Infof("Transaction added on Node: %s", me.getAddress())
respondWithJSON(w, http.StatusOK, "Transaction added")
}
} else {
glog.Warningf("Invalid Transaction (Already exists) on Node: %s", me.getAddress())
respondWithError(w, http.StatusUnprocessableEntity, "Invalid Transaction (Already exists)")
}
}
}
// newTransaction adds a transaction, which consists of:
// Sender string
// Recipient string
// Amount float32
func (a *App) newTransaction(w http.ResponseWriter, r *http.Request) {
var tr Transaction
err := json.NewDecoder(r.Body).Decode(&tr)
if err != nil {
glog.Warningf("Invalid Transaction (%s)", err)
respondWithError(w, http.StatusUnprocessableEntity, "Invalid Transaction (Unable to decode)")
} else {
// for a new transaction, time should be added by the system
tr.Time = 0
addedTransaction, err := bc.newTransaction(tr)
if err != nil {
respondWithError(w, http.StatusUnprocessableEntity, err.Error())
} else {
// all OK. Add the transaction and distribute it.
nodes.distributeTransaction(addedTransaction) // distribution
respondWithJSON(w, http.StatusOK, "Transaction added")
}
}
}
// distributedBlock is a receiver for blocks mined by other nodes.
// It catches the newly mined block and checks for validity on his own chain
// If it is valid the block is added and a statusOk is returned.
// Otherwise it gives an error
func (a *App) distributedBlock(w http.ResponseWriter, r *http.Request) {
// fetching the block that came with the request
decoder := json.NewDecoder(r.Body)
type Payload struct {
NewBlock Block `json:"block"`
Sender string `json:"sender"`
}
var payload Payload
err := decoder.Decode(&payload)
if err != nil {
glog.Errorf("Could not decode postdata of new block; %s", err.Error())
respondWithError(w, http.StatusBadRequest, "invalid json")
}
block, err := bc.addBlock(payload.NewBlock)
if err == nil {
bc.clearTransactions(block.Transactions)
resp := map[string]interface{}{
"success": true,
"message": "New block added",
}
respondWithJSON(w, http.StatusOK, resp)
} else {
repair := bc.analyseInvalidBlock(payload.NewBlock, payload.Sender)
if repair == false {
// better resolve..?
respondWithError(w, http.StatusConflict, "Invalid block")
} else {
resp := map[string]interface{}{
"success": true,
"message": "New blocks added",
}
respondWithJSON(w, http.StatusOK, resp)
}
}
}
// resolve Resolving conflict between chains in the network
func (a *App) resolve(w http.ResponseWriter, r *http.Request) {
resolved := bc.resolve()
respondWithJSON(w, http.StatusOK, resolved)
}
// lastblock Serves single block
func (a *App) lastblock(w http.ResponseWriter, r *http.Request) {
block := bc.Chain[len(bc.Chain)-1]
resp := map[string]interface{}{"success": true, "block": block}
respondWithJSON(w, http.StatusOK, resp)
}
// block Serves single block identified by it's hash
func (a *App) block(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hash := vars["hash"]
found := false
for _, bl := range bc.Chain {
if bl.PreviousHash == hash {
found = true
resp := map[string]interface{}{"success": true, "block": bl}
respondWithJSON(w, http.StatusOK, resp)
}
break
}
if found == false {
respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Could not find block by hash %s", hash))
}
}
// blockByIndex Serves single block identified by it's index
func (a *App) blockByIndex(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
rawIndex := vars["index"]
index, err := strconv.ParseInt(rawIndex, 10, 16) // always gives an int64...
if err != nil {
glog.Errorf("Unable to cast block Index %s to int: %s", rawIndex, err)
}
found := false
for _, bl := range bc.Chain {
if bl.Index == index {
found = true
resp := map[string]interface{}{"success": true, "block": bl}
respondWithJSON(w, http.StatusOK, resp)
}
break
}
if !found {
respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Could not find block by index %d", index))
}
}
// chainStatus tells about the lenght and last hash of the chain.
func (a *App) chainStatus(w http.ResponseWriter, r *http.Request) {
hash := bc.Chain[len(bc.Chain)-1].PreviousHash
resp := map[string]interface{}{"length": len(bc.Chain), "hash": hash}
respondWithJSON(w, http.StatusOK, resp)
}
// connectNode Connect a Node to the network which is represented
// in the Nodes.list The postdata should consist of a standard Node
func (a *App) connectNode(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var newCl Node
err := decoder.Decode(&newCl)
if err != nil {
respondWithError(w, http.StatusBadRequest, "invalid json")
glog.Panicf("Could not decode postdata of new node; %s", err.Error())
}
// register the node
added := nodes.addNode(&newCl)
if added {
resp := map[string]interface{}{"Node": newCl, "total": nodes.num()}
respondWithJSON(w, http.StatusOK, resp)
} else {
respondWithError(w, http.StatusConflict, "Node could not be added")
}
}
// getNodes response is the list of Nodes
func (a *App) getNodes(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{"list": nodes.List, "length": len(nodes.List)}
respondWithJSON(w, http.StatusOK, resp)
}
// chain shows the entire blockchain
func (a *App) chain(w http.ResponseWriter, r *http.Request) {
resp := map[string]interface{}{"chain": bc.Chain, "transactions": bc.Transactions, "length": len(bc.Chain)}
respondWithJSON(w, http.StatusOK, resp)
}
// validate checks the entire blockchain
func (a *App) validate(w http.ResponseWriter, r *http.Request) {
isValid := bc.validate()
resp := map[string]interface{}{"valid": isValid, "length": len(bc.Chain)}
respondWithJSON(w, http.StatusOK, resp)
}
// mine Mines a block and puts all transactions in the block
// An incentive is paid to the miner and the list of transactions is cleared
func (a *App) mine(w http.ResponseWriter, r *http.Request) {
block, err := bc.mine()
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
} else {
resp := map[string]interface{}{
"message": "New block mined.",
"Block": block,
"length": len(bc.Chain),
"transactions": len(block.Transactions),
}
respondWithJSON(w, http.StatusOK, resp)
}
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}