• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 11178652423

04 Oct 2024 10:52AM UTC coverage: 49.756% (+0.6%) from 49.188%
11178652423

push

github

web-flow
Merge pull request #9161 from ellemouton/fixInvalidBlindingEncodeSig

channeldb/mig/lnwire21: fix FailInvalidBlinding Encode sig

0 of 1 new or added line in 1 file covered. (0.0%)

96 existing lines in 10 files now uncovered.

98485 of 197934 relevant lines covered (49.76%)

1.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

71.31
/chainntnfs/btcdnotify/btcd.go
1
package btcdnotify
2

3
import (
4
        "errors"
5
        "fmt"
6
        "sync"
7
        "sync/atomic"
8
        "time"
9

10
        "github.com/btcsuite/btcd/btcjson"
11
        "github.com/btcsuite/btcd/btcutil"
12
        "github.com/btcsuite/btcd/chaincfg"
13
        "github.com/btcsuite/btcd/chaincfg/chainhash"
14
        "github.com/btcsuite/btcd/rpcclient"
15
        "github.com/btcsuite/btcd/txscript"
16
        "github.com/btcsuite/btcd/wire"
17
        "github.com/btcsuite/btcwallet/chain"
18
        "github.com/lightningnetwork/lnd/blockcache"
19
        "github.com/lightningnetwork/lnd/chainntnfs"
20
        "github.com/lightningnetwork/lnd/fn"
21
        "github.com/lightningnetwork/lnd/queue"
22
)
23

24
const (
25
        // notifierType uniquely identifies this concrete implementation of the
26
        // ChainNotifier interface.
27
        notifierType = "btcd"
28
)
29

30
// chainUpdate encapsulates an update to the current main chain. This struct is
31
// used as an element within an unbounded queue in order to avoid blocking the
32
// main rpc dispatch rule.
33
type chainUpdate struct {
34
        blockHash   *chainhash.Hash
35
        blockHeight int32
36

37
        // connected is true if this update is a new block and false if it is a
38
        // disconnected block.
39
        connect bool
40
}
41

42
// txUpdate encapsulates a transaction related notification sent from btcd to
43
// the registered RPC client. This struct is used as an element within an
44
// unbounded queue in order to avoid blocking the main rpc dispatch rule.
45
type txUpdate struct {
46
        tx      *btcutil.Tx
47
        details *btcjson.BlockDetails
48
}
49

50
// TODO(roasbeef): generalize struct below:
51
//  * move chans to config, allow outside callers to handle send conditions
52

53
// BtcdNotifier implements the ChainNotifier interface using btcd's websockets
54
// notifications. Multiple concurrent clients are supported. All notifications
55
// are achieved via non-blocking sends on client channels.
56
type BtcdNotifier struct {
57
        epochClientCounter uint64 // To be used atomically.
58

59
        start   sync.Once
60
        active  int32 // To be used atomically.
61
        stopped int32 // To be used atomically.
62

63
        chainConn   *chain.RPCClient
64
        chainParams *chaincfg.Params
65

66
        notificationCancels  chan interface{}
67
        notificationRegistry chan interface{}
68

69
        txNotifier *chainntnfs.TxNotifier
70

71
        blockEpochClients map[uint64]*blockEpochRegistration
72

73
        bestBlock chainntnfs.BlockEpoch
74

75
        // blockCache is a LRU block cache.
76
        blockCache *blockcache.BlockCache
77

78
        chainUpdates *queue.ConcurrentQueue
79
        txUpdates    *queue.ConcurrentQueue
80

81
        // spendHintCache is a cache used to query and update the latest height
82
        // hints for an outpoint. Each height hint represents the earliest
83
        // height at which the outpoint could have been spent within the chain.
84
        spendHintCache chainntnfs.SpendHintCache
85

86
        // confirmHintCache is a cache used to query the latest height hints for
87
        // a transaction. Each height hint represents the earliest height at
88
        // which the transaction could have confirmed within the chain.
89
        confirmHintCache chainntnfs.ConfirmHintCache
90

91
        // memNotifier notifies clients of events related to the mempool.
92
        memNotifier *chainntnfs.MempoolNotifier
93

94
        wg   sync.WaitGroup
95
        quit chan struct{}
96
}
97

98
// Ensure BtcdNotifier implements the ChainNotifier interface at compile time.
99
var _ chainntnfs.ChainNotifier = (*BtcdNotifier)(nil)
100

101
// Ensure BtcdNotifier implements the MempoolWatcher interface at compile time.
102
var _ chainntnfs.MempoolWatcher = (*BtcdNotifier)(nil)
103

104
// New returns a new BtcdNotifier instance. This function assumes the btcd node
105
// detailed in the passed configuration is already running, and willing to
106
// accept new websockets clients.
107
func New(config *rpcclient.ConnConfig, chainParams *chaincfg.Params,
108
        spendHintCache chainntnfs.SpendHintCache,
109
        confirmHintCache chainntnfs.ConfirmHintCache,
110
        blockCache *blockcache.BlockCache) (*BtcdNotifier, error) {
1✔
111

1✔
112
        notifier := &BtcdNotifier{
1✔
113
                chainParams: chainParams,
1✔
114

1✔
115
                notificationCancels:  make(chan interface{}),
1✔
116
                notificationRegistry: make(chan interface{}),
1✔
117

1✔
118
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
1✔
119

1✔
120
                chainUpdates: queue.NewConcurrentQueue(10),
1✔
121
                txUpdates:    queue.NewConcurrentQueue(10),
1✔
122

1✔
123
                spendHintCache:   spendHintCache,
1✔
124
                confirmHintCache: confirmHintCache,
1✔
125

1✔
126
                blockCache:  blockCache,
1✔
127
                memNotifier: chainntnfs.NewMempoolNotifier(),
1✔
128

1✔
129
                quit: make(chan struct{}),
1✔
130
        }
1✔
131

1✔
132
        // Disable connecting to btcd within the rpcclient.New method. We
1✔
133
        // defer establishing the connection to our .Start() method.
1✔
134
        config.DisableConnectOnNew = true
1✔
135
        config.DisableAutoReconnect = false
1✔
136

1✔
137
        ntfnCallbacks := &rpcclient.NotificationHandlers{
1✔
138
                OnBlockConnected:    notifier.onBlockConnected,
1✔
139
                OnBlockDisconnected: notifier.onBlockDisconnected,
1✔
140
                OnRedeemingTx:       notifier.onRedeemingTx,
1✔
141
        }
1✔
142

1✔
143
        rpcCfg := &chain.RPCClientConfig{
1✔
144
                ReconnectAttempts:    20,
1✔
145
                Conn:                 config,
1✔
146
                Chain:                chainParams,
1✔
147
                NotificationHandlers: ntfnCallbacks,
1✔
148
        }
1✔
149

1✔
150
        chainRPC, err := chain.NewRPCClientWithConfig(rpcCfg)
1✔
151
        if err != nil {
1✔
152
                return nil, err
×
153
        }
×
154

155
        notifier.chainConn = chainRPC
1✔
156

1✔
157
        return notifier, nil
1✔
158
}
159

160
// Start connects to the running btcd node over websockets, registers for block
161
// notifications, and finally launches all related helper goroutines.
162
func (b *BtcdNotifier) Start() error {
1✔
163
        var startErr error
1✔
164
        b.start.Do(func() {
2✔
165
                startErr = b.startNotifier()
1✔
166
        })
1✔
167

168
        return startErr
1✔
169
}
170

171
// Started returns true if this instance has been started, and false otherwise.
172
func (b *BtcdNotifier) Started() bool {
1✔
173
        return atomic.LoadInt32(&b.active) != 0
1✔
174
}
1✔
175

176
// Stop shutsdown the BtcdNotifier.
177
func (b *BtcdNotifier) Stop() error {
1✔
178
        // Already shutting down?
1✔
179
        if atomic.AddInt32(&b.stopped, 1) != 1 {
1✔
180
                return nil
×
181
        }
×
182

183
        chainntnfs.Log.Info("btcd notifier shutting down...")
1✔
184
        defer chainntnfs.Log.Debug("btcd notifier shutdown complete")
1✔
185

1✔
186
        // Shutdown the rpc client, this gracefully disconnects from btcd, and
1✔
187
        // cleans up all related resources.
1✔
188
        b.chainConn.Shutdown()
1✔
189

1✔
190
        close(b.quit)
1✔
191
        b.wg.Wait()
1✔
192

1✔
193
        b.chainUpdates.Stop()
1✔
194
        b.txUpdates.Stop()
1✔
195

1✔
196
        // Notify all pending clients of our shutdown by closing the related
1✔
197
        // notification channels.
1✔
198
        for _, epochClient := range b.blockEpochClients {
2✔
199
                close(epochClient.cancelChan)
1✔
200
                epochClient.wg.Wait()
1✔
201

1✔
202
                close(epochClient.epochChan)
1✔
203
        }
1✔
204
        b.txNotifier.TearDown()
1✔
205

1✔
206
        // Stop the mempool notifier.
1✔
207
        b.memNotifier.TearDown()
1✔
208

1✔
209
        return nil
1✔
210
}
211

212
func (b *BtcdNotifier) startNotifier() error {
1✔
213
        // Start our concurrent queues before starting the chain connection, to
1✔
214
        // ensure onBlockConnected and onRedeemingTx callbacks won't be
1✔
215
        // blocked.
1✔
216
        b.chainUpdates.Start()
1✔
217
        b.txUpdates.Start()
1✔
218

1✔
219
        // Connect to btcd, and register for notifications on connected, and
1✔
220
        // disconnected blocks.
1✔
221
        if err := b.chainConn.Connect(20); err != nil {
1✔
222
                b.txUpdates.Stop()
×
223
                b.chainUpdates.Stop()
×
224
                return err
×
225
        }
×
226

227
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
1✔
228
        if err != nil {
1✔
229
                b.txUpdates.Stop()
×
230
                b.chainUpdates.Stop()
×
231
                return err
×
232
        }
×
233

234
        bestBlock, err := b.chainConn.GetBlock(currentHash)
1✔
235
        if err != nil {
1✔
236
                b.txUpdates.Stop()
×
237
                b.chainUpdates.Stop()
×
238
                return err
×
239
        }
×
240

241
        b.txNotifier = chainntnfs.NewTxNotifier(
1✔
242
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
1✔
243
                b.confirmHintCache, b.spendHintCache,
1✔
244
        )
1✔
245

1✔
246
        b.bestBlock = chainntnfs.BlockEpoch{
1✔
247
                Height:      currentHeight,
1✔
248
                Hash:        currentHash,
1✔
249
                BlockHeader: &bestBlock.Header,
1✔
250
        }
1✔
251

1✔
252
        if err := b.chainConn.NotifyBlocks(); err != nil {
1✔
253
                b.txUpdates.Stop()
×
254
                b.chainUpdates.Stop()
×
255
                return err
×
256
        }
×
257

258
        b.wg.Add(1)
1✔
259
        go b.notificationDispatcher()
1✔
260

1✔
261
        // Set the active flag now that we've completed the full
1✔
262
        // startup.
1✔
263
        atomic.StoreInt32(&b.active, 1)
1✔
264

1✔
265
        return nil
1✔
266
}
267

268
// onBlockConnected implements on OnBlockConnected callback for rpcclient.
269
// Ingesting a block updates the wallet's internal utxo state based on the
270
// outputs created and destroyed within each block.
271
func (b *BtcdNotifier) onBlockConnected(hash *chainhash.Hash, height int32, t time.Time) {
1✔
272
        // Append this new chain update to the end of the queue of new chain
1✔
273
        // updates.
1✔
274
        select {
1✔
275
        case b.chainUpdates.ChanIn() <- &chainUpdate{
276
                blockHash:   hash,
277
                blockHeight: height,
278
                connect:     true,
279
        }:
1✔
280
        case <-b.quit:
×
281
                return
×
282
        }
283
}
284

285
// filteredBlock represents a new block which has been connected to the main
286
// chain. The slice of transactions will only be populated if the block
287
// includes a transaction that confirmed one of our watched txids, or spends
288
// one of the outputs currently being watched.
289
//
290
// TODO(halseth): this is currently used for complete blocks. Change to use
291
// onFilteredBlockConnected and onFilteredBlockDisconnected, making it easier
292
// to unify with the Neutrino implementation.
293
type filteredBlock struct {
294
        hash   chainhash.Hash
295
        height uint32
296
        block  *btcutil.Block
297

298
        // connected is true if this update is a new block and false if it is a
299
        // disconnected block.
300
        connect bool
301
}
302

303
// onBlockDisconnected implements on OnBlockDisconnected callback for rpcclient.
304
func (b *BtcdNotifier) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) {
1✔
305
        // Append this new chain update to the end of the queue of new chain
1✔
306
        // updates.
1✔
307
        select {
1✔
308
        case b.chainUpdates.ChanIn() <- &chainUpdate{
309
                blockHash:   hash,
310
                blockHeight: height,
311
                connect:     false,
312
        }:
1✔
313
        case <-b.quit:
×
314
                return
×
315
        }
316
}
317

318
// onRedeemingTx implements on OnRedeemingTx callback for rpcclient.
319
func (b *BtcdNotifier) onRedeemingTx(tx *btcutil.Tx, details *btcjson.BlockDetails) {
1✔
320
        // Append this new transaction update to the end of the queue of new
1✔
321
        // chain updates.
1✔
322
        select {
1✔
323
        case b.txUpdates.ChanIn() <- &txUpdate{tx, details}:
1✔
324
        case <-b.quit:
×
325
                return
×
326
        }
327
}
328

329
// notificationDispatcher is the primary goroutine which handles client
330
// notification registrations, as well as notification dispatches.
331
func (b *BtcdNotifier) notificationDispatcher() {
1✔
332
        defer b.wg.Done()
1✔
333

1✔
334
out:
1✔
335
        for {
2✔
336
                select {
1✔
337
                case cancelMsg := <-b.notificationCancels:
1✔
338
                        switch msg := cancelMsg.(type) {
1✔
339
                        case *epochCancel:
1✔
340
                                chainntnfs.Log.Infof("Cancelling epoch "+
1✔
341
                                        "notification, epoch_id=%v", msg.epochID)
1✔
342

1✔
343
                                // First, we'll lookup the original
1✔
344
                                // registration in order to stop the active
1✔
345
                                // queue goroutine.
1✔
346
                                reg := b.blockEpochClients[msg.epochID]
1✔
347
                                reg.epochQueue.Stop()
1✔
348

1✔
349
                                // Next, close the cancel channel for this
1✔
350
                                // specific client, and wait for the client to
1✔
351
                                // exit.
1✔
352
                                close(b.blockEpochClients[msg.epochID].cancelChan)
1✔
353
                                b.blockEpochClients[msg.epochID].wg.Wait()
1✔
354

1✔
355
                                // Once the client has exited, we can then
1✔
356
                                // safely close the channel used to send epoch
1✔
357
                                // notifications, in order to notify any
1✔
358
                                // listeners that the intent has been
1✔
359
                                // canceled.
1✔
360
                                close(b.blockEpochClients[msg.epochID].epochChan)
1✔
361
                                delete(b.blockEpochClients, msg.epochID)
1✔
362
                        }
363
                case registerMsg := <-b.notificationRegistry:
1✔
364
                        switch msg := registerMsg.(type) {
1✔
365
                        case *chainntnfs.HistoricalConfDispatch:
1✔
366
                                // Look up whether the transaction/output script
1✔
367
                                // has already confirmed in the active chain.
1✔
368
                                // We'll do this in a goroutine to prevent
1✔
369
                                // blocking potentially long rescans.
1✔
370
                                //
1✔
371
                                // TODO(wilmer): add retry logic if rescan fails?
1✔
372
                                b.wg.Add(1)
1✔
373

1✔
374
                                //nolint:lll
1✔
375
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
2✔
376
                                        defer b.wg.Done()
1✔
377

1✔
378
                                        confDetails, _, err := b.historicalConfDetails(
1✔
379
                                                msg.ConfRequest,
1✔
380
                                                msg.StartHeight, msg.EndHeight,
1✔
381
                                        )
1✔
382
                                        if err != nil {
1✔
383
                                                chainntnfs.Log.Error(err)
×
384
                                                return
×
385
                                        }
×
386

387
                                        // If the historical dispatch finished
388
                                        // without error, we will invoke
389
                                        // UpdateConfDetails even if none were
390
                                        // found. This allows the notifier to
391
                                        // begin safely updating the height hint
392
                                        // cache at tip, since any pending
393
                                        // rescans have now completed.
394
                                        err = b.txNotifier.UpdateConfDetails(
1✔
395
                                                msg.ConfRequest, confDetails,
1✔
396
                                        )
1✔
397
                                        if err != nil {
1✔
398
                                                chainntnfs.Log.Error(err)
×
399
                                        }
×
400
                                }(msg)
401

402
                        case *blockEpochRegistration:
1✔
403
                                chainntnfs.Log.Infof("New block epoch subscription")
1✔
404

1✔
405
                                b.blockEpochClients[msg.epochID] = msg
1✔
406

1✔
407
                                // If the client did not provide their best
1✔
408
                                // known block, then we'll immediately dispatch
1✔
409
                                // a notification for the current tip.
1✔
410
                                if msg.bestBlock == nil {
2✔
411
                                        b.notifyBlockEpochClient(
1✔
412
                                                msg, b.bestBlock.Height,
1✔
413
                                                b.bestBlock.Hash,
1✔
414
                                                b.bestBlock.BlockHeader,
1✔
415
                                        )
1✔
416

1✔
417
                                        msg.errorChan <- nil
1✔
418
                                        continue
1✔
419
                                }
420

421
                                // Otherwise, we'll attempt to deliver the
422
                                // backlog of notifications from their best
423
                                // known block.
424
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
1✔
425
                                        b.chainConn, msg.bestBlock,
1✔
426
                                        b.bestBlock.Height, true,
1✔
427
                                )
1✔
428
                                if err != nil {
1✔
429
                                        msg.errorChan <- err
×
430
                                        continue
×
431
                                }
432

433
                                for _, block := range missedBlocks {
1✔
434
                                        b.notifyBlockEpochClient(
×
435
                                                msg, block.Height, block.Hash,
×
436
                                                block.BlockHeader,
×
437
                                        )
×
438
                                }
×
439

440
                                msg.errorChan <- nil
1✔
441
                        }
442

443
                case item := <-b.chainUpdates.ChanOut():
1✔
444
                        update := item.(*chainUpdate)
1✔
445
                        if update.connect {
2✔
446
                                blockHeader, err := b.chainConn.GetBlockHeader(
1✔
447
                                        update.blockHash,
1✔
448
                                )
1✔
449
                                if err != nil {
1✔
450
                                        chainntnfs.Log.Errorf("Unable to fetch "+
×
451
                                                "block header: %v", err)
×
452
                                        continue
×
453
                                }
454

455
                                if blockHeader.PrevBlock != *b.bestBlock.Hash {
1✔
UNCOV
456
                                        // Handle the case where the notifier
×
UNCOV
457
                                        // missed some blocks from its chain
×
UNCOV
458
                                        // backend
×
UNCOV
459
                                        chainntnfs.Log.Infof("Missed blocks, " +
×
UNCOV
460
                                                "attempting to catch up")
×
UNCOV
461
                                        newBestBlock, missedBlocks, err :=
×
UNCOV
462
                                                chainntnfs.HandleMissedBlocks(
×
UNCOV
463
                                                        b.chainConn,
×
UNCOV
464
                                                        b.txNotifier,
×
UNCOV
465
                                                        b.bestBlock,
×
UNCOV
466
                                                        update.blockHeight,
×
UNCOV
467
                                                        true,
×
UNCOV
468
                                                )
×
UNCOV
469
                                        if err != nil {
×
UNCOV
470
                                                // Set the bestBlock here in case
×
UNCOV
471
                                                // a catch up partially completed.
×
UNCOV
472
                                                b.bestBlock = newBestBlock
×
UNCOV
473
                                                chainntnfs.Log.Error(err)
×
UNCOV
474
                                                continue
×
475
                                        }
476

UNCOV
477
                                        for _, block := range missedBlocks {
×
UNCOV
478
                                                err := b.handleBlockConnected(block)
×
UNCOV
479
                                                if err != nil {
×
480
                                                        chainntnfs.Log.Error(err)
×
481
                                                        continue out
×
482
                                                }
483
                                        }
484
                                }
485

486
                                newBlock := chainntnfs.BlockEpoch{
1✔
487
                                        Height:      update.blockHeight,
1✔
488
                                        Hash:        update.blockHash,
1✔
489
                                        BlockHeader: blockHeader,
1✔
490
                                }
1✔
491
                                if err := b.handleBlockConnected(newBlock); err != nil {
1✔
492
                                        chainntnfs.Log.Error(err)
×
493
                                }
×
494
                                continue
1✔
495
                        }
496

497
                        if update.blockHeight != b.bestBlock.Height {
2✔
498
                                chainntnfs.Log.Infof("Missed disconnected" +
1✔
499
                                        "blocks, attempting to catch up")
1✔
500
                        }
1✔
501

502
                        newBestBlock, err := chainntnfs.RewindChain(
1✔
503
                                b.chainConn, b.txNotifier, b.bestBlock,
1✔
504
                                update.blockHeight-1,
1✔
505
                        )
1✔
506
                        if err != nil {
2✔
507
                                chainntnfs.Log.Errorf("Unable to rewind chain "+
1✔
508
                                        "from height %d to height %d: %v",
1✔
509
                                        b.bestBlock.Height, update.blockHeight-1, err)
1✔
510
                        }
1✔
511

512
                        // Set the bestBlock here in case a chain rewind
513
                        // partially completed.
514
                        b.bestBlock = newBestBlock
1✔
515

516
                case item := <-b.txUpdates.ChanOut():
1✔
517
                        newSpend := item.(*txUpdate)
1✔
518
                        tx := newSpend.tx
1✔
519

1✔
520
                        // Init values.
1✔
521
                        isMempool := false
1✔
522
                        height := uint32(0)
1✔
523

1✔
524
                        // Unwrap values.
1✔
525
                        if newSpend.details == nil {
2✔
526
                                isMempool = true
1✔
527
                        } else {
2✔
528
                                height = uint32(newSpend.details.Height)
1✔
529
                        }
1✔
530

531
                        // Handle the transaction.
532
                        b.handleRelevantTx(tx, isMempool, height)
1✔
533

534
                case <-b.quit:
1✔
535
                        break out
1✔
536
                }
537
        }
538
}
539

540
// handleRelevantTx handles a new transaction that has been seen either in a
541
// block or in the mempool. If in mempool, it will ask the mempool notifier to
542
// handle it. If in a block, it will ask the txNotifier to handle it, and
543
// cancel any relevant subscriptions made in the mempool.
544
func (b *BtcdNotifier) handleRelevantTx(tx *btcutil.Tx,
545
        mempool bool, height uint32) {
1✔
546

1✔
547
        // If this is a mempool spend, we'll ask the mempool notifier to hanlde
1✔
548
        // it.
1✔
549
        if mempool {
2✔
550
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
1✔
551
                if err != nil {
1✔
552
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
553
                                "%v: %v", tx.Hash(), err)
×
554
                }
×
555

556
                return
1✔
557
        }
558

559
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
560
        // to handle it.
561
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
1✔
562
        if err != nil {
1✔
563
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
564
                        tx.Hash(), err)
×
565

×
566
                return
×
567
        }
×
568

569
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
570
        // the input.
571
        //
572
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
573
        // but choose to implement it here so we can easily decouple the two
574
        // notifiers in the future.
575
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
1✔
576
}
577

578
// historicalConfDetails looks up whether a confirmation request (txid/output
579
// script) has already been included in a block in the active chain and, if so,
580
// returns details about said block.
581
func (b *BtcdNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
582
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
583
        chainntnfs.TxConfStatus, error) {
1✔
584

1✔
585
        // If a txid was not provided, then we should dispatch upon seeing the
1✔
586
        // script on-chain, so we'll short-circuit straight to scanning manually
1✔
587
        // as there doesn't exist a script index to query.
1✔
588
        if confRequest.TxID == chainntnfs.ZeroHash {
1✔
589
                return b.confDetailsManually(
×
590
                        confRequest, startHeight, endHeight,
×
591
                )
×
592
        }
×
593

594
        // Otherwise, we'll dispatch upon seeing a transaction on-chain with the
595
        // given hash.
596
        //
597
        // We'll first attempt to retrieve the transaction using the node's
598
        // txindex.
599
        txNotFoundErr := "No information available about transaction"
1✔
600
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
1✔
601
                b.chainConn, confRequest, txNotFoundErr,
1✔
602
        )
1✔
603

1✔
604
        // We'll then check the status of the transaction lookup returned to
1✔
605
        // determine whether we should proceed with any fallback methods.
1✔
606
        switch {
1✔
607

608
        // We failed querying the index for the transaction, fall back to
609
        // scanning manually.
610
        case err != nil:
×
611
                chainntnfs.Log.Debugf("Unable to determine confirmation of %v "+
×
612
                        "through the backend's txindex (%v), scanning manually",
×
613
                        confRequest.TxID, err)
×
614

×
615
                return b.confDetailsManually(
×
616
                        confRequest, startHeight, endHeight,
×
617
                )
×
618

619
        // The transaction was found within the node's mempool.
620
        case txStatus == chainntnfs.TxFoundMempool:
1✔
621

622
        // The transaction was found within the node's txindex.
623
        case txStatus == chainntnfs.TxFoundIndex:
1✔
624

625
        // The transaction was not found within the node's mempool or txindex.
626
        case txStatus == chainntnfs.TxNotFoundIndex:
1✔
627

628
        // Unexpected txStatus returned.
629
        default:
×
630
                return nil, txStatus,
×
631
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
632
        }
633

634
        return txConf, txStatus, nil
1✔
635
}
636

637
// confDetailsManually looks up whether a transaction/output script has already
638
// been included in a block in the active chain by scanning the chain's blocks
639
// within the given range. If the transaction/output script is found, its
640
// confirmation details are returned. Otherwise, nil is returned.
641
func (b *BtcdNotifier) confDetailsManually(confRequest chainntnfs.ConfRequest,
642
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
643
        chainntnfs.TxConfStatus, error) {
×
644

×
645
        // Begin scanning blocks at every height to determine where the
×
646
        // transaction was included in.
×
647
        for height := endHeight; height >= startHeight && height > 0; height-- {
×
648
                // Ensure we haven't been requested to shut down before
×
649
                // processing the next height.
×
650
                select {
×
651
                case <-b.quit:
×
652
                        return nil, chainntnfs.TxNotFoundManually,
×
653
                                chainntnfs.ErrChainNotifierShuttingDown
×
654
                default:
×
655
                }
656

657
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
658
                if err != nil {
×
659
                        return nil, chainntnfs.TxNotFoundManually,
×
660
                                fmt.Errorf("unable to get hash from block "+
×
661
                                        "with height %d", height)
×
662
                }
×
663

664
                // TODO: fetch the neutrino filters instead.
665
                block, err := b.GetBlock(blockHash)
×
666
                if err != nil {
×
667
                        return nil, chainntnfs.TxNotFoundManually,
×
668
                                fmt.Errorf("unable to get block with hash "+
×
669
                                        "%v: %v", blockHash, err)
×
670
                }
×
671

672
                // For every transaction in the block, check which one matches
673
                // our request. If we find one that does, we can dispatch its
674
                // confirmation details.
675
                for txIndex, tx := range block.Transactions {
×
676
                        if !confRequest.MatchesTx(tx) {
×
677
                                continue
×
678
                        }
679

680
                        return &chainntnfs.TxConfirmation{
×
681
                                Tx:          tx.Copy(),
×
682
                                BlockHash:   blockHash,
×
683
                                BlockHeight: height,
×
684
                                TxIndex:     uint32(txIndex),
×
685
                                Block:       block,
×
686
                        }, chainntnfs.TxFoundManually, nil
×
687
                }
688
        }
689

690
        // If we reach here, then we were not able to find the transaction
691
        // within a block, so we avoid returning an error.
692
        return nil, chainntnfs.TxNotFoundManually, nil
×
693
}
694

695
// handleBlockConnected applies a chain update for a new block. Any watched
696
// transactions included this block will processed to either send notifications
697
// now or after numConfirmations confs.
698
// TODO(halseth): this is reusing the neutrino notifier implementation, unify
699
// them.
700
func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error {
1✔
701
        // First, we'll fetch the raw block as we'll need to gather all the
1✔
702
        // transactions to determine whether any are relevant to our registered
1✔
703
        // clients.
1✔
704
        rawBlock, err := b.GetBlock(epoch.Hash)
1✔
705
        if err != nil {
1✔
706
                return fmt.Errorf("unable to get block: %w", err)
×
707
        }
×
708
        newBlock := &filteredBlock{
1✔
709
                hash:    *epoch.Hash,
1✔
710
                height:  uint32(epoch.Height),
1✔
711
                block:   btcutil.NewBlock(rawBlock),
1✔
712
                connect: true,
1✔
713
        }
1✔
714

1✔
715
        // We'll then extend the txNotifier's height with the information of
1✔
716
        // this new block, which will handle all of the notification logic for
1✔
717
        // us.
1✔
718
        err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height)
1✔
719
        if err != nil {
1✔
720
                return fmt.Errorf("unable to connect tip: %w", err)
×
721
        }
×
722

723
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
1✔
724
                epoch.Hash)
1✔
725

1✔
726
        // Now that we've guaranteed the new block extends the txNotifier's
1✔
727
        // current tip, we'll proceed to dispatch notifications to all of our
1✔
728
        // registered clients whom have had notifications fulfilled. Before
1✔
729
        // doing so, we'll make sure update our in memory state in order to
1✔
730
        // satisfy any client requests based upon the new block.
1✔
731
        b.bestBlock = epoch
1✔
732

1✔
733
        b.notifyBlockEpochs(
1✔
734
                epoch.Height, epoch.Hash, epoch.BlockHeader,
1✔
735
        )
1✔
736

1✔
737
        return b.txNotifier.NotifyHeight(uint32(epoch.Height))
1✔
738
}
739

740
// notifyBlockEpochs notifies all registered block epoch clients of the newly
741
// connected block to the main chain.
742
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
743
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
744

1✔
745
        for _, client := range b.blockEpochClients {
2✔
746
                b.notifyBlockEpochClient(
1✔
747
                        client, newHeight, newSha, blockHeader,
1✔
748
                )
1✔
749
        }
1✔
750
}
751

752
// notifyBlockEpochClient sends a registered block epoch client a notification
753
// about a specific block.
754
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
755
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
756

1✔
757
        epoch := &chainntnfs.BlockEpoch{
1✔
758
                Height:      height,
1✔
759
                Hash:        sha,
1✔
760
                BlockHeader: blockHeader,
1✔
761
        }
1✔
762

1✔
763
        select {
1✔
764
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
765
        case <-epochClient.cancelChan:
×
766
        case <-b.quit:
×
767
        }
768
}
769

770
// RegisterSpendNtfn registers an intent to be notified once the target
771
// outpoint/output script has been spent by a transaction on-chain. When
772
// intending to be notified of the spend of an output script, a nil outpoint
773
// must be used. The heightHint should represent the earliest height in the
774
// chain of the transaction that spent the outpoint/output script.
775
//
776
// Once a spend of has been detected, the details of the spending event will be
777
// sent across the 'Spend' channel.
778
func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
779
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
1✔
780

1✔
781
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
782
        // for `dispatch` will be returned if we are required to perform a
1✔
783
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
784
        // watching at tip for the transaction to confirm.
1✔
785
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
1✔
786
        if err != nil {
2✔
787
                return nil, err
1✔
788
        }
1✔
789

790
        // We'll then request the backend to notify us when it has detected the
791
        // outpoint/output script as spent.
792
        //
793
        // TODO(wilmer): use LoadFilter API instead.
794
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
1✔
795
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
796
                        pkScript, b.chainParams,
×
797
                )
×
798
                if err != nil {
×
799
                        return nil, fmt.Errorf("unable to parse script: %w",
×
800
                                err)
×
801
                }
×
802
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
×
803
                        return nil, err
×
804
                }
×
805
        } else {
1✔
806
                ops := []*wire.OutPoint{outpoint}
1✔
807
                if err := b.chainConn.NotifySpent(ops); err != nil {
1✔
808
                        return nil, err
×
809
                }
×
810
        }
811

812
        // If the txNotifier didn't return any details to perform a historical
813
        // scan of the chain, then we can return early as there's nothing left
814
        // for us to do.
815
        if ntfn.HistoricalDispatch == nil {
2✔
816
                return ntfn.Event, nil
1✔
817
        }
1✔
818

819
        // Otherwise, we'll need to dispatch a historical rescan to determine if
820
        // the outpoint was already spent at a previous height.
821
        //
822
        // We'll short-circuit the path when dispatching the spend of a script,
823
        // rather than an outpoint, as there aren't any additional checks we can
824
        // make for scripts.
825
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
1✔
826
                startHash, err := b.chainConn.GetBlockHash(
×
827
                        int64(ntfn.HistoricalDispatch.StartHeight),
×
828
                )
×
829
                if err != nil {
×
830
                        return nil, err
×
831
                }
×
832

833
                // TODO(wilmer): add retry logic if rescan fails?
834
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
835
                        pkScript, b.chainParams,
×
836
                )
×
837
                if err != nil {
×
838
                        return nil, fmt.Errorf("unable to parse address: %w",
×
839
                                err)
×
840
                }
×
841

842
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
×
843
                go func() {
×
844
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
×
845
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
846
                                        "the spend details of %v failed: %v",
×
847
                                        ntfn.HistoricalDispatch.SpendRequest,
×
848
                                        rescanErr)
×
849
                        }
×
850
                }()
851

852
                return ntfn.Event, nil
×
853
        }
854

855
        // When dispatching spends of outpoints, there are a number of checks we
856
        // can make to start our rescan from a better height or completely avoid
857
        // it.
858
        //
859
        // We'll start by checking the backend's UTXO set to determine whether
860
        // the outpoint has been spent. If it hasn't, we can return to the
861
        // caller as well.
862
        txOut, err := b.chainConn.GetTxOut(&outpoint.Hash, outpoint.Index, true)
1✔
863
        if err != nil {
1✔
864
                return nil, err
×
865
        }
×
866
        if txOut != nil {
2✔
867
                // We'll let the txNotifier know the outpoint is still unspent
1✔
868
                // in order to begin updating its spend hint.
1✔
869
                err := b.txNotifier.UpdateSpendDetails(
1✔
870
                        ntfn.HistoricalDispatch.SpendRequest, nil,
1✔
871
                )
1✔
872
                if err != nil {
1✔
873
                        return nil, err
×
874
                }
×
875

876
                return ntfn.Event, nil
1✔
877
        }
878

879
        // Since the outpoint was spent, as it no longer exists within the UTXO
880
        // set, we'll determine when it happened by scanning the chain. We'll
881
        // begin by fetching the block hash of our starting height.
882
        startHash, err := b.chainConn.GetBlockHash(
1✔
883
                int64(ntfn.HistoricalDispatch.StartHeight),
1✔
884
        )
1✔
885
        if err != nil {
1✔
886
                return nil, fmt.Errorf("unable to get block hash for height "+
×
887
                        "%d: %v", ntfn.HistoricalDispatch.StartHeight, err)
×
888
        }
×
889

890
        // As a minimal optimization, we'll query the backend's transaction
891
        // index (if enabled) to determine if we have a better rescan starting
892
        // height. We can do this as the GetRawTransaction call will return the
893
        // hash of the block it was included in within the chain.
894
        tx, err := b.chainConn.GetRawTransactionVerbose(&outpoint.Hash)
1✔
895
        if err != nil {
2✔
896
                // Avoid returning an error if the transaction was not found to
1✔
897
                // proceed with fallback methods.
1✔
898
                jsonErr, ok := err.(*btcjson.RPCError)
1✔
899
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
1✔
900
                        return nil, fmt.Errorf("unable to query for txid %v: "+
×
901
                                "%w", outpoint.Hash, err)
×
902
                }
×
903
        }
904

905
        // If the transaction index was enabled, we'll use the block's hash to
906
        // retrieve its height and check whether it provides a better starting
907
        // point for our rescan.
908
        if tx != nil {
2✔
909
                // If the transaction containing the outpoint hasn't confirmed
1✔
910
                // on-chain, then there's no need to perform a rescan.
1✔
911
                if tx.BlockHash == "" {
2✔
912
                        return ntfn.Event, nil
1✔
913
                }
1✔
914

915
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
916
                if err != nil {
1✔
917
                        return nil, err
×
918
                }
×
919
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
1✔
920
                if err != nil {
1✔
921
                        return nil, fmt.Errorf("unable to get header for "+
×
922
                                "block %v: %v", blockHash, err)
×
923
                }
×
924

925
                if uint32(blockHeader.Height) > ntfn.HistoricalDispatch.StartHeight {
2✔
926
                        startHash, err = b.chainConn.GetBlockHash(
1✔
927
                                int64(blockHeader.Height),
1✔
928
                        )
1✔
929
                        if err != nil {
1✔
930
                                return nil, fmt.Errorf("unable to get block "+
×
931
                                        "hash for height %d: %v",
×
932
                                        blockHeader.Height, err)
×
933
                        }
×
934
                }
935
        }
936

937
        // Now that we've determined the best starting point for our rescan,
938
        // we can go ahead and dispatch it.
939
        //
940
        // In order to ensure that we don't block the caller on what may be a
941
        // long rescan, we'll launch a new goroutine to handle the async result
942
        // of the rescan. We purposefully prevent from adding this goroutine to
943
        // the WaitGroup as we cannot wait for a quit signal due to the
944
        // asyncResult channel not being exposed.
945
        //
946
        // TODO(wilmer): add retry logic if rescan fails?
947
        asyncResult := b.chainConn.RescanAsync(
1✔
948
                startHash, nil, []*wire.OutPoint{outpoint},
1✔
949
        )
1✔
950
        go func() {
2✔
951
                if rescanErr := asyncResult.Receive(); rescanErr != nil {
1✔
952
                        chainntnfs.Log.Errorf("Rescan to determine the spend "+
×
953
                                "details of %v failed: %v", outpoint, rescanErr)
×
954
                }
×
955
        }()
956

957
        return ntfn.Event, nil
1✔
958
}
959

960
// RegisterConfirmationsNtfn registers an intent to be notified once the target
961
// txid/output script has reached numConfs confirmations on-chain. When
962
// intending to be notified of the confirmation of an output script, a nil txid
963
// must be used. The heightHint should represent the earliest height at which
964
// the txid/output script could have been included in the chain.
965
//
966
// Progress on the number of confirmations left can be read from the 'Updates'
967
// channel. Once it has reached all of its confirmations, a notification will be
968
// sent across the 'Confirmed' channel.
969
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
970
        pkScript []byte, numConfs, heightHint uint32,
971
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
1✔
972

1✔
973
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
974
        // for `dispatch` will be returned if we are required to perform a
1✔
975
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
976
        // watching at tip for the transaction to confirm.
1✔
977
        ntfn, err := b.txNotifier.RegisterConf(
1✔
978
                txid, pkScript, numConfs, heightHint, opts...,
1✔
979
        )
1✔
980
        if err != nil {
1✔
981
                return nil, err
×
982
        }
×
983

984
        if ntfn.HistoricalDispatch == nil {
2✔
985
                return ntfn.Event, nil
1✔
986
        }
1✔
987

988
        select {
1✔
989
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
990
                return ntfn.Event, nil
1✔
991
        case <-b.quit:
×
992
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
993
        }
994
}
995

996
// blockEpochRegistration represents a client's intent to receive a
997
// notification with each newly connected block.
998
type blockEpochRegistration struct {
999
        epochID uint64
1000

1001
        epochChan chan *chainntnfs.BlockEpoch
1002

1003
        epochQueue *queue.ConcurrentQueue
1004

1005
        bestBlock *chainntnfs.BlockEpoch
1006

1007
        errorChan chan error
1008

1009
        cancelChan chan struct{}
1010

1011
        wg sync.WaitGroup
1012
}
1013

1014
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1015
// cancel an outstanding epoch notification that has yet to be dispatched.
1016
type epochCancel struct {
1017
        epochID uint64
1018
}
1019

1020
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1021
// caller to receive notifications, of each new block connected to the main
1022
// chain. Clients have the option of passing in their best known block, which
1023
// the notifier uses to check if they are behind on blocks and catch them up. If
1024
// they do not provide one, then a notification will be dispatched immediately
1025
// for the current tip of the chain upon a successful registration.
1026
func (b *BtcdNotifier) RegisterBlockEpochNtfn(
1027
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
1✔
1028

1✔
1029
        reg := &blockEpochRegistration{
1✔
1030
                epochQueue: queue.NewConcurrentQueue(20),
1✔
1031
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
1032
                cancelChan: make(chan struct{}),
1✔
1033
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
1034
                bestBlock:  bestBlock,
1✔
1035
                errorChan:  make(chan error, 1),
1✔
1036
        }
1✔
1037

1✔
1038
        reg.epochQueue.Start()
1✔
1039

1✔
1040
        // Before we send the request to the main goroutine, we'll launch a new
1✔
1041
        // goroutine to proxy items added to our queue to the client itself.
1✔
1042
        // This ensures that all notifications are received *in order*.
1✔
1043
        reg.wg.Add(1)
1✔
1044
        go func() {
2✔
1045
                defer reg.wg.Done()
1✔
1046

1✔
1047
                for {
2✔
1048
                        select {
1✔
1049
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
1050
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
1051
                                select {
1✔
1052
                                case reg.epochChan <- blockNtfn:
1✔
1053

1054
                                case <-reg.cancelChan:
1✔
1055
                                        return
1✔
1056

1057
                                case <-b.quit:
×
1058
                                        return
×
1059
                                }
1060

1061
                        case <-reg.cancelChan:
1✔
1062
                                return
1✔
1063

1064
                        case <-b.quit:
1✔
1065
                                return
1✔
1066
                        }
1067
                }
1068
        }()
1069

1070
        select {
1✔
1071
        case <-b.quit:
×
1072
                // As we're exiting before the registration could be sent,
×
1073
                // we'll stop the queue now ourselves.
×
1074
                reg.epochQueue.Stop()
×
1075

×
1076
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1077
                        "attempting to register for block epoch notification.")
×
1078
        case b.notificationRegistry <- reg:
1✔
1079
                return &chainntnfs.BlockEpochEvent{
1✔
1080
                        Epochs: reg.epochChan,
1✔
1081
                        Cancel: func() {
2✔
1082
                                cancel := &epochCancel{
1✔
1083
                                        epochID: reg.epochID,
1✔
1084
                                }
1✔
1085

1✔
1086
                                // Submit epoch cancellation to notification dispatcher.
1✔
1087
                                select {
1✔
1088
                                case b.notificationCancels <- cancel:
1✔
1089
                                        // Cancellation is being handled, drain
1✔
1090
                                        // the epoch channel until it is closed
1✔
1091
                                        // before yielding to caller.
1✔
1092
                                        for {
2✔
1093
                                                select {
1✔
1094
                                                case _, ok := <-reg.epochChan:
1✔
1095
                                                        if !ok {
2✔
1096
                                                                return
1✔
1097
                                                        }
1✔
1098
                                                case <-b.quit:
1✔
1099
                                                        return
1✔
1100
                                                }
1101
                                        }
1102
                                case <-b.quit:
1✔
1103
                                }
1104
                        },
1105
                }, nil
1106
        }
1107
}
1108

1109
// GetBlock is used to retrieve the block with the given hash. This function
1110
// wraps the blockCache's GetBlock function.
1111
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1112
        error) {
1✔
1113

1✔
1114
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1115
}
1✔
1116

1117
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1118
// for a spend of an outpoint in the mempool.The event will be dispatched once
1119
// the outpoint is spent in the mempool.
1120
//
1121
// NOTE: part of the MempoolWatcher interface.
1122
func (b *BtcdNotifier) SubscribeMempoolSpent(
1123
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1124

1✔
1125
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1126

1✔
1127
        ops := []*wire.OutPoint{&outpoint}
1✔
1128

1✔
1129
        return event, b.chainConn.NotifySpent(ops)
1✔
1130
}
1✔
1131

1132
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1133
// for a spend of an outpoint in the mempool.
1134
//
1135
// NOTE: part of the MempoolWatcher interface.
1136
func (b *BtcdNotifier) CancelMempoolSpendEvent(
1137
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1138

1✔
1139
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1140
}
1✔
1141

1142
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1143
// its spending tx. Returns the tx if found, otherwise fn.None.
1144
//
1145
// NOTE: part of the MempoolWatcher interface.
1146
func (b *BtcdNotifier) LookupInputMempoolSpend(
1147
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1148

1✔
1149
        // Find the spending txid.
1✔
1150
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1151
        if !found {
2✔
1152
                return fn.None[wire.MsgTx]()
1✔
1153
        }
1✔
1154

1155
        // Query the spending tx using the id.
1156
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1157
        if err != nil {
2✔
1158
                // TODO(yy): enable logging errors in this package.
1✔
1159
                return fn.None[wire.MsgTx]()
1✔
1160
        }
1✔
1161

1162
        return fn.Some(*tx.MsgTx().Copy())
1✔
1163
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc