-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
80 lines (64 loc) · 1.72 KB
/
server.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
package main
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"net"
)
const protocol = "tcp"
const nodeVersion = 1
const commandLength = 12
var nodeAddr string
var miningAddress string // the mining reward payee
var knownNodes = []string{"localhost:3000"} // central node
var blocksInTransit = [][]byte{} // a block hash set waiting to be downloaded
var mempool = make(map[string]Transaction)
// StartServer starts a node to connect network
// `nodeID`: constructing IP address "localhost:`nodeID`"
// `minerAddress` : the address to received mining rewards to
func StartServer(nodeID, minerAddress string) {
nodeAddr = fmt.Sprintf("localhost:%s", nodeID)
miningAddress = minerAddress
ln, err := net.Listen(protocol, nodeAddr)
logErr(err)
defer ln.Close()
bc := NewBlockchain(nodeID)
// If current node is not central node, then send `version` message to
// central node to know if its blockchain is outdated
if nodeAddr != knownNodes[0] {
sendVersion(knownNodes[0], bc)
}
for {
conn, err := ln.Accept()
//logErr(err)
go handleConnection(conn, bc)
}
}
// commandToBytes converts `command` into a 12-byte buffer
func commandToBytes(command string) []byte {
var bytes [commandLength]byte
for i, c := range command {
bytes[i] = byte(c)
}
return bytes[:]
}
// bytesToCommand converts 12-byte buffer `bytes` into command 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 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()
}