-
Notifications
You must be signed in to change notification settings - Fork 1
/
mempool.go
496 lines (388 loc) · 12.4 KB
/
mempool.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package mempool
import (
"encoding/hex"
"os"
"sob-miner/internal/ierrors"
"sob-miner/pkg/address"
"sob-miner/pkg/opcode"
"sob-miner/pkg/transaction"
"strings"
"sync"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
type mempool struct {
dust uint64
maxTxSize uint
maxMemPoolSize uint
db *gorm.DB
logger *logrus.Logger
mu sync.RWMutex
rejectedTxFile *os.File
}
type Mempool interface {
DB() *gorm.DB
ResetTables() error
PutTx(tx Transaction) error
PickBestTx() (transaction.Tx, error)
PickBestTxWithinWeight(weight uint64) (transaction.Tx, error)
DeleteTx(ID uint) error
GetInputs(SpendingTxHash string) ([]transaction.InputTx, error)
GetOutputs(FundingTxHash string) ([]transaction.OutPutTx, error)
GetOutPointByIndex(FundingTxHash string, index uint32) (transaction.OutPutTx, error)
MarkOutPointSpent(FundingTxHash string, index uint32) error
ValidateWholeTx(tx transaction.Tx, inputs []transaction.InputTx) error
}
func New(dialector gorm.Dialector, mempoolOpts Opts, opts ...gorm.Option) (Mempool, error) {
db, err := gorm.Open(dialector, opts...)
if err != nil {
return nil, err
}
if err := db.AutoMigrate(transaction.Tx{}, transaction.InputTx{}, transaction.OutPutTx{}); err != nil {
return nil, err
}
var _tx transaction.Tx
stmt := db.Session(&gorm.Session{DryRun: true}).Order("fee_collected / weight desc").Limit(1).Find(&_tx).Limit(1).Statement
if err := db.Order("fee_collected / weight desc").Find(&_tx).Limit(1).Error; err != nil {
return nil, err
}
mempoolOpts.Logger.Infof("Dry Run Test: %v", stmt.SQL.String())
mempoolOpts.Logger.Infof("Dry Run Test: %v", _tx)
return &mempool{
db: db,
logger: mempoolOpts.Logger,
maxMemPoolSize: mempoolOpts.MaxMemPoolSize,
dust: mempoolOpts.Dust,
maxTxSize: mempoolOpts.MaxTxSize,
mu: sync.RWMutex{},
// rejectedTxFile: ,
}, nil
}
func (m *mempool) DB() *gorm.DB {
return m.db
}
// TODO: configure proper logger
func (m *mempool) PutTx(tx Transaction) error {
if err := tx.Validate(); err != nil {
m.logger.Info("tx id is invalid ", err)
return err
}
txHash, wtxid, weight, err := tx.Hash()
if err != nil {
m.logger.Info("unable to compute Hash", err)
return err
}
_tx := transaction.Tx{
Version: tx.Version,
Locktime: tx.Locktime,
Hash: txHash,
Weight: uint64(weight),
WTXID: wtxid,
}
m.mu.Lock()
defer m.mu.Unlock()
amountLoad, err := m.PutInputTx(tx.Vin, txHash)
if err != nil {
m.logger.Info("unable to PutInputTx", err)
return err
}
amountSpent, err := m.PutOutputTx(tx.Vout, []string{txHash}, []uint32{})
if err != nil {
m.logger.Infof("unable to PutOutputTx %v for tx %v", err, txHash)
return err
}
feeCollected := amountLoad - amountSpent
if feeCollected < int(m.dust) {
m.logger.Info("fee collected is less than dust")
return ierrors.ErrFeeTooLow
}
_tx.FeeCollected = uint64(feeCollected)
return m.db.Create(&_tx).Error
}
// TODO: batch writes to db
func (m *mempool) PutInputTx(Vin []TxIn, spendingHash string) (amountLoaded int, err error) {
outputs := []TxOut{}
fundingTxIndexes := []uint32{}
fundingTxHashes := []string{}
inputTxs := []transaction.InputTx{}
isRBF := false
for i := 0; i < len(Vin); i++ {
witness := ""
for j := 0; j < len(Vin[i].Witness); j++ {
if j != 0 {
witness += ","
}
witness += Vin[i].Witness[j]
}
inputTx := transaction.InputTx{
SpendingTxHash: spendingHash,
FundingTxHash: Vin[i].Txid,
FundingIndex: Vin[i].Vout,
ScriptSig: Vin[i].ScriptSig,
Sequence: Vin[i].Sequence,
ScriptAsm: Vin[i].ScriptSigAsm,
Witness: witness,
IsCoinbase: Vin[i].IsCoinbase, // no coinbase txs in given mempool [might remove in future iterations]
InnerWitnessScriptAsm: Vin[i].InnerWitnessScriptAsm,
InnerRedeemScriptAsm: Vin[i].InnerRedeemScriptAsm,
}
inputTxs = append(inputTxs, inputTx)
outputs = append(outputs, Vin[i].Prevout)
fundingTxIndexes = append(fundingTxIndexes, Vin[i].Vout)
fundingTxHashes = append(fundingTxHashes, Vin[i].Txid)
if Vin[i].Sequence <= 0xFFFFFFFD && !isRBF {
isRBF = true
}
}
if err := m.db.Create(&inputTxs).Error; err != nil {
m.logger.Info("unable to create input txs", err)
return 0, err
}
amountLoaded, err = m.PutOutputTx(outputs, fundingTxHashes, fundingTxIndexes)
if err != nil {
m.logger.Infof("unable to PutOutputTx %v for tx %v", err, spendingHash)
return 0, err
}
return amountLoaded, nil
}
// TODO: batch writes to db
func (m *mempool) PutOutputTx(Vout []TxOut, fundingTxHashes []string, fundingIndexes []uint32) (amountSpent int, err error) {
amountSpent = 0
if len(fundingIndexes) == 0 {
for i := 0; i < len(Vout); i++ {
fundingIndexes = append(fundingIndexes, uint32(i))
}
}
if len(fundingTxHashes) == 1 {
for i := 1; i < len(Vout); i++ {
fundingTxHashes = append(fundingTxHashes, fundingTxHashes[0])
}
}
if len(Vout) != len(fundingIndexes) {
m.logger.Info("len(Vout) != len(fundingIndexes)")
return 0, ierrors.ErrInvalidTx
}
for i := 0; i < len(Vout); i++ {
amountSpent += int(Vout[i].Value)
outPutTx := transaction.OutPutTx{
FundingTxHash: fundingTxHashes[i],
FundingTxPos: uint32(fundingIndexes[i]),
ScriptPubKey: Vout[i].ScriptPubKey,
ScriptAsm: Vout[i].ScriptPubKeyAsm,
ScriptType: transaction.Type(Vout[i].ScriptPubKeyType),
ScriptAddress: Vout[i].ScriptPubKeyAddress,
Value: Vout[i].Value,
}
if err := m.ValidateOutput(outPutTx); err != nil {
m.logger.Info("unable to ValidateOutput", err)
return 0, err
}
var tempOut transaction.OutPutTx
// check if outpoint already exists in db by fundingTxHash and index
if err := m.db.Where("funding_tx_hash = ? AND funding_tx_pos = ?", outPutTx.FundingTxHash, fundingIndexes[i]).Take(&tempOut).Error; err != nil {
if err == gorm.ErrRecordNotFound {
if err := m.db.Create(&outPutTx).Error; err != nil {
m.logger.Info("unable to create outpoint tx", err)
return 0, err
}
continue
}
m.logger.Info("err while fetching outpoint from db", err)
return 0, err
}
m.logger.Debugf("outpoint %s:%d already exists in db ID %d obj %v and err %v", outPutTx.FundingTxHash, fundingIndexes[i], tempOut.ID, tempOut, err)
continue
}
return amountSpent, nil
}
func (m *mempool) PickBestTx() (transaction.Tx, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var _tx transaction.Tx
if err := m.db.Order("fee_collected / weight desc").Find(&_tx).Limit(1).Error; err != nil {
return transaction.Tx{}, err
}
return _tx, nil
}
func (m *mempool) GetInputs(SpendingTxHash string) ([]transaction.InputTx, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var inputs []transaction.InputTx
if err := m.db.Where("spending_tx_hash = ?", SpendingTxHash).Find(&inputs).Error; err != nil {
return nil, err
}
return inputs, nil
}
func (m *mempool) GetOutputs(FundingTxHash string) ([]transaction.OutPutTx, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var outputs []transaction.OutPutTx
if err := m.db.Where("funding_tx_hash = ?", FundingTxHash).Find(&outputs).Error; err != nil {
return nil, err
}
return outputs, nil
}
func (m *mempool) GetOutPointByIndex(FundingTxHash string, index uint32) (transaction.OutPutTx, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var output transaction.OutPutTx
if err := m.db.Where("funding_tx_hash = ? AND funding_tx_pos = ?", FundingTxHash, index).Find(&output).Error; err != nil {
return transaction.OutPutTx{}, err
}
return output, nil
}
func (m *mempool) MarkOutPointSpent(FundingTxHash string, index uint32) error {
m.mu.Lock()
defer m.mu.Unlock()
var output transaction.OutPutTx
if err := m.db.Where("funding_tx_hash = ? AND funding_tx_pos = ?", FundingTxHash, index).Find(&output).Error; err != nil {
return err
}
if output.Spent {
m.logger.Info("outpoint already spent", FundingTxHash, index)
return ierrors.ErrAlreadySpent
}
output.Spent = true
if err := m.db.Save(&output).Error; err != nil {
return err
}
return nil
}
// UnUsed
func (m *mempool) ValidateInput(input transaction.InputTx) error {
// TODO: validate sequence only if tx version is 2
if input.Sequence > 0xffffffff {
return ierrors.ErrInvalidSequence
}
prevOut, err := m.GetOutPointByIndex(input.FundingTxHash, input.FundingIndex)
if err != nil {
m.logger.Info("err while fetching outpoint from db", err)
return err
}
switch prevOut.ScriptType {
case transaction.OP_RETURN_TYPE:
return ierrors.ErrUsingOpReturnAsInput
case transaction.P2MS:
case transaction.P2PKH,
transaction.P2WPKH, transaction.P2WSH,
transaction.P2TR, transaction.P2PK, transaction.P2SH:
default:
m.logger.Info("invalid script type", prevOut.ScriptType)
return ierrors.ErrInvalidScript
}
return nil
}
func (m *mempool) ValidateOutput(out transaction.OutPutTx) error {
if out.ScriptType == transaction.OP_RETURN_TYPE {
return nil
}
if out.ScriptAsm == "" {
return nil
}
asmScript := strings.Split(out.ScriptAsm, " ")
decoded_script := []byte{}
for _, item := range asmScript {
if len(item) > 3 && item[:3] == "OP_" {
bytedecoded, ok := opcode.OpCodeMap[item]
if !ok {
m.logger.Info("invalid opcode", item, out.ScriptAddress)
return ierrors.ErrInvalidOpCode
}
decoded_script = append(decoded_script, bytedecoded)
continue
}
byteItem, err := hex.DecodeString(item)
if err != nil {
m.logger.Info("invalid hex string", " "+item+" ", err, " "+out.ScriptAddress)
return err
}
decoded_script = append(decoded_script, byteItem...)
}
hexstring := hex.EncodeToString(decoded_script)
if hexstring != out.ScriptPubKey {
m.logger.Infof("asm and script mismatch %v %v", hexstring, out.ScriptPubKey)
return ierrors.ErrAsmAndScriptMismatch
}
encodedAddress, err := address.EncodeAddress(out.ScriptAsm, out.ScriptType)
if err != nil {
m.logger.Infof("unable to encode address %v for script %v", err, out.ScriptAsm)
return err
}
if encodedAddress != out.ScriptAddress {
m.logger.Info("asm and address mismatch", encodedAddress, out.ScriptAddress)
return ierrors.ErrInvalidAddress
}
return nil
}
func (m *mempool) DeleteTx(ID uint) error {
return m.db.Delete(&transaction.Tx{}, ID).Error
}
func (m *mempool) ValidateWholeTx(tx transaction.Tx, inputs []transaction.InputTx) error {
m.mu.RLock()
defer m.mu.RUnlock()
var Vins []TxIn
var Vouts []TxOut
for _, input := range inputs {
outpoint, err := m.GetOutPointByIndex(input.FundingTxHash, input.FundingIndex)
if err != nil {
return err
}
Vins = append(Vins, TxIn{
Txid: input.FundingTxHash,
Vout: input.FundingIndex,
Prevout: TxOut{
ScriptPubKey: outpoint.ScriptPubKey,
ScriptPubKeyAsm: outpoint.ScriptAsm,
ScriptPubKeyType: string(outpoint.ScriptType),
ScriptPubKeyAddress: outpoint.ScriptAddress,
Value: outpoint.Value,
},
ScriptSig: input.ScriptSig,
ScriptSigAsm: input.ScriptAsm,
Witness: strings.Split(input.Witness, ","),
Sequence: input.Sequence,
InnerWitnessScriptAsm: input.InnerWitnessScriptAsm,
InnerRedeemScriptAsm: input.InnerRedeemScriptAsm,
})
}
outputs, err := m.GetOutputs(tx.Hash)
if err != nil {
return err
}
for _, output := range outputs {
Vouts = append(Vouts, TxOut{
ScriptPubKey: output.ScriptPubKey,
ScriptPubKeyAsm: output.ScriptAsm,
ScriptPubKeyType: string(output.ScriptType),
ScriptPubKeyAddress: output.ScriptAddress,
Value: output.Value,
})
}
wholeTx := Transaction{
Version: tx.Version,
Locktime: tx.Locktime,
Vin: Vins,
Vout: Vouts,
}
return wholeTx.ValidateTxScripts()
}
func (m *mempool) ResetTables() error {
if err := m.db.Exec("UPDATE txes SET deleted_at = NULL;").Error; err != nil {
return err
}
if err := m.db.Exec("UPDATE out_put_txes SET spent = false;").Error; err != nil {
return err
}
return nil
}
func (m *mempool) PickBestTxWithinWeight(weight uint64) (transaction.Tx, error) {
m.mu.RLock()
defer m.mu.RUnlock()
var _tx transaction.Tx
if err := m.db.Where("weight <= ?", weight).Order("fee_collected / weight desc").Take(&_tx).Limit(1).Error; err != nil {
return transaction.Tx{}, err
}
return _tx, nil
}
// 6a4c58325b1056bbd88c79d8a9a1648ff834e11d75cd5053aaa1d1878c2cfa809d7cb75913b944fa322a1f943a4f5c9c103548622aa92e1fa448e7c83d244a39b9da02f16c000cbbf60001000cabd5000849
// 6a4c5058325b1056bbd88c79d8a9a1648ff834e11d75cd5053aaa1d1878c2cfa809d7cb75913b944fa322a1f943a4f5c9c103548622aa92e1fa448e7c83d244a39b9da02f16c000cbbf60001000cabd5000849