-
Notifications
You must be signed in to change notification settings - Fork 17
/
netmap_contract.go
540 lines (424 loc) · 11.2 KB
/
netmap_contract.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package netmapcontract
import (
"github.com/nspcc-dev/neo-go/pkg/interop/binary"
"github.com/nspcc-dev/neo-go/pkg/interop/blockchain"
"github.com/nspcc-dev/neo-go/pkg/interop/crypto"
"github.com/nspcc-dev/neo-go/pkg/interop/iterator"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
"github.com/nspcc-dev/neo-go/pkg/interop/util"
)
type (
irNode struct {
key []byte
}
storageNode struct {
info []byte
}
ballot struct {
id []byte // id of the voting decision
n [][]byte // already voted inner ring nodes
block int // block with the last vote
}
netmapNode struct {
node storageNode
state nodeState
}
nodeState int
record struct {
key []byte
val []byte
}
)
const (
version = 1
blockDiff = 20 // change base on performance evaluation
voteKey = "ballots"
netmapKey = "netmap"
innerRingKey = "innerring"
configuredKey = "initconfig"
snapshot0Key = "snapshotCurrent"
snapshot1Key = "snapshotPrevious"
snapshotEpoch = "snapshotEpoch"
)
const (
_ nodeState = iota
onlineState
offlineState
)
var (
configPrefix = []byte("config")
ctx storage.Context
)
func init() {
if runtime.GetTrigger() != runtime.Application {
panic("contract has not been called in application node")
}
ctx = storage.GetContext()
}
// Init function sets up initial list of inner ring public keys and should
// be invoked once at neofs infrastructure setup.
func Init(keys [][]byte) {
if storage.Get(ctx, innerRingKey) != nil {
panic("netmap: contract already initialized")
}
var irList []irNode
for i := 0; i < len(keys); i++ {
key := keys[i]
irList = append(irList, irNode{key: key})
}
setSerialized(ctx, innerRingKey, irList)
// epoch number is a little endian int, it doesn't need to be serialized
storage.Put(ctx, snapshotEpoch, 0)
// simplified: this used for const sysfee in AddPeer method
setSerialized(ctx, netmapKey, []netmapNode{})
setSerialized(ctx, snapshot0Key, []netmapNode{})
setSerialized(ctx, snapshot1Key, []netmapNode{})
setSerialized(ctx, voteKey, []ballot{})
runtime.Log("netmap contract initialized")
}
func InnerRingList() []irNode {
return getIRNodes(ctx)
}
func UpdateInnerRing(keys [][]byte) bool {
innerRing := getIRNodes(ctx)
threshold := len(innerRing)/3*2 + 1
irKey := innerRingInvoker(innerRing)
if len(irKey) == 0 {
panic("updateInnerRing: this method must be invoked by inner ring nodes")
}
var irList []irNode
for i := 0; i < len(keys); i++ {
key := keys[i]
irList = append(irList, irNode{key: key})
}
rawIRList := binary.Serialize(irList)
hashIRList := crypto.SHA256(rawIRList)
n := vote(ctx, hashIRList, irKey)
if n >= threshold {
runtime.Log("updateInnerRing: inner ring list updated")
setSerialized(ctx, innerRingKey, irList)
removeVotes(ctx, hashIRList)
} else {
runtime.Log("updateInnerRing: processed invoke from inner ring")
}
return true
}
func AddPeer(nodeInfo []byte) bool {
innerRing := getIRNodes(ctx)
threshold := len(innerRing)/3*2 + 1
irKey := innerRingInvoker(innerRing)
if len(irKey) == 0 {
publicKey := nodeInfo[2:35] // offset:2, len:33
if !runtime.CheckWitness(publicKey) {
panic("addPeer: witness check failed")
}
runtime.Notify("AddPeer", nodeInfo)
return true
}
candidate := storageNode{
info: nodeInfo,
}
rawCandidate := binary.Serialize(candidate)
hashCandidate := crypto.SHA256(rawCandidate)
nm := addToNetmap(ctx, candidate)
n := vote(ctx, hashCandidate, irKey)
if n >= threshold {
if nm == nil {
runtime.Log("addPeer: storage node already in the netmap")
} else {
setSerialized(ctx, netmapKey, nm)
runtime.Log("addPeer: add storage node to the network map")
}
removeVotes(ctx, hashCandidate)
} else {
runtime.Log("addPeer: processed invoke from inner ring")
}
return true
}
func UpdateState(state int, publicKey []byte) bool {
if len(publicKey) != 33 {
panic("updateState: incorrect public key")
}
innerRing := getIRNodes(ctx)
threshold := len(innerRing)/3*2 + 1
irKey := innerRingInvoker(innerRing)
if len(irKey) == 0 {
if !runtime.CheckWitness(publicKey) {
panic("updateState: witness check failed")
}
runtime.Notify("UpdateState", state, publicKey)
return true
}
switch nodeState(state) {
case offlineState:
newNetmap := removeFromNetmap(ctx, publicKey)
hashID := invokeID([]interface{}{publicKey}, []byte("delete"))
n := vote(ctx, hashID, irKey)
if n >= threshold {
runtime.Log("updateState: remove storage node from the network map")
setSerialized(ctx, netmapKey, newNetmap)
removeVotes(ctx, hashID)
} else {
runtime.Log("updateState: processed invoke from inner ring")
}
default:
panic("updateState: unsupported state")
}
return true
}
func NewEpoch(epochNum int) bool {
innerRing := getIRNodes(ctx)
threshold := len(innerRing)/3*2 + 1
irKey := innerRingInvoker(innerRing)
if len(irKey) == 0 {
panic("newEpoch: this method must be invoked by inner ring nodes")
}
data0snapshot := getSnapshot(ctx, snapshot0Key)
dataOnlineState := filterNetmap(ctx, onlineState)
hashID := invokeID([]interface{}{epochNum}, []byte("epoch"))
n := vote(ctx, hashID, irKey)
if n >= threshold {
runtime.Log("newEpoch: process new epoch")
// todo: check if provided epoch number is bigger than current
storage.Put(ctx, snapshotEpoch, epochNum)
// put actual snapshot into previous snapshot
setSerialized(ctx, snapshot1Key, data0snapshot)
// put netmap into actual snapshot
setSerialized(ctx, snapshot0Key, dataOnlineState)
removeVotes(ctx, hashID)
runtime.Notify("NewEpoch", epochNum)
} else {
runtime.Log("newEpoch: processed invoke from inner ring")
}
return true
}
func Epoch() int {
return storage.Get(ctx, snapshotEpoch).(int)
}
func Netmap() []storageNode {
return getSnapshot(ctx, snapshot0Key)
}
func Snapshot(diff int) []storageNode {
var key string
switch diff {
case 0:
key = snapshot0Key
case 1:
key = snapshot1Key
default:
panic("snapshot: incorrect diff")
}
return getSnapshot(ctx, key)
}
func Config(key []byte) interface{} {
return getConfig(ctx, key)
}
func SetConfig(id, key, val []byte) bool {
// check if it is inner ring invocation
innerRing := getIRNodes(ctx)
threshold := len(innerRing)/3*2 + 1
irKey := innerRingInvoker(innerRing)
if len(irKey) == 0 {
panic("setConfig: invoked by non inner ring node")
}
// check unique id of the operation
hashID := invokeID([]interface{}{id, key, val}, []byte("config"))
n := vote(ctx, hashID, irKey)
if n >= threshold {
removeVotes(ctx, hashID)
setConfig(ctx, key, val)
runtime.Log("setConfig: configuration has been updated")
}
return true
}
func InitConfig(args [][]byte) bool {
if storage.Get(ctx, configuredKey) != nil {
panic("netmap: configuration already installed")
}
ln := len(args)
if ln%2 != 0 {
panic("initConfig: bad arguments")
}
for i := 0; i < ln/2; i++ {
key := args[i*2]
val := args[i*2+1]
setConfig(ctx, key, val)
}
storage.Put(ctx, configuredKey, true)
runtime.Log("netmap: config has been installed")
return true
}
func ListConfig() []record {
var config []record
it := storage.Find(ctx, configPrefix)
for iterator.Next(it) {
key := iterator.Key(it).([]byte)
val := iterator.Value(it).([]byte)
r := record{key: key[len(configPrefix):], val: val}
config = append(config, r)
}
return config
}
func Version() int {
return version
}
func innerRingInvoker(ir []irNode) []byte {
for i := 0; i < len(ir); i++ {
node := ir[i]
if runtime.CheckWitness(node.key) {
return node.key
}
}
return nil
}
func addToNetmap(ctx storage.Context, n storageNode) []netmapNode {
var (
newNode = n.info
newNodeKey = newNode[2:35]
netmap = getNetmapNodes(ctx)
node = netmapNode{
node: n,
state: onlineState,
}
)
for i := range netmap {
netmapNode := netmap[i].node.info
netmapNodeKey := netmapNode[2:35]
if bytesEqual(newNodeKey, netmapNodeKey) {
return nil
}
}
netmap = append(netmap, node)
return netmap
}
func removeFromNetmap(ctx storage.Context, key []byte) []netmapNode {
var (
netmap = getNetmapNodes(ctx)
newNetmap = []netmapNode{}
)
for i := 0; i < len(netmap); i++ {
item := netmap[i]
node := item.node.info
publicKey := node[2:35] // offset:2, len:33
if !bytesEqual(publicKey, key) {
newNetmap = append(newNetmap, item)
}
}
return newNetmap
}
func filterNetmap(ctx storage.Context, st nodeState) []storageNode {
var (
netmap = getNetmapNodes(ctx)
result = []storageNode{}
)
for i := 0; i < len(netmap); i++ {
item := netmap[i]
if item.state == st {
result = append(result, item.node)
}
}
return result
}
func vote(ctx storage.Context, id, from []byte) int {
var (
newCandidates []ballot
candidates = getBallots(ctx)
found = -1
blockHeight = blockchain.GetHeight()
)
for i := 0; i < len(candidates); i++ {
cnd := candidates[i]
if bytesEqual(cnd.id, id) {
voters := cnd.n
for j := range voters {
if bytesEqual(voters[j], from) {
return len(voters)
}
}
voters = append(voters, from)
cnd = ballot{id: id, n: voters, block: blockHeight}
found = len(voters)
}
// do not add old ballots, they are invalid
if blockHeight-cnd.block <= blockDiff {
newCandidates = append(newCandidates, cnd)
}
}
if found < 0 {
voters := [][]byte{from}
newCandidates = append(newCandidates, ballot{
id: id,
n: voters,
block: blockHeight})
found = 1
}
setSerialized(ctx, voteKey, newCandidates)
return found
}
func removeVotes(ctx storage.Context, id []byte) {
var (
newCandidates []ballot
candidates = getBallots(ctx)
)
for i := 0; i < len(candidates); i++ {
cnd := candidates[i]
if !bytesEqual(cnd.id, id) {
newCandidates = append(newCandidates, cnd)
}
}
setSerialized(ctx, voteKey, newCandidates)
}
func getIRNodes(ctx storage.Context) []irNode {
data := storage.Get(ctx, innerRingKey)
if data != nil {
return binary.Deserialize(data.([]byte)).([]irNode)
}
return []irNode{}
}
func getNetmapNodes(ctx storage.Context) []netmapNode {
data := storage.Get(ctx, netmapKey)
if data != nil {
return binary.Deserialize(data.([]byte)).([]netmapNode)
}
return []netmapNode{}
}
func getSnapshot(ctx storage.Context, key string) []storageNode {
data := storage.Get(ctx, key)
if data != nil {
return binary.Deserialize(data.([]byte)).([]storageNode)
}
return []storageNode{}
}
func getBallots(ctx storage.Context) []ballot {
data := storage.Get(ctx, voteKey)
if data != nil {
return binary.Deserialize(data.([]byte)).([]ballot)
}
return []ballot{}
}
func setSerialized(ctx storage.Context, key interface{}, value interface{}) {
data := binary.Serialize(value)
storage.Put(ctx, key, data)
}
func getConfig(ctx storage.Context, key interface{}) interface{} {
postfix := key.([]byte)
storageKey := append(configPrefix, postfix...)
return storage.Get(ctx, storageKey)
}
func setConfig(ctx storage.Context, key, val interface{}) {
postfix := key.([]byte)
storageKey := append(configPrefix, postfix...)
storage.Put(ctx, storageKey, val)
}
func invokeID(args []interface{}, prefix []byte) []byte {
for i := range args {
arg := args[i].([]byte)
prefix = append(prefix, arg...)
}
return crypto.SHA256(prefix)
}
// neo-go#1176
func bytesEqual(a []byte, b []byte) bool {
return util.Equals(string(a), string(b))
}