-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_graph.go
203 lines (178 loc) · 5.75 KB
/
badger_graph.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
package storage
import (
"context"
"encoding/binary"
"fmt"
"runtime"
"sort"
"sync/atomic"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/config"
"github.com/MixinNetwork/mixin/crypto"
"github.com/MixinNetwork/mixin/logger"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/badger/pb"
)
const (
graphPrefixGhost = "GHOST" // each output key should only be used once
graphPrefixUTXO = "UTXO" // unspent outputs, including first consumed transaction hash
graphPrefixDeposit = "DEPOSIT"
graphPrefixMint = "MINT"
graphPrefixTransaction = "TRANSACTION" // raw transaction, may not be finalized yet, if finalized with first finalized snapshot hash
graphPrefixFinalization = "FINALIZATION" // transaction finalization hack
graphPrefixUnique = "UNIQUE" // unique transaction in one node
graphPrefixRound = "ROUND" // hash|node-if-cache {node:hash,number:734,references:{self-parent-round-hash,external-round-hash}}
graphPrefixSnapshot = "SNAPSHOT" // {
graphPrefixLink = "LINK" // self-external number
graphPrefixTopology = "TOPOLOGY"
graphPrefixSnapTopology = "SNAPTOPO"
graphPrefixAsset = "ASSET"
)
func (s *BadgerStore) ValidateGraphEntries() (int, int, error) {
txn := s.snapshotsDB.NewTransaction(false)
defer txn.Discard()
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
var total, invalid int64
stream := s.snapshotsDB.NewStream()
stream.NumGo = runtime.NumCPU()
stream.Prefix = []byte(graphPrefixTransaction)
stream.LogPrefix = "Badger.ValidateGraphEntries"
stream.ChooseKey = func(item *badger.Item) bool {
atomic.AddInt64(&total, 1)
err := item.Value(func(val []byte) error {
ver, err := common.DecompressUnmarshalVersionedTransaction(val)
if err != nil {
return err
}
key := item.Key()
var hash crypto.Hash
copy(hash[:], key[len(graphPrefixTransaction):])
if hash.String() != ver.PayloadHash().String() {
atomic.AddInt64(&invalid, 1)
logger.Printf("MALFORMED %s %s %#v\n", hash.String(), ver.PayloadHash().String(), ver)
}
return nil
})
if err != nil {
panic(err)
}
return false
}
stream.KeyToList = nil
stream.Send = func(list *pb.KVList) error { return nil }
err := stream.Orchestrate(context.Background())
return int(total), int(invalid), err
}
func (s *BadgerStore) RemoveGraphEntries(prefix string) error {
txn := s.snapshotsDB.NewTransaction(true)
defer txn.Discard()
opts := badger.DefaultIteratorOptions
opts.PrefetchValues = false
it := txn.NewIterator(opts)
defer it.Close()
it.Seek([]byte(prefix))
for ; it.ValidForPrefix([]byte(prefix)); it.Next() {
item := it.Item()
err := txn.Delete(item.Key())
if err != nil {
return err
}
}
it.Close()
return txn.Commit()
}
func (s *BadgerStore) ReadSnapshotsForNodeRound(nodeId crypto.Hash, round uint64) ([]*common.SnapshotWithTopologicalOrder, error) {
txn := s.snapshotsDB.NewTransaction(false)
defer txn.Discard()
return readSnapshotsForNodeRound(txn, nodeId, round)
}
func readSnapshotsForNodeRound(txn *badger.Txn, nodeId crypto.Hash, round uint64) ([]*common.SnapshotWithTopologicalOrder, error) {
snapshots := make([]*common.SnapshotWithTopologicalOrder, 0)
it := txn.NewIterator(badger.DefaultIteratorOptions)
defer it.Close()
key := graphSnapshotKey(nodeId, round, crypto.Hash{})
prefix := key[:len(key)-len(crypto.Hash{})]
for it.Seek(key); it.ValidForPrefix(prefix); it.Next() {
item := it.Item()
v, err := item.ValueCopy(nil)
if err != nil {
return snapshots, err
}
var s common.SnapshotWithTopologicalOrder
err = common.DecompressMsgpackUnmarshal(v, &s)
if err != nil {
return snapshots, err
}
s.Hash = s.PayloadHash()
snapshots = append(snapshots, &s)
}
sort.Slice(snapshots, func(i, j int) bool { return snapshots[i].Timestamp < snapshots[j].Timestamp })
return snapshots, nil
}
func (s *BadgerStore) WriteSnapshot(snap *common.SnapshotWithTopologicalOrder) error {
txn := s.snapshotsDB.NewTransaction(true)
defer txn.Discard()
// FIXME assert only, remove in future
if config.Debug {
cache, err := readRound(txn, snap.NodeId)
if err != nil {
return err
}
if cache == nil || snap.RoundNumber != cache.Number {
panic(fmt.Errorf("snapshot round number assert error %d %d", cache.Number, snap.RoundNumber))
}
if snap.RoundNumber > 0 && !snap.References.Equal(cache.References) {
panic("snapshot references assert error")
}
ver, err := readTransaction(txn, snap.Transaction)
if err != nil {
return err
}
if ver == nil {
panic("snapshot transaction not exist")
}
key := graphSnapshotKey(snap.NodeId, snap.RoundNumber, snap.Transaction)
_, err = txn.Get(key)
if err == nil {
panic("snapshot duplication")
} else if err != badger.ErrKeyNotFound {
return err
}
}
// end assert
ver, err := readTransaction(txn, snap.Transaction)
if err != nil {
return err
}
err = writeSnapshot(txn, snap, ver)
if err != nil {
return err
}
return txn.Commit()
}
func writeSnapshot(txn *badger.Txn, snap *common.SnapshotWithTopologicalOrder, ver *common.VersionedTransaction) error {
err := finalizeTransaction(txn, ver, snap)
if err != nil {
return err
}
key := graphSnapshotKey(snap.NodeId, snap.RoundNumber, snap.Transaction)
val := common.CompressMsgpackMarshalPanic(snap)
err = txn.Set(key, val)
if err != nil {
return err
}
key = graphUniqueKey(snap.NodeId, snap.Transaction)
err = txn.Set(key, []byte{})
if err != nil {
return err
}
return writeTopology(txn, snap)
}
func graphSnapshotKey(nodeId crypto.Hash, round uint64, hash crypto.Hash) []byte {
buf := make([]byte, 8)
binary.BigEndian.PutUint64(buf, round)
key := append([]byte(graphPrefixSnapshot), nodeId[:]...)
key = append(key, buf...)
return append(key, hash[:]...)
}