-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger_transaction.go
248 lines (219 loc) · 6.28 KB
/
badger_transaction.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
package storage
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/MixinNetwork/mixin/common"
"github.com/MixinNetwork/mixin/config"
"github.com/MixinNetwork/mixin/crypto"
"github.com/dgraph-io/badger/v2"
)
func (s *BadgerStore) ReadTransaction(hash crypto.Hash) (*common.VersionedTransaction, string, error) {
txn := s.snapshotsDB.NewTransaction(false)
defer txn.Discard()
return readTransactionAndFinalization(txn, hash)
}
func readTransactionAndFinalization(txn *badger.Txn, hash crypto.Hash) (*common.VersionedTransaction, string, error) {
tx, err := readTransaction(txn, hash)
if err != nil || tx == nil {
return tx, "", err
}
key := graphFinalizationKey(hash)
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return tx, "", nil
} else if err != nil {
return tx, "", err
}
val, err := item.ValueCopy(nil)
if err != nil {
return tx, "", err
}
if len(val) == 0 {
return tx, "MISSING", nil
}
var final crypto.Hash
copy(final[:], val)
return tx, final.String(), nil
}
func (s *BadgerStore) WriteTransaction(ver *common.VersionedTransaction) error {
txn := s.snapshotsDB.NewTransaction(true)
defer txn.Discard()
// FIXME assert kind checks, not needed at all
if config.Debug {
txHash := ver.PayloadHash()
for _, in := range ver.Inputs {
if len(in.Genesis) > 0 {
continue
}
if in.Deposit != nil {
ival, err := readDepositInput(txn, in.Deposit)
if err != nil {
panic(fmt.Errorf("deposit check error %s", err.Error()))
}
if !bytes.Equal(ival, txHash[:]) {
panic(fmt.Errorf("deposit locked for transaction %s", hex.EncodeToString(ival)))
}
continue
}
if in.Mint != nil {
dist, err := readMintInput(txn, in.Mint)
if err != nil {
panic(fmt.Errorf("mint check error %s", err.Error()))
}
if dist.Transaction != txHash || dist.Amount.Cmp(in.Mint.Amount) != 0 {
panic(fmt.Errorf("mint locked for transaction %s", dist.Transaction.String()))
}
continue
}
key := graphUtxoKey(in.Hash, in.Index)
item, err := txn.Get(key)
if err != nil {
panic(fmt.Errorf("UTXO check error %s %s:%d=>%s", err.Error(), in.Hash.String(), in.Index, txHash.String()))
}
ival, err := item.ValueCopy(nil)
if err != nil {
panic(fmt.Errorf("UTXO check error %s", err.Error()))
}
var out common.UTXOWithLock
err = common.DecompressMsgpackUnmarshal(ival, &out)
if err != nil {
panic(fmt.Errorf("UTXO check error %s", err.Error()))
}
if out.LockHash != txHash {
panic(fmt.Errorf("utxo %s:%d locked for transaction %s instead of %s", out.Hash, out.Index, out.LockHash, txHash))
}
}
}
// assert end
err := writeTransaction(txn, ver)
if err != nil {
return err
}
return txn.Commit()
}
func readTransaction(txn *badger.Txn, hash crypto.Hash) (*common.VersionedTransaction, error) {
key := graphTransactionKey(hash)
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return nil, nil
}
val, err := item.ValueCopy(nil)
if err != nil {
return nil, err
}
return common.DecompressUnmarshalVersionedTransaction(val)
}
func pruneTransaction(txn *badger.Txn, hash crypto.Hash) error {
key := graphFinalizationKey(hash)
_, err := txn.Get(key)
if err == nil {
return fmt.Errorf("prune finalized transaction %s", hash.String())
} else if err != badger.ErrKeyNotFound {
return err
}
key = graphTransactionKey(hash)
return txn.Delete(key)
}
func writeTransaction(txn *badger.Txn, ver *common.VersionedTransaction) error {
key := graphTransactionKey(ver.PayloadHash())
_, err := txn.Get(key)
if err == nil {
return nil
} else if err != badger.ErrKeyNotFound {
return err
}
val := ver.CompressMarshal()
return txn.Set(key, val)
}
func finalizeTransaction(txn *badger.Txn, ver *common.VersionedTransaction, snap *common.SnapshotWithTopologicalOrder) error {
key := graphFinalizationKey(ver.PayloadHash())
_, err := txn.Get(key)
if err == nil {
return nil
} else if err != badger.ErrKeyNotFound {
return err
}
snapHash := snap.PayloadHash()
err = txn.Set(key, snapHash[:])
if err != nil {
return err
}
var genesis bool
for _, in := range ver.Inputs {
if len(in.Genesis) > 0 {
genesis = true
break
}
}
for _, utxo := range ver.UnspentOutputs() {
err := writeUTXO(txn, utxo, ver.Extra, snap.Timestamp, genesis)
if err != nil {
return err
}
}
return nil
}
func writeUTXO(txn *badger.Txn, utxo *common.UTXO, extra []byte, timestamp uint64, genesis bool) error {
for _, k := range utxo.Keys {
key := graphGhostKey(k)
// FIXME assert kind checks, not needed at all
if config.Debug {
_, err := txn.Get(key)
if err == nil {
panic("ErrorValidateFailed")
} else if err != badger.ErrKeyNotFound {
return err
}
}
// assert end
err := txn.Set(key, []byte{0})
if err != nil {
return err
}
}
key := graphUtxoKey(utxo.Hash, utxo.Index)
val := common.CompressMsgpackMarshalPanic(utxo)
err := txn.Set(key, val)
if err != nil {
return err
}
var signer, payee crypto.Key
if len(extra) >= len(signer) {
copy(signer[:], extra)
copy(payee[:], extra[len(signer):])
}
switch utxo.Type {
case common.OutputTypeNodePledge:
return writeNodePledge(txn, signer, payee, utxo.Hash, timestamp)
case common.OutputTypeNodeCancel:
return writeNodeCancel(txn, signer, payee, utxo.Hash, timestamp)
case common.OutputTypeNodeAccept:
return writeNodeAccept(txn, signer, payee, utxo.Hash, timestamp, genesis)
case common.OutputTypeNodeRemove:
return writeNodeRemove(txn, signer, payee, utxo.Hash, timestamp)
case common.OutputTypeDomainAccept:
return writeDomainAccept(txn, signer, utxo.Hash, timestamp)
}
return nil
}
func graphTransactionKey(hash crypto.Hash) []byte {
return append([]byte(graphPrefixTransaction), hash[:]...)
}
func graphFinalizationKey(hash crypto.Hash) []byte {
return append([]byte(graphPrefixFinalization), hash[:]...)
}
func graphUniqueKey(nodeId, hash crypto.Hash) []byte {
key := append(hash[:], nodeId[:]...)
return append([]byte(graphPrefixUnique), key...)
}
func graphGhostKey(k crypto.Key) []byte {
return append([]byte(graphPrefixGhost), k[:]...)
}
func graphUtxoKey(hash crypto.Hash, index int) []byte {
buf := make([]byte, binary.MaxVarintLen64)
size := binary.PutVarint(buf, int64(index))
key := append([]byte(graphPrefixUTXO), hash[:]...)
return append(key, buf[:size]...)
}