-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_node.go
245 lines (213 loc) · 6.35 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
package storage
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/crypto"
"github.com/dgraph-io/badger"
)
const (
graphPrefixNodePledge = "NODESTATEPLEDGE"
graphPrefixNodeAccept = "NODESTATEACCEPT"
graphPrefixNodeDepart = "NODESTATEDEPART"
graphPrefixNodeRemove = "NODESTATEREMOVE"
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)
for _, n := range accepted {
n.State = common.NodeStateAccepted
nodes = append(nodes, n)
}
pledging := readNodesInState(txn, graphPrefixNodePledge)
for _, n := range pledging {
n.State = common.NodeStatePledging
nodes = append(nodes, n)
}
departing := readNodesInState(txn, graphPrefixNodeDepart)
for _, n := range departing {
n.State = common.NodeStateDeparting
nodes = append(nodes, n)
}
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"
}
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)
}
nodes = append(nodes, &common.Node{
Signer: signer,
Payee: nodePayee(ival),
Transaction: nodeTransaction(ival),
Timestamp: nodeTimestamp(ival),
})
}
return nodes
}
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)
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, timestamp)
val := append(payee[:], tx[:]...)
val = append(val, buf...)
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())
}
departing := readNodesInState(txn, graphPrefixNodeDepart)
if len(departing) > 0 {
node := departing[0]
return fmt.Errorf("node %s is departing", node.Signer.PublicSpendKey.String())
}
key = nodePledgeKey(signer)
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, timestamp)
val := append(payee[:], tx[:]...)
val = append(val, buf...)
return txn.Set(key, val)
}
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 nodeAcceptKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodeAccept), publicSpend[:]...)
}
func nodeDepartKey(publicSpend crypto.Key) []byte {
return append([]byte(graphPrefixNodeDepart), publicSpend[:]...)
}
func nodeOperationKey(timestamp uint64) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, timestamp)
return append([]byte(graphPrefixNodeOperation), buf...)
}