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

lightningnetwork / lnd / 14475117777

15 Apr 2025 04:59PM UTC coverage: 58.578% (-10.5%) from 69.084%
14475117777

Pull #9721

github

web-flow
Merge 52078978b into 06f1ef47f
Pull Request #9721: feat(lncli): Add --route_hints flag to sendpayment and queryroutes

97136 of 165824 relevant lines covered (58.58%)

1.82 hits per line

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

70.43
/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/v2"
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
        ntfnCallbacks := &rpcclient.NotificationHandlers{
1✔
133
                OnBlockConnected:    notifier.onBlockConnected,
1✔
134
                OnBlockDisconnected: notifier.onBlockDisconnected,
1✔
135
                OnRedeemingTx:       notifier.onRedeemingTx,
1✔
136
        }
1✔
137

1✔
138
        rpcCfg := &chain.RPCClientConfig{
1✔
139
                ReconnectAttempts:    20,
1✔
140
                Conn:                 config,
1✔
141
                Chain:                chainParams,
1✔
142
                NotificationHandlers: ntfnCallbacks,
1✔
143
        }
1✔
144

1✔
145
        chainRPC, err := chain.NewRPCClientWithConfig(rpcCfg)
1✔
146
        if err != nil {
1✔
147
                return nil, err
×
148
        }
×
149

150
        notifier.chainConn = chainRPC
1✔
151

1✔
152
        return notifier, nil
1✔
153
}
154

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

163
        return startErr
1✔
164
}
165

166
// Started returns true if this instance has been started, and false otherwise.
167
func (b *BtcdNotifier) Started() bool {
1✔
168
        return atomic.LoadInt32(&b.active) != 0
1✔
169
}
1✔
170

171
// Stop shutsdown the BtcdNotifier.
172
func (b *BtcdNotifier) Stop() error {
1✔
173
        // Already shutting down?
1✔
174
        if atomic.AddInt32(&b.stopped, 1) != 1 {
1✔
175
                return nil
×
176
        }
×
177

178
        chainntnfs.Log.Info("btcd notifier shutting down...")
1✔
179
        defer chainntnfs.Log.Debug("btcd notifier shutdown complete")
1✔
180

1✔
181
        // Shutdown the rpc client, this gracefully disconnects from btcd, and
1✔
182
        // cleans up all related resources.
1✔
183
        b.chainConn.Stop()
1✔
184

1✔
185
        close(b.quit)
1✔
186
        b.wg.Wait()
1✔
187

1✔
188
        b.chainUpdates.Stop()
1✔
189
        b.txUpdates.Stop()
1✔
190

1✔
191
        // Notify all pending clients of our shutdown by closing the related
1✔
192
        // notification channels.
1✔
193
        for _, epochClient := range b.blockEpochClients {
2✔
194
                close(epochClient.cancelChan)
1✔
195
                epochClient.wg.Wait()
1✔
196

1✔
197
                close(epochClient.epochChan)
1✔
198
        }
1✔
199
        b.txNotifier.TearDown()
1✔
200

1✔
201
        // Stop the mempool notifier.
1✔
202
        b.memNotifier.TearDown()
1✔
203

1✔
204
        return nil
1✔
205
}
206

207
// startNotifier is the main starting point for the BtcdNotifier. It connects
208
// to btcd and start the main dispatcher goroutine.
209
func (b *BtcdNotifier) startNotifier() error {
1✔
210
        chainntnfs.Log.Infof("btcd notifier starting...")
1✔
211

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

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

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

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

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

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

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

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

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

1✔
264
        chainntnfs.Log.Debugf("btcd notifier started")
1✔
265

1✔
266
        return nil
1✔
267
}
268

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

557
                return
1✔
558
        }
559

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

×
567
                return
×
568
        }
×
569

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
734
        err = b.txNotifier.NotifyHeight(uint32(epoch.Height))
1✔
735
        if err != nil {
1✔
736
                return fmt.Errorf("unable to notify height: %w", err)
×
737
        }
×
738

739
        b.notifyBlockEpochs(
1✔
740
                epoch.Height, epoch.Hash, epoch.BlockHeader,
1✔
741
        )
1✔
742

1✔
743
        return nil
1✔
744
}
745

746
// notifyBlockEpochs notifies all registered block epoch clients of the newly
747
// connected block to the main chain.
748
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
749
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
750

1✔
751
        for _, client := range b.blockEpochClients {
2✔
752
                b.notifyBlockEpochClient(
1✔
753
                        client, newHeight, newSha, blockHeader,
1✔
754
                )
1✔
755
        }
1✔
756
}
757

758
// notifyBlockEpochClient sends a registered block epoch client a notification
759
// about a specific block.
760
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
761
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
762

1✔
763
        epoch := &chainntnfs.BlockEpoch{
1✔
764
                Height:      height,
1✔
765
                Hash:        sha,
1✔
766
                BlockHeader: blockHeader,
1✔
767
        }
1✔
768

1✔
769
        select {
1✔
770
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
771
        case <-epochClient.cancelChan:
×
772
        case <-b.quit:
×
773
        }
774
}
775

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

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

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

818
        // If the txNotifier didn't return any details to perform a historical
819
        // scan of the chain, then we can return early as there's nothing left
820
        // for us to do.
821
        if ntfn.HistoricalDispatch == nil {
2✔
822
                return ntfn.Event, nil
1✔
823
        }
1✔
824

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

839
                // TODO(wilmer): add retry logic if rescan fails?
840
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
841
                        pkScript, b.chainParams,
×
842
                )
×
843
                if err != nil {
×
844
                        return nil, fmt.Errorf("unable to parse address: %w",
×
845
                                err)
×
846
                }
×
847

848
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
×
849
                go func() {
×
850
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
×
851
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
852
                                        "the spend details of %v failed: %v",
×
853
                                        ntfn.HistoricalDispatch.SpendRequest,
×
854
                                        rescanErr)
×
855
                        }
×
856
                }()
857

858
                return ntfn.Event, nil
×
859
        }
860

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

882
                return ntfn.Event, nil
1✔
883
        }
884

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

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

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

921
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
922
                if err != nil {
1✔
923
                        return nil, err
×
924
                }
×
925
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
1✔
926
                if err != nil {
1✔
927
                        return nil, fmt.Errorf("unable to get header for "+
×
928
                                "block %v: %v", blockHash, err)
×
929
                }
×
930

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

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

963
        return ntfn.Event, nil
1✔
964
}
965

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

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

990
        if ntfn.HistoricalDispatch == nil {
2✔
991
                return ntfn.Event, nil
1✔
992
        }
1✔
993

994
        select {
1✔
995
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
996
                return ntfn.Event, nil
1✔
997
        case <-b.quit:
×
998
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
999
        }
1000
}
1001

1002
// blockEpochRegistration represents a client's intent to receive a
1003
// notification with each newly connected block.
1004
type blockEpochRegistration struct {
1005
        epochID uint64
1006

1007
        epochChan chan *chainntnfs.BlockEpoch
1008

1009
        epochQueue *queue.ConcurrentQueue
1010

1011
        bestBlock *chainntnfs.BlockEpoch
1012

1013
        errorChan chan error
1014

1015
        cancelChan chan struct{}
1016

1017
        wg sync.WaitGroup
1018
}
1019

1020
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1021
// cancel an outstanding epoch notification that has yet to be dispatched.
1022
type epochCancel struct {
1023
        epochID uint64
1024
}
1025

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

1✔
1035
        reg := &blockEpochRegistration{
1✔
1036
                epochQueue: queue.NewConcurrentQueue(20),
1✔
1037
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
1038
                cancelChan: make(chan struct{}),
1✔
1039
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
1040
                bestBlock:  bestBlock,
1✔
1041
                errorChan:  make(chan error, 1),
1✔
1042
        }
1✔
1043

1✔
1044
        reg.epochQueue.Start()
1✔
1045

1✔
1046
        // Before we send the request to the main goroutine, we'll launch a new
1✔
1047
        // goroutine to proxy items added to our queue to the client itself.
1✔
1048
        // This ensures that all notifications are received *in order*.
1✔
1049
        reg.wg.Add(1)
1✔
1050
        go func() {
2✔
1051
                defer reg.wg.Done()
1✔
1052

1✔
1053
                for {
2✔
1054
                        select {
1✔
1055
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
1056
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
1057
                                select {
1✔
1058
                                case reg.epochChan <- blockNtfn:
1✔
1059

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

1063
                                case <-b.quit:
×
1064
                                        return
×
1065
                                }
1066

1067
                        case <-reg.cancelChan:
1✔
1068
                                return
1✔
1069

1070
                        case <-b.quit:
1✔
1071
                                return
1✔
1072
                        }
1073
                }
1074
        }()
1075

1076
        select {
1✔
1077
        case <-b.quit:
×
1078
                // As we're exiting before the registration could be sent,
×
1079
                // we'll stop the queue now ourselves.
×
1080
                reg.epochQueue.Stop()
×
1081

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

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

1115
// GetBlock is used to retrieve the block with the given hash. This function
1116
// wraps the blockCache's GetBlock function.
1117
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1118
        error) {
1✔
1119

1✔
1120
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1121
}
1✔
1122

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

1✔
1131
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1132

1✔
1133
        ops := []*wire.OutPoint{&outpoint}
1✔
1134

1✔
1135
        return event, b.chainConn.NotifySpent(ops)
1✔
1136
}
1✔
1137

1138
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1139
// for a spend of an outpoint in the mempool.
1140
//
1141
// NOTE: part of the MempoolWatcher interface.
1142
func (b *BtcdNotifier) CancelMempoolSpendEvent(
1143
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1144

1✔
1145
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1146
}
1✔
1147

1148
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1149
// its spending tx. Returns the tx if found, otherwise fn.None.
1150
//
1151
// NOTE: part of the MempoolWatcher interface.
1152
func (b *BtcdNotifier) LookupInputMempoolSpend(
1153
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1154

1✔
1155
        // Find the spending txid.
1✔
1156
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1157
        if !found {
2✔
1158
                return fn.None[wire.MsgTx]()
1✔
1159
        }
1✔
1160

1161
        // Query the spending tx using the id.
1162
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1163
        if err != nil {
1✔
1164
                // TODO(yy): enable logging errors in this package.
×
1165
                return fn.None[wire.MsgTx]()
×
1166
        }
×
1167

1168
        return fn.Some(*tx.MsgTx().Copy())
1✔
1169
}
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