-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
315 lines (244 loc) · 8.25 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
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
/*
Implements an example server for the BlockArt project, to be used in
project 1 of UBC CS 416 2017W2.
This server takes in settings from an input json files and implements
a simple strategy for GetNodes: return a fixed number of random miners
("num-miner-to-return" in the json config file).
Usage:
$ go run server.go
-c string
Path to the JSON config
*/
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/gob"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"net/rpc"
"os"
"sort"
"sync"
"time"
)
// Errors that the server could return.
type UnknownKeyError error
type KeyAlreadyRegisteredError string
func (e KeyAlreadyRegisteredError) Error() string {
return fmt.Sprintf("BlockArt server: key already registered [%s]", string(e))
}
type AddressAlreadyRegisteredError string
func (e AddressAlreadyRegisteredError) Error() string {
return fmt.Sprintf("BlockArt server: address already registered [%s]", string(e))
}
// Settings for a canvas in BlockArt.
type CanvasSettings struct {
// Canvas dimensions
CanvasXMax uint32 `json:"canvas-x-max"`
CanvasYMax uint32 `json:"canvas-y-max"`
}
type MinerSettings struct {
// Hash of the very first (empty) block in the chain.
GenesisBlockHash string `json:"genesis-block-hash"`
// The minimum number of ink miners that an ink miner should be
// connected to.
MinNumMinerConnections uint8 `json:"min-num-miner-connections"`
// Mining ink reward per op and no-op blocks (>= 1)
InkPerOpBlock uint32 `json:"ink-per-op-block"`
InkPerNoOpBlock uint32 `json:"ink-per-no-op-block"`
// Number of milliseconds between heartbeat messages to the server.
HeartBeat uint32 `json:"heartbeat"`
// Proof of work difficulty: number of zeroes in prefix (>=0)
PoWDifficultyOpBlock uint8 `json:"pow-difficulty-op-block"`
PoWDifficultyNoOpBlock uint8 `json:"pow-difficulty-no-op-block"`
}
// Settings for an instance of the BlockArt project/network.
type MinerNetSettings struct {
// Hash of the very first (empty) block in the chain.
GenesisBlockHash string `json:"genesis-block-hash"`
// The minimum number of ink miners that an ink miner should be
// connected to.
MinNumMinerConnections uint8 `json:"min-num-miner-connections"`
// Mining ink reward per op and no-op blocks (>= 1)
InkPerOpBlock uint32 `json:"ink-per-op-block"`
InkPerNoOpBlock uint32 `json:"ink-per-no-op-block"`
// Number of milliseconds between heartbeat messages to the server.
HeartBeat uint32 `json:"heartbeat"`
// Proof of work difficulty: number of zeroes in prefix (>=0)
PoWDifficultyOpBlock uint8 `json:"pow-difficulty-op-block"`
PoWDifficultyNoOpBlock uint8 `json:"pow-difficulty-no-op-block"`
// Canvas settings
CanvasSettings CanvasSettings `json:"canvas-settings"`
}
type RServer int
type Miner struct {
Address net.Addr
RecentHeartbeat int64
}
type Config struct {
MinerSettings MinerNetSettings `json:"miner-settings"`
RpcIpPort string `json:"rpc-ip-port"`
NumMinerToReturn uint8 `json:"num-miner-to-return"`
}
type AllMiners struct {
sync.RWMutex
all map[string]*Miner
}
var (
unknownKeyError UnknownKeyError = errors.New("BlockArt server: unknown key")
config Config
errLog *log.Logger = log.New(os.Stderr, "[serv] ", log.Lshortfile|log.LUTC|log.Lmicroseconds)
outLog *log.Logger = log.New(os.Stderr, "[serv] ", log.Lshortfile|log.LUTC|log.Lmicroseconds)
// Miners in the system.
allMiners AllMiners = AllMiners{all: make(map[string]*Miner)}
)
func readConfigOrDie(path string) {
file, err := os.Open(path)
handleErrorFatal("config file", err)
buffer, err := ioutil.ReadAll(file)
handleErrorFatal("read config", err)
err = json.Unmarshal(buffer, &config)
handleErrorFatal("parse config", err)
}
// Parses args, setups up RPC server.
func main() {
gob.Register(&net.TCPAddr{})
gob.Register(&elliptic.CurveParams{})
path := flag.String("c", "", "Path to the JSON config")
flag.Parse()
if *path == "" {
flag.PrintDefaults()
os.Exit(1)
}
readConfigOrDie(*path)
rand.Seed(time.Now().UnixNano())
rserver := new(RServer)
server := rpc.NewServer()
server.Register(rserver)
l, e := net.Listen("tcp", config.RpcIpPort)
handleErrorFatal("listen error", e)
outLog.Printf("Server started. Receiving on %s\n", config.RpcIpPort)
for {
conn, _ := l.Accept()
go server.ServeConn(conn)
}
}
type MinerInfo struct {
Address net.Addr
Key ecdsa.PublicKey
}
// Function to delete dead miners (no recent heartbeat)
func monitor(k string, heartBeatInterval time.Duration) {
for {
allMiners.Lock()
if time.Now().UnixNano()-allMiners.all[k].RecentHeartbeat > int64(heartBeatInterval*100) {
outLog.Printf("%s timed out\n", allMiners.all[k].Address.String())
delete(allMiners.all, k)
allMiners.Unlock()
return
}
// outLog.Printf("%s is alive\n", allMiners.all[k].Address.String())
allMiners.Unlock()
time.Sleep(heartBeatInterval)
}
}
func pubKeyToString(key ecdsa.PublicKey) string {
return string(elliptic.Marshal(key.Curve, key.X, key.Y))
}
// Registers a new miner with an address for other miner to use to
// connect to it (returned in GetNodes call below), and a
// public-key for this miner. Returns error, or if error is not set,
// then setting for this canvas instance.
//
// Returns:
// - AddressAlreadyRegisteredError if the server has already registered this address.
// - KeyAlreadyRegisteredError if the server already has a registration record for publicKey.
func (s *RServer) Register(m MinerInfo, r *MinerNetSettings) error {
allMiners.Lock()
defer allMiners.Unlock()
k := pubKeyToString(m.Key)
if miner, exists := allMiners.all[k]; exists {
return KeyAlreadyRegisteredError(miner.Address.String())
}
for _, miner := range allMiners.all {
if miner.Address.Network() == m.Address.Network() && miner.Address.String() == m.Address.String() {
return AddressAlreadyRegisteredError(m.Address.String())
}
}
allMiners.all[k] = &Miner{
m.Address,
time.Now().UnixNano(),
}
go monitor(k, time.Duration(config.MinerSettings.HeartBeat)*time.Millisecond)
*r = config.MinerSettings
outLog.Printf("Got Register from %s\n", m.Address.String())
return nil
}
type Addresses []net.Addr
func (a Addresses) Len() int { return len(a) }
func (a Addresses) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Addresses) Less(i, j int) bool { return a[i].String() < a[j].String() }
// Returns addresses for a subset of miners in the system.
//
// Returns:
// - UnknownKeyError if the server does not know a miner with this publicKey.
func (s *RServer) GetNodes(key ecdsa.PublicKey, addrSet *[]net.Addr) error {
// TODO: validate miner's GetNodes protocol? (could monitor state
// of network graph/connectivity and validate protocol FSM)
allMiners.RLock()
defer allMiners.RUnlock()
k := pubKeyToString(key)
if _, ok := allMiners.all[k]; !ok {
return unknownKeyError
}
minerAddresses := make([]net.Addr, 0, len(allMiners.all)-1)
for pubKey, miner := range allMiners.all {
if pubKey == k {
continue
}
minerAddresses = append(minerAddresses, miner.Address)
}
sort.Sort(Addresses(minerAddresses))
deterministicRandomNumber := key.X.Int64() % 32
r := rand.New(rand.NewSource(deterministicRandomNumber))
for n := len(minerAddresses); n > 0; n-- {
randIndex := r.Intn(n)
minerAddresses[n-1], minerAddresses[randIndex] = minerAddresses[randIndex], minerAddresses[n-1]
}
n := len(minerAddresses)
if int(config.NumMinerToReturn) < n {
n = int(config.NumMinerToReturn)
}
*addrSet = minerAddresses[:n]
return nil
}
// The server also listens for heartbeats from known miners. A miner must
// send a heartbeat to the server every HeartBeat milliseconds
// (specified in settings from server) after calling Register, otherwise
// the server will stop returning this miner's address/key to other
// miners.
//
// Returns:
// - UnknownKeyError if the server does not know a miner with this publicKey.
func (s *RServer) HeartBeat(key ecdsa.PublicKey, _ignored *bool) error {
allMiners.Lock()
defer allMiners.Unlock()
k := pubKeyToString(key)
if _, ok := allMiners.all[k]; !ok {
return unknownKeyError
}
allMiners.all[k].RecentHeartbeat = time.Now().UnixNano()
return nil
}
func handleErrorFatal(msg string, e error) {
if e != nil {
errLog.Fatalf("%s, err = %s\n", msg, e.Error())
}
}