/
txunmined.go
409 lines (362 loc) · 12 KB
/
txunmined.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
// Copyright (c) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package udb
import (
"bytes"
"decred.org/dcrwallet/v2/errors"
"decred.org/dcrwallet/v2/wallet/walletdb"
"github.com/decred/dcrd/blockchain/stake/v4"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/wire"
)
// InsertMemPoolTx inserts a memory pool transaction record. It also marks
// previous outputs referenced by its inputs as spent. Errors with the
// DoubleSpend code if another unmined transaction is a double spend of this
// transaction.
func (s *Store) InsertMemPoolTx(dbtx walletdb.ReadWriteTx, rec *TxRecord) error {
ns := dbtx.ReadWriteBucket(wtxmgrBucketKey)
_, recVal := latestTxRecord(ns, rec.Hash[:])
if recVal != nil {
return errors.E(errors.Exist, "transaction already exists mined")
}
v := existsRawUnmined(ns, rec.Hash[:])
if v != nil {
return nil
}
// Check for other unmined transactions which cause this tx to be a double
// spend. Unlike mined transactions that double spend an unmined tx,
// existing unmined txs are not removed when inserting a double spending
// unmined tx.
//
// An exception is made for this rule for votes and revocations that double
// spend an unmined vote that doesn't vote on the tip block.
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
if v := existsRawUnminedInput(ns, k); v != nil {
var spenderHash chainhash.Hash
readRawUnminedInputSpenderHash(v, &spenderHash)
// A switch is used here instead of an if statement so it can be
// broken out of to the error below.
DoubleSpendVoteCheck:
switch rec.TxType {
case stake.TxTypeSSGen, stake.TxTypeSSRtx:
spenderVal := existsRawUnmined(ns, spenderHash[:])
spenderTxBytes := extractRawUnminedTx(spenderVal)
var spenderTx wire.MsgTx
err := spenderTx.Deserialize(bytes.NewReader(spenderTxBytes))
if err != nil {
return errors.E(errors.IO, err)
}
if stake.DetermineTxType(&spenderTx, true, false) != stake.TxTypeSSGen {
break DoubleSpendVoteCheck
}
votedBlock, _ := stake.SSGenBlockVotedOn(&spenderTx)
tipBlock, _ := s.MainChainTip(dbtx)
if votedBlock == tipBlock {
err := errors.Errorf("vote or revocation %v double spends unmined "+
"vote %v on the tip block", &rec.Hash, &spenderHash)
return errors.E(errors.DoubleSpend, err)
}
err = s.RemoveUnconfirmed(ns, &spenderTx, &spenderHash)
if err != nil {
return err
}
continue
}
err := errors.Errorf("%v conflicts with %v by double spending %v", &rec.Hash, &spenderHash, prevOut)
return errors.E(errors.DoubleSpend, err)
}
}
log.Infof("Inserting unconfirmed transaction %v", &rec.Hash)
v, err := valueTxRecord(rec)
if err != nil {
return err
}
err = putRawUnmined(ns, rec.Hash[:], v)
if err != nil {
return err
}
if rec.Unpublished {
err = putUnpublished(ns, rec.Hash[:])
if err != nil {
return err
}
}
txType := stake.DetermineTxType(&rec.MsgTx, true, false)
for i, input := range rec.MsgTx.TxIn {
// Skip stakebases for votes.
if i == 0 && txType == stake.TxTypeSSGen {
continue
}
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err = putRawUnminedInput(ns, k, rec.Hash[:])
if err != nil {
return err
}
}
// If the transaction is a ticket purchase, record it in the ticket
// purchases bucket.
if txType == stake.TxTypeSStx {
tk := rec.Hash[:]
tv := existsRawTicketRecord(ns, tk)
if tv == nil {
tv = valueTicketRecord(-1)
err := putRawTicketRecord(ns, tk, tv)
if err != nil {
return err
}
}
}
// TODO: increment credit amount for each credit (but those are unknown
// here currently).
return nil
}
// SetPublished modifies the published state of an unmined transaction.
func (s *Store) SetPublished(dbtx walletdb.ReadWriteTx, txHash *chainhash.Hash, published bool) error {
ns := dbtx.ReadWriteBucket(wtxmgrBucketKey)
if published {
return deleteUnpublished(ns, txHash[:])
}
return putUnpublished(ns, txHash[:])
}
// removeDoubleSpends checks for any unmined transactions which would introduce
// a double spend if tx was added to the store (either as a confirmed or unmined
// transaction). Each conflicting transaction and all transactions which spend
// it are recursively removed.
func (s *Store) removeDoubleSpends(ns walletdb.ReadWriteBucket, rec *TxRecord) error {
for _, input := range rec.MsgTx.TxIn {
prevOut := &input.PreviousOutPoint
prevOutKey := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
doubleSpendHash := existsRawUnminedInput(ns, prevOutKey)
if doubleSpendHash != nil {
var doubleSpend TxRecord
doubleSpendVal := existsRawUnmined(ns, doubleSpendHash)
copy(doubleSpend.Hash[:], doubleSpendHash) // Silly but need an array
err := readRawTxRecord(&doubleSpend.Hash, doubleSpendVal,
&doubleSpend)
if err != nil {
return err
}
log.Debugf("Removing double spending transaction %v",
doubleSpend.Hash)
err = s.RemoveUnconfirmed(ns, &doubleSpend.MsgTx, &doubleSpend.Hash)
if err != nil {
return err
}
}
}
return nil
}
// RemoveUnconfirmed removes an unmined transaction record and all spend chains
// deriving from it from the store. This is designed to remove transactions
// that would otherwise result in double spend conflicts if left in the store,
// and to remove transactions that spend coinbase transactions on reorgs. It
// can also be used to remove old tickets that do not meet the network difficulty
// and expired transactions.
func (s *Store) RemoveUnconfirmed(ns walletdb.ReadWriteBucket, tx *wire.MsgTx, txHash *chainhash.Hash) error {
stxType := stake.DetermineTxType(tx, true, false)
// For each potential credit for this record, each spender (if any) must
// be recursively removed as well. Once the spenders are removed, the
// credit is deleted.
numOuts := uint32(len(tx.TxOut))
for i := uint32(0); i < numOuts; i++ {
k := canonicalOutPoint(txHash, i)
spenderHash := existsRawUnminedInput(ns, k)
if spenderHash != nil {
var spender TxRecord
spenderVal := existsRawUnmined(ns, spenderHash)
copy(spender.Hash[:], spenderHash) // Silly but need an array
err := readRawTxRecord(&spender.Hash, spenderVal, &spender)
if err != nil {
return err
}
log.Debugf("Transaction %v is part of a removed conflict "+
"chain -- removing as well", spender.Hash)
err = s.RemoveUnconfirmed(ns, &spender.MsgTx, &spender.Hash)
if err != nil {
return err
}
}
err := deleteRawUnminedCredit(ns, k)
if err != nil {
return err
}
if (stxType == stake.TxTypeSStx) && (i%2 == 1) {
// An unconfirmed ticket leaving the store means we need to delete
// the respective commitment and its entry from the unspent
// commitments index.
// This assumes that the key to ticket commitment values in the db are
// canonicalOutPoints. If this ever changes, this needs to be changed to
// use keyTicketCommitment(...).
ktc := k
vtc := existsRawTicketCommitment(ns, ktc)
if vtc != nil {
log.Debugf("Removing unconfirmed ticket commitment %s:%d",
txHash, i)
err = deleteRawTicketCommitment(ns, ktc)
if err != nil {
return err
}
err = deleteRawUnspentTicketCommitment(ns, ktc)
if err != nil {
return err
}
}
}
}
if (stxType == stake.TxTypeSSGen) || (stxType == stake.TxTypeSSRtx) {
// An unconfirmed vote/revocation leaving the store means we need to
// unmark the commitments of the respective ticket as unminedSpent.
err := s.replaceTicketCommitmentUnminedSpent(ns, stxType, tx, false)
if err != nil {
return err
}
}
// If this tx spends any previous credits (either mined or unmined), set
// each unspent. Mined transactions are only marked spent by having the
// output in the unmined inputs bucket.
for _, input := range tx.TxIn {
prevOut := &input.PreviousOutPoint
k := canonicalOutPoint(&prevOut.Hash, prevOut.Index)
err := deleteRawUnminedInput(ns, k)
if err != nil {
return err
}
// If a multisig output is recorded for this input, mark it unspent.
if v := existsMultisigOut(ns, k); v != nil {
vcopy := make([]byte, len(v))
copy(vcopy, v)
setMultisigOutUnSpent(vcopy)
err := putMultisigOutRawValues(ns, k, vcopy)
if err != nil {
return err
}
err = putMultisigOutUS(ns, k)
if err != nil {
return err
}
}
}
err := deleteUnpublished(ns, txHash[:])
if err != nil {
return err
}
return deleteRawUnmined(ns, txHash[:])
}
// UnminedTxs returns the transaction records for all unmined transactions
// which are not known to have been mined in a block. Transactions are
// guaranteed to be sorted by their dependency order.
func (s *Store) UnminedTxs(dbtx walletdb.ReadTx) ([]*TxRecord, error) {
ns := dbtx.ReadBucket(wtxmgrBucketKey)
recSet, err := s.unminedTxRecords(ns)
if err != nil {
return nil, err
}
recs := dependencySort(recSet)
return recs, nil
}
func (s *Store) unminedTxRecords(ns walletdb.ReadBucket) (map[chainhash.Hash]*TxRecord, error) {
unmined := make(map[chainhash.Hash]*TxRecord)
err := ns.NestedReadBucket(bucketUnmined).ForEach(func(k, v []byte) error {
var txHash chainhash.Hash
err := readRawUnminedHash(k, &txHash)
if err != nil {
return err
}
rec := new(TxRecord)
err = readRawTxRecord(&txHash, v, rec)
if err != nil {
return err
}
rec.Unpublished = existsUnpublished(ns, txHash[:])
unmined[rec.Hash] = rec
return nil
})
return unmined, err
}
// UnminedTxHashes returns the hashes of all transactions not known to have been
// mined in a block.
func (s *Store) UnminedTxHashes(ns walletdb.ReadBucket) ([]*chainhash.Hash, error) {
return s.unminedTxHashes(ns)
}
func (s *Store) unminedTxHashes(ns walletdb.ReadBucket) ([]*chainhash.Hash, error) {
var hashes []*chainhash.Hash
err := ns.NestedReadBucket(bucketUnmined).ForEach(func(k, v []byte) error {
hash := new(chainhash.Hash)
err := readRawUnminedHash(k, hash)
if err == nil {
hashes = append(hashes, hash)
}
return err
})
return hashes, err
}
// PruneUnmined removes unmined transactions that no longer belong in the
// unmined tx set. This includes:
//
// * Any transactions past a set expiry
// * Ticket purchases with a different ticket price than the passed stake
// difficulty
// * Votes that do not vote on the tip block
func (s *Store) PruneUnmined(dbtx walletdb.ReadWriteTx, stakeDiff int64) ([]*chainhash.Hash, error) {
ns := dbtx.ReadWriteBucket(wtxmgrBucketKey)
tipHash, tipHeight := s.MainChainTip(dbtx)
type removeTx struct {
tx wire.MsgTx
hash *chainhash.Hash
}
var toRemove []*removeTx
c := ns.NestedReadBucket(bucketUnmined).ReadCursor()
defer c.Close()
for k, v := c.First(); k != nil; k, v = c.Next() {
var tx wire.MsgTx
err := tx.Deserialize(bytes.NewReader(extractRawUnminedTx(v)))
if err != nil {
return nil, errors.E(errors.IO, err)
}
var expired, isTicketPurchase, isVote bool
switch {
case tx.Expiry != wire.NoExpiryValue && tx.Expiry <= uint32(tipHeight):
expired = true
case stake.IsSStx(&tx):
isTicketPurchase = true
if tx.TxOut[0].Value == stakeDiff {
continue
}
case stake.IsSSGen(&tx, true): // Yes treasury
isVote = true
// This will never actually error
votedBlockHash, _ := stake.SSGenBlockVotedOn(&tx)
if votedBlockHash == tipHash {
continue
}
default:
continue
}
txHash, err := chainhash.NewHash(k)
if err != nil {
return nil, errors.E(errors.IO, err)
}
if expired {
log.Infof("Removing expired unmined transaction %v", txHash)
} else if isTicketPurchase {
log.Infof("Removing old unmined ticket purchase %v", txHash)
} else if isVote {
log.Infof("Removing missed or invalid vote %v", txHash)
}
toRemove = append(toRemove, &removeTx{tx, txHash})
}
removed := make([]*chainhash.Hash, 0, len(toRemove))
for _, r := range toRemove {
err := s.RemoveUnconfirmed(ns, &r.tx, r.hash)
if err != nil {
return removed, err
}
removed = append(removed, r.hash)
}
return removed, nil
}