-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_node.go
319 lines (277 loc) · 8.57 KB
/
badger_node.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
package storage
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/crypto"
"github.com/dgraph-io/badger/v2"
)
const (
graphPrefixNodePledge = "NODESTATEPLEDGE"
graphPrefixNodeAccept = "NODESTATEACCEPT"
graphPrefixNodeResign = "NODESTATERESIGN"
graphPrefixNodeRemove = "NODESTATEREMOVE"
graphPrefixNodeCancel = "NODESTATECANCEL"
graphPrefixNodeOperation = "NODEOPERATION"
)
func (s *BadgerStore) ReadConsensusNodes() []*common.Node {
nodes := make([]*common.Node, 0)
txn := s.snapshotsDB.NewTransaction(false)
defer txn.Discard()
accepted := readNodesInState(txn, graphPrefixNodeAccept)
nodes = append(nodes, accepted...)
pledging := readNodesInState(txn, graphPrefixNodePledge)
nodes = append(nodes, pledging...)
resigning := readNodesInState(txn, graphPrefixNodeResign)
nodes = append(nodes, resigning...)
return nodes
}
func (s *BadgerStore) AddNodeOperation(tx *common.VersionedTransaction, timestamp, threshold uint64) error {
txn := s.snapshotsDB.NewTransaction(true)
defer txn.Discard()
var op string
switch tx.TransactionType() {
case common.TransactionTypeNodePledge:
op = "PLEDGE"
case common.TransactionTypeNodeCancel:
op = "CANCEL"
}
if op == "" {
return fmt.Errorf("invalid operation %d %s", tx.TransactionType(), op)
}
hash := tx.PayloadHash()
lastOp, lastTx, lastTs, err := readLastNodeOperation(txn)
if err != nil {
return err
}
if lastTs+threshold >= timestamp {
if lastOp == op && lastTx == hash {
return nil
}
return fmt.Errorf("invalid operation lock %s %s %d", lastTx, lastOp, lastTs)
}
val := append(hash[:], []byte(op)...)
err = txn.Set(nodeOperationKey(timestamp), val)
if err != nil {
return err
}
return txn.Commit()
}
func readLastNodeOperation(txn *badger.Txn) (string, crypto.Hash, uint64, error) {
var timestamp uint64
var hash crypto.Hash
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
opts.Reverse = true
it := txn.NewIterator(opts)
defer it.Close()
it.Seek(nodeOperationKey(^uint64(0)))
if it.ValidForPrefix([]byte(graphPrefixNodeOperation)) {
item := it.Item()
order := item.Key()[len(graphPrefixNodeOperation):]
timestamp = binary.BigEndian.Uint64(order)
val, err := item.ValueCopy(nil)
if err != nil {
return "", hash, timestamp, err
}
copy(hash[:], val)
return string(val[len(hash):]), hash, timestamp, nil
}
return "", hash, timestamp, nil
}
func readNodesInState(txn *badger.Txn, nodeState string) []*common.Node {
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
prefix := []byte(nodeState)
nodes := make([]*common.Node, 0)
for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() {
item := it.Item()
signer := nodeSignerForState(item.Key(), nodeState)
ival, err := item.ValueCopy(nil)
if err != nil {
panic(err)
}
n := &common.Node{
Signer: signer,
Payee: nodePayee(ival),
Transaction: nodeTransaction(ival),
Timestamp: nodeTimestamp(ival),
}
switch nodeState {
case graphPrefixNodePledge:
n.State = common.NodeStatePledging
case graphPrefixNodeAccept:
n.State = common.NodeStateAccepted
case graphPrefixNodeResign:
n.State = common.NodeStateResigning
case graphPrefixNodeRemove:
n.State = common.NodeStateRemoved
case graphPrefixNodeCancel:
n.State = common.NodeStateCancelled
}
nodes = append(nodes, n)
}
return nodes
}
func writeNodeCancel(txn *badger.Txn, signer, payee crypto.Key, tx crypto.Hash, timestamp uint64) error {
// TODO these checks are only assert kind checks, not needed at all
key := nodePledgeKey(signer)
_, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return fmt.Errorf("node not pledging yet %s", signer.String())
} else if err != nil {
return err
}
pledging := readNodesInState(txn, graphPrefixNodePledge)
if len(pledging) > 0 {
node := pledging[0]
return fmt.Errorf("node %s is pledging", node.Signer.PublicSpendKey.String())
}
resigning := readNodesInState(txn, graphPrefixNodeResign)
if len(resigning) > 0 {
node := resigning[0]
return fmt.Errorf("node %s is resigning", node.Signer.PublicSpendKey.String())
}
err = txn.Delete(key)
if err != nil {
return err
}
key = nodeCancelKey(signer)
val := nodeEntryValue(payee, tx, timestamp)
return txn.Set(key, val)
}
func writeNodeRemove(txn *badger.Txn, signer, payee crypto.Key, tx crypto.Hash, timestamp uint64) error {
// TODO these checks are only assert kind checks, not needed at all
key := nodeAcceptKey(signer)
_, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return fmt.Errorf("node not accepted yet %s", signer.String())
} else if err != nil {
return err
}
pledging := readNodesInState(txn, graphPrefixNodePledge)
if len(pledging) > 0 {
node := pledging[0]
return fmt.Errorf("node %s is pledging", node.Signer.PublicSpendKey.String())
}
resigning := readNodesInState(txn, graphPrefixNodeResign)
if len(resigning) > 0 {
node := resigning[0]
return fmt.Errorf("node %s is resigning", node.Signer.PublicSpendKey.String())
}
err = txn.Delete(key)
if err != nil {
return err
}
key = nodeRemoveKey(signer)
val := nodeEntryValue(payee, tx, timestamp)
return txn.Set(key, val)
}
func writeNodeAccept(txn *badger.Txn, signer, payee crypto.Key, tx crypto.Hash, timestamp uint64, genesis bool) error {
// TODO these checks are only assert kind checks, not needed at all
key := nodePledgeKey(signer)
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
if !genesis {
return fmt.Errorf("node not pledging yet %s", signer.String())
}
} else if err != nil {
return err
}
if !genesis {
ival, err := item.ValueCopy(nil)
if err != nil {
return err
}
if bytes.Compare(payee[:], ival[:len(payee)]) != 0 {
return fmt.Errorf("node not accept to the same payee account %s %s", hex.EncodeToString(ival[:len(payee)]), payee.String())
}
}
err = txn.Delete(key)
if err != nil {
return err
}
key = nodeAcceptKey(signer)
val := nodeEntryValue(payee, tx, timestamp)
return txn.Set(key, val)
}
func writeNodePledge(txn *badger.Txn, signer, payee crypto.Key, tx crypto.Hash, timestamp uint64) error {
// TODO these checks are only assert kind checks, not needed at all
key := nodeAcceptKey(signer)
_, err := txn.Get(key)
if err == nil {
return fmt.Errorf("node already accepted %s", signer.String())
} else if err != badger.ErrKeyNotFound {
return err
}
pledging := readNodesInState(txn, graphPrefixNodePledge)
if len(pledging) > 0 {
node := pledging[0]
return fmt.Errorf("node %s is pledging", node.Signer.PublicSpendKey.String())
}
resigning := readNodesInState(txn, graphPrefixNodeResign)
if len(resigning) > 0 {
node := resigning[0]
return fmt.Errorf("node %s is resigning", node.Signer.PublicSpendKey.String())
}
key = nodePledgeKey(signer)
val := nodeEntryValue(payee, tx, timestamp)
return txn.Set(key, val)
}
func nodeEntryValue(payee crypto.Key, tx crypto.Hash, timestamp uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, timestamp)
val := append(payee[:], tx[:]...)
return append(val, buf...)
}
func nodeSignerForState(key []byte, nodeState string) common.Address {
var publicSpend crypto.Key
copy(publicSpend[:], key[len(nodeState):])
privateView := publicSpend.DeterministicHashDerive()
return common.Address{
PrivateViewKey: privateView,
PublicViewKey: privateView.Public(),
PublicSpendKey: publicSpend,
}
}
func nodePayee(ival []byte) common.Address {
var publicSpend crypto.Key
copy(publicSpend[:], ival[:len(publicSpend)])
privateView := publicSpend.DeterministicHashDerive()
return common.Address{
PrivateViewKey: privateView,
PublicViewKey: privateView.Public(),
PublicSpendKey: publicSpend,
}
}
func nodeTransaction(ival []byte) crypto.Hash {
var tx crypto.Hash
copy(tx[:], ival[len(crypto.Key{}):])
return tx
}
func nodeTimestamp(ival []byte) uint64 {
l := len(crypto.Key{}) + len(crypto.Hash{})
if len(ival) == l+8 {
return binary.BigEndian.Uint64(ival[l:])
}
return 0
}
func nodePledgeKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodePledge), publicSpend[:]...)
}
func nodeCancelKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodeCancel), publicSpend[:]...)
}
func nodeAcceptKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodeAccept), publicSpend[:]...)
}
func nodeRemoveKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodeRemove), publicSpend[:]...)
}
func nodeOperationKey(timestamp uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, timestamp)
return append([]byte(graphPrefixNodeOperation), buf...)
}