-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
509 lines (413 loc) · 11 KB
/
server.go
File metadata and controls
509 lines (413 loc) · 11 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package main
import (
"bytes"
"encoding/gob"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"net"
)
const protocol = "tcp"
const nodeVersion = 1
const commandLength = 12
var nodeAddress string
var miningAddress string
var knownNodes = []string{"localhost:3000"}
var blocksInTransit = [][]byte{}
var mempool = make(map[string]Transaction)
type addr struct {
AddrList []string
}
type block struct {
AddrFrom string
Block []byte
}
type getblocks struct {
AddrFrom string
}
type getdata struct {
AddrFrom string
Type string
ID []byte
}
/**
向其他节点展示当前节点有什么块和交易
它没有包含完整的区块链和交易,仅仅是哈希而已。
Type 字段表明了这是块还是交易。
*/
type inv struct {
AddrFrom string
Type string
Items [][]byte
}
type tx struct {
AddFrom string
Transaction []byte
}
/**
由于我们仅有一个区块链版本,所以 Version 字段实际并不会存储什么重要信息;
BestHeight 存储区块链中节点的高度;
AddFrom 存储发送者的地址.
*/
type verzion struct {
Version int
BestHeight int
AddrFrom string
}
//前 12 个字节指定了命令名
//将string型的命令转换成bytes型的
func commandToBytes(command string) []byte {
var bytes [commandLength]byte
for i, c := range command {
bytes[i] = byte(c)
}
return bytes[:]
}
//将命令bytes型的 转换成 string型的
func bytesToCommand(bytes []byte) string {
var command []byte
for _, b := range bytes {
if b != 0x0 {
command = append(command, b)
}
}
return fmt.Sprintf("%s", command)
}
func extractCommand(request []byte) []byte {
return request[:commandLength]
}
func requestBlocks() {
for _, node := range knownNodes {
sendGetBlocks(node)
}
}
func sendAddr(address string) {
nodes := addr{knownNodes}
nodes.AddrList = append(nodes.AddrList, nodeAddress)
payload := gobEncode(nodes)
request := append(commandToBytes("addr"), payload...)
sendData(address, request)
}
func sendBlock(addr string, b *Block) {
data := block{nodeAddress, b.Serialize()}
payload := gobEncode(data)
request := append(commandToBytes("block"), payload...)
sendData(addr, request)
}
//发送数据
func sendData(addr string, data []byte) {
conn, err := net.Dial(protocol, addr)
if err != nil {
fmt.Printf("%s is not available\n", addr)
fmt.Println("knownNodes 真的添加了新的节点信息了吗??")
var updatedNodes []string
for _, node := range knownNodes {
if node != addr {
updatedNodes = append(updatedNodes, node)
}
}
knownNodes = updatedNodes
fmt.Println("updatedNodes knownNodes is",knownNodes)
return
}
defer conn.Close()
_, err = io.Copy(conn, bytes.NewReader(data))
if err != nil {
log.Panic(err)
}
}
func sendInv(address, kind string, items [][]byte) {
inventory := inv{nodeAddress, kind, items}
payload := gobEncode(inventory)
request := append(commandToBytes("inv"), payload...)
sendData(address, request)
}
func sendGetBlocks(address string) {
payload := gobEncode(getblocks{nodeAddress})
request := append(commandToBytes("getblocks"), payload...)
sendData(address, request)
}
func sendGetData(address, kind string, id []byte) {
payload := gobEncode(getdata{nodeAddress, kind, id})
request := append(commandToBytes("getdata"), payload...)
sendData(address, request)
}
func sendTx(addr string, tnx *Transaction) {
data := tx{nodeAddress, tnx.Serialize()}
payload := gobEncode(data)
request := append(commandToBytes("tx"), payload...)
sendData(addr, request)
}
//请求 拉取最新的区块
func sendVersion(addr string, bc *Blockchain) {
bestHeight := bc.GetBestHeight()
payload := gobEncode(verzion{nodeVersion, bestHeight, nodeAddress})
request := append(commandToBytes("version"), payload...)
sendData(addr, request)
}
func handleAddr(request []byte) {
var buff bytes.Buffer
var payload addr
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
knownNodes = append(knownNodes, payload.AddrList...)
fmt.Printf("There are %d known nodes now!\n", len(knownNodes))
requestBlocks()
}
/**
当接收到一个新块时,我们把它放到区块链里面。
如果还有更多的区块需要下载,我们继续从上一个下载的块的那个节点继续请求。
当最后把所有块都下载完后,对 UTXO 集进行重新索引
*/
func handleBlock(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload block
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
blockData := payload.Block
block := DeserializeBlock(blockData)
fmt.Println("Recevied a new block!")
bc.AddBlock(block)
fmt.Printf("Added block %x\n", block.Hash)
if len(blocksInTransit) > 0 {
blockHash := blocksInTransit[0]
sendGetData(payload.AddrFrom, "block", blockHash)
blocksInTransit = blocksInTransit[1:]
} else {
UTXOSet := UTXOSet{bc}
UTXOSet.Reindex()
}
}
func handleInv(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload inv
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
fmt.Printf("Recevied inventory with %d %s\n", len(payload.Items), payload.Type)
if payload.Type == "block" {
blocksInTransit = payload.Items
blockHash := payload.Items[0]
sendGetData(payload.AddrFrom, "block", blockHash)
newInTransit := [][]byte{}
for _, b := range blocksInTransit {
if bytes.Compare(b, blockHash) != 0 {
newInTransit = append(newInTransit, b)
}
}
blocksInTransit = newInTransit
}
if payload.Type == "tx" {
txID := payload.Items[0]
if mempool[hex.EncodeToString(txID)].ID == nil {
sendGetData(payload.AddrFrom, "tx", txID)
}
}
}
func handleGetBlocks(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload getblocks
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
blocks := bc.GetBlockHashes()
sendInv(payload.AddrFrom, "block", blocks)
}
func handleGetData(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload getdata
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
if payload.Type == "block" {
block, err := bc.GetBlock([]byte(payload.ID))
if err != nil {
return
}
sendBlock(payload.AddrFrom, &block)
}
if payload.Type == "tx" {
txID := hex.EncodeToString(payload.ID)
tx := mempool[txID]
sendTx(payload.AddrFrom, &tx)
// delete(mempool, txID)
}
}
func handleTx(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload tx
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
txData := payload.Transaction
tx := DeserializeTransaction(txData)
//如果当前节点(矿工)的内存池中有两笔或更多的交易,开始挖矿
mempool[hex.EncodeToString(tx.ID)] = tx
//在我们的实现中,中心节点并不会挖矿。它只会将新的交易推送给网络中的其他节点。
if nodeAddress == knownNodes[0] {
for _, node := range knownNodes {
if node != nodeAddress && node != payload.AddFrom {
sendInv(node, "tx", [][]byte{tx.ID})
}
}
} else {
if len(mempool) >= 2 && len(miningAddress) > 0 {
MineTransactions:
var txs []*Transaction
for id := range mempool {
tx := mempool[id]
if bc.VerifyTransaction(&tx) {
txs = append(txs, &tx)
}
}
if len(txs) == 0 {
fmt.Println("All transactions are invalid! Waiting for new ones...")
return
}
cbTx := NewCoinbaseTX(miningAddress, "")
txs = append(txs, cbTx)
newBlock := bc.MineBlock(txs)
UTXOSet := UTXOSet{bc}
UTXOSet.Reindex()
fmt.Println("New block is mined!")
fmt.Println("I want to know allAddress is ",knownNodes)
for _, tx := range txs {
txID := hex.EncodeToString(tx.ID)
delete(mempool, txID)
}
for _, node := range knownNodes {
if node != nodeAddress {
sendInv(node, "block", [][]byte{newBlock.Hash})
}
}
if len(mempool) > 0 {
goto MineTransactions
}
}
}
}
//gob,由发送端使用Encoder对数据结构进行编码。
//在接收端收到消息之后,接收端使用Decoder将序列化的数据变化成本地变量。
/**
节点将从消息中提取的 BestHeight 与自身进行比较。
如果自身节点的区块链更长,它会回复 version 消息;
否则,它会发送 getblocks 消息
*/
func handleVersion(request []byte, bc *Blockchain) {
var buff bytes.Buffer
var payload verzion
//net.write向服务端发送请求数据???
buff.Write(request[commandLength:])
dec := gob.NewDecoder(&buff)
err := dec.Decode(&payload)
if err != nil {
log.Panic(err)
}
myBestHeight := bc.GetBestHeight()
foreignerBestHeight := payload.BestHeight
if myBestHeight < foreignerBestHeight {
sendGetBlocks(payload.AddrFrom)
} else if myBestHeight > foreignerBestHeight {
sendVersion(payload.AddrFrom, bc)
}
// sendAddr(payload.AddrFrom)
if !nodeIsKnown(payload.AddrFrom) {
knownNodes = append(knownNodes, payload.AddrFrom)
}
}
/**
当一个节点接收到一个命令,它会运行 bytesToCommand 来提取命令名,并选择正确的处理器处理命令主体
*/
func handleConnection(conn net.Conn, bc *Blockchain) {
request, err := ioutil.ReadAll(conn)
if err != nil {
log.Panic(err)
}
command := bytesToCommand(request[:commandLength])
fmt.Printf("Received %s command\n", command)
switch command {
case "addr":
handleAddr(request)
case "block":
handleBlock(request, bc)
case "inv":
handleInv(request, bc)
case "getblocks":
handleGetBlocks(request, bc)
case "getdata":
handleGetData(request, bc)
case "tx":
handleTx(request, bc)
case "version":
handleVersion(request, bc)
default:
fmt.Println("Unknown command!")
}
conn.Close()
}
// StartServer starts a node 接收消息,开启一个服务器
//minerAddress 参数指定了接收挖矿奖励的地址
func StartServer(nodeID, minerAddress string) {
nodeAddress = fmt.Sprintf("localhost:%s", nodeID)
fmt.Print("Listen ID is " + nodeAddress)
fmt.Print("\n")
miningAddress = minerAddress
ln, err := net.Listen(protocol, nodeAddress)
if err != nil {
log.Panic(err)
}
defer ln.Close()
bc := NewBlockchain(nodeID)
//对中心节点的地址进行硬编码
//如果当前节点不是中心节点,它必须向中心节点发送 version 消息来查询是否自己的区块链已过时
fmt.Println("knownNodes is ",knownNodes)
if nodeAddress != knownNodes[0] {
sendVersion(knownNodes[0], bc)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Panic(err)
}
go handleConnection(conn, bc)
}
}
func gobEncode(data interface{}) []byte {
var buff bytes.Buffer
enc := gob.NewEncoder(&buff)
err := enc.Encode(data)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
}
func nodeIsKnown(addr string) bool {
for _, node := range knownNodes {
if node == addr {
return true
}
}
return false
}