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

lightningnetwork / lnd / 16177692143

09 Jul 2025 06:49PM UTC coverage: 55.317% (-2.3%) from 57.611%
16177692143

Pull #10060

github

web-flow
Merge 4aec413e3 into 0e830da9d
Pull Request #10060: sweep: fix expected spending events being missed

9 of 25 new or added lines in 1 file covered. (36.0%)

23713 existing lines in 281 files now uncovered.

108499 of 196142 relevant lines covered (55.32%)

22331.52 hits per line

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

72.64
/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) {
10✔
111

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

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

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

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

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

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

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

10✔
132
        ntfnCallbacks := &rpcclient.NotificationHandlers{
10✔
133
                OnBlockConnected:    notifier.onBlockConnected,
10✔
134
                OnBlockDisconnected: notifier.onBlockDisconnected,
10✔
135
                OnRedeemingTx:       notifier.onRedeemingTx,
10✔
136
        }
10✔
137

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

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

150
        notifier.chainConn = chainRPC
10✔
151

10✔
152
        return notifier, nil
10✔
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 {
7✔
158
        var startErr error
7✔
159
        b.start.Do(func() {
14✔
160
                startErr = b.startNotifier()
7✔
161
        })
7✔
162

163
        return startErr
7✔
164
}
165

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

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

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

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

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

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

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

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

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

6✔
204
        return nil
6✔
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 {
7✔
210
        chainntnfs.Log.Infof("btcd notifier starting...")
7✔
211

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

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

226
        // Before we fetch the best block/block height we need to register the
227
        // notifications for connected blocks, otherwise we might think we are
228
        // at an earlier block height because during block notification
229
        // registration we might have already mined some new blocks. Hence we
230
        // will not get notified accordingly.
231
        if err := b.chainConn.NotifyBlocks(); err != nil {
7✔
232
                b.txUpdates.Stop()
×
233
                b.chainUpdates.Stop()
×
234
                return err
×
235
        }
×
236

237
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
7✔
238
        if err != nil {
7✔
239
                b.txUpdates.Stop()
×
240
                b.chainUpdates.Stop()
×
241
                return err
×
242
        }
×
243

244
        bestBlock, err := b.chainConn.GetBlock(currentHash)
7✔
245
        if err != nil {
7✔
246
                b.txUpdates.Stop()
×
247
                b.chainUpdates.Stop()
×
248
                return err
×
249
        }
×
250

251
        b.txNotifier = chainntnfs.NewTxNotifier(
7✔
252
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
7✔
253
                b.confirmHintCache, b.spendHintCache,
7✔
254
        )
7✔
255

7✔
256
        b.bestBlock = chainntnfs.BlockEpoch{
7✔
257
                Height:      currentHeight,
7✔
258
                Hash:        currentHash,
7✔
259
                BlockHeader: &bestBlock.Header,
7✔
260
        }
7✔
261

7✔
262
        b.wg.Add(1)
7✔
263
        go b.notificationDispatcher()
7✔
264

7✔
265
        // Set the active flag now that we've completed the full
7✔
266
        // startup.
7✔
267
        atomic.StoreInt32(&b.active, 1)
7✔
268

7✔
269
        chainntnfs.Log.Debugf("btcd notifier started")
7✔
270

7✔
271
        return nil
7✔
272
}
273

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

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

304
        // connected is true if this update is a new block and false if it is a
305
        // disconnected block.
306
        connect bool
307
}
308

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

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

335
// notificationDispatcher is the primary goroutine which handles client
336
// notification registrations, as well as notification dispatches.
337
func (b *BtcdNotifier) notificationDispatcher() {
10✔
338
        defer b.wg.Done()
10✔
339

10✔
340
out:
10✔
341
        for {
1,012✔
342
                select {
1,002✔
343
                case cancelMsg := <-b.notificationCancels:
1✔
344
                        switch msg := cancelMsg.(type) {
1✔
345
                        case *epochCancel:
1✔
346
                                chainntnfs.Log.Infof("Cancelling epoch "+
1✔
347
                                        "notification, epoch_id=%v", msg.epochID)
1✔
348

1✔
349
                                // First, we'll lookup the original
1✔
350
                                // registration in order to stop the active
1✔
351
                                // queue goroutine.
1✔
352
                                reg := b.blockEpochClients[msg.epochID]
1✔
353
                                reg.epochQueue.Stop()
1✔
354

1✔
355
                                // Next, close the cancel channel for this
1✔
356
                                // specific client, and wait for the client to
1✔
357
                                // exit.
1✔
358
                                close(b.blockEpochClients[msg.epochID].cancelChan)
1✔
359
                                b.blockEpochClients[msg.epochID].wg.Wait()
1✔
360

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

34✔
380
                                //nolint:ll
34✔
381
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
68✔
382
                                        defer b.wg.Done()
34✔
383

34✔
384
                                        confDetails, _, err := b.historicalConfDetails(
34✔
385
                                                msg.ConfRequest,
34✔
386
                                                msg.StartHeight, msg.EndHeight,
34✔
387
                                        )
34✔
388
                                        if err != nil {
34✔
389
                                                chainntnfs.Log.Error(err)
×
390
                                                return
×
391
                                        }
×
392

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

408
                        case *blockEpochRegistration:
24✔
409
                                chainntnfs.Log.Infof("New block epoch subscription")
24✔
410

24✔
411
                                b.blockEpochClients[msg.epochID] = msg
24✔
412

24✔
413
                                // If the client did not provide their best
24✔
414
                                // known block, then we'll immediately dispatch
24✔
415
                                // a notification for the current tip.
24✔
416
                                if msg.bestBlock == nil {
43✔
417
                                        b.notifyBlockEpochClient(
19✔
418
                                                msg, b.bestBlock.Height,
19✔
419
                                                b.bestBlock.Hash,
19✔
420
                                                b.bestBlock.BlockHeader,
19✔
421
                                        )
19✔
422

19✔
423
                                        msg.errorChan <- nil
19✔
424
                                        continue
19✔
425
                                }
426

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

439
                                for _, block := range missedBlocks {
55✔
440
                                        b.notifyBlockEpochClient(
50✔
441
                                                msg, block.Height, block.Hash,
50✔
442
                                                block.BlockHeader,
50✔
443
                                        )
50✔
444
                                }
50✔
445

446
                                msg.errorChan <- nil
5✔
447
                        }
448

449
                case item := <-b.chainUpdates.ChanOut():
920✔
450
                        update := item.(*chainUpdate)
920✔
451
                        if update.connect {
1,796✔
452
                                blockHeader, err := b.chainConn.GetBlockHeader(
876✔
453
                                        update.blockHash,
876✔
454
                                )
876✔
455
                                if err != nil {
877✔
456
                                        chainntnfs.Log.Errorf("Unable to fetch "+
1✔
457
                                                "block header: %v", err)
1✔
458
                                        continue
1✔
459
                                }
460

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

483
                                        for _, block := range missedBlocks {
23✔
484
                                                err := b.handleBlockConnected(block)
21✔
485
                                                if err != nil {
21✔
486
                                                        chainntnfs.Log.Error(err)
×
487
                                                        continue out
×
488
                                                }
489
                                        }
490
                                }
491

492
                                newBlock := chainntnfs.BlockEpoch{
875✔
493
                                        Height:      update.blockHeight,
875✔
494
                                        Hash:        update.blockHash,
875✔
495
                                        BlockHeader: blockHeader,
875✔
496
                                }
875✔
497
                                if err := b.handleBlockConnected(newBlock); err != nil {
875✔
498
                                        chainntnfs.Log.Error(err)
×
499
                                }
×
500
                                continue
875✔
501
                        }
502

503
                        if update.blockHeight != b.bestBlock.Height {
44✔
UNCOV
504
                                chainntnfs.Log.Infof("Missed disconnected" +
×
UNCOV
505
                                        "blocks, attempting to catch up")
×
UNCOV
506
                        }
×
507

508
                        newBestBlock, err := chainntnfs.RewindChain(
44✔
509
                                b.chainConn, b.txNotifier, b.bestBlock,
44✔
510
                                update.blockHeight-1,
44✔
511
                        )
44✔
512
                        if err != nil {
44✔
UNCOV
513
                                chainntnfs.Log.Errorf("Unable to rewind chain "+
×
UNCOV
514
                                        "from height %d to height %d: %v",
×
UNCOV
515
                                        b.bestBlock.Height, update.blockHeight-1, err)
×
UNCOV
516
                        }
×
517

518
                        // Set the bestBlock here in case a chain rewind
519
                        // partially completed.
520
                        b.bestBlock = newBestBlock
44✔
521

522
                case item := <-b.txUpdates.ChanOut():
13✔
523
                        newSpend := item.(*txUpdate)
13✔
524
                        tx := newSpend.tx
13✔
525

13✔
526
                        // Init values.
13✔
527
                        isMempool := false
13✔
528
                        height := uint32(0)
13✔
529

13✔
530
                        // Unwrap values.
13✔
531
                        if newSpend.details == nil {
19✔
532
                                isMempool = true
6✔
533
                        } else {
13✔
534
                                height = uint32(newSpend.details.Height)
7✔
535
                        }
7✔
536

537
                        // Handle the transaction.
538
                        b.handleRelevantTx(tx, isMempool, height)
13✔
539

540
                case <-b.quit:
6✔
541
                        break out
6✔
542
                }
543
        }
544
}
545

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

13✔
553
        // If this is a mempool spend, we'll ask the mempool notifier to handle
13✔
554
        // it.
13✔
555
        if mempool {
19✔
556
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
6✔
557
                if err != nil {
6✔
558
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
559
                                "%v: %v", tx.Hash(), err)
×
560
                }
×
561

562
                return
6✔
563
        }
564

565
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
566
        // to handle it.
567
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
7✔
568
        if err != nil {
7✔
569
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
570
                        tx.Hash(), err)
×
571

×
572
                return
×
573
        }
×
574

575
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
576
        // the input.
577
        //
578
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
579
        // but choose to implement it here so we can easily decouple the two
580
        // notifiers in the future.
581
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
7✔
582
}
583

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

40✔
591
        // If a txid was not provided, then we should dispatch upon seeing the
40✔
592
        // script on-chain, so we'll short-circuit straight to scanning manually
40✔
593
        // as there doesn't exist a script index to query.
40✔
594
        if confRequest.TxID == chainntnfs.ZeroHash {
56✔
595
                return b.confDetailsManually(
16✔
596
                        confRequest, startHeight, endHeight,
16✔
597
                )
16✔
598
        }
16✔
599

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

24✔
610
        // We'll then check the status of the transaction lookup returned to
24✔
611
        // determine whether we should proceed with any fallback methods.
24✔
612
        switch {
24✔
613

614
        // We failed querying the index for the transaction, fall back to
615
        // scanning manually.
616
        case err != nil:
8✔
617
                chainntnfs.Log.Debugf("Unable to determine confirmation of %v "+
8✔
618
                        "through the backend's txindex (%v), scanning manually",
8✔
619
                        confRequest.TxID, err)
8✔
620

8✔
621
                return b.confDetailsManually(
8✔
622
                        confRequest, startHeight, endHeight,
8✔
623
                )
8✔
624

625
        // The transaction was found within the node's mempool.
626
        case txStatus == chainntnfs.TxFoundMempool:
14✔
627

628
        // The transaction was found within the node's txindex.
629
        case txStatus == chainntnfs.TxFoundIndex:
1✔
630

631
        // The transaction was not found within the node's mempool or txindex.
632
        case txStatus == chainntnfs.TxNotFoundIndex:
1✔
633

634
        // Unexpected txStatus returned.
635
        default:
×
636
                return nil, txStatus,
×
637
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
638
        }
639

640
        return txConf, txStatus, nil
16✔
641
}
642

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

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

663
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
37✔
664
                if err != nil {
37✔
665
                        return nil, chainntnfs.TxNotFoundManually,
×
666
                                fmt.Errorf("unable to get hash from block "+
×
667
                                        "with height %d", height)
×
668
                }
×
669

670
                // TODO: fetch the neutrino filters instead.
671
                block, err := b.GetBlock(blockHash)
37✔
672
                if err != nil {
37✔
673
                        return nil, chainntnfs.TxNotFoundManually,
×
674
                                fmt.Errorf("unable to get block with hash "+
×
675
                                        "%v: %v", blockHash, err)
×
676
                }
×
677

678
                // For every transaction in the block, check which one matches
679
                // our request. If we find one that does, we can dispatch its
680
                // confirmation details.
681
                for txIndex, tx := range block.Transactions {
96✔
682
                        if !confRequest.MatchesTx(tx) {
113✔
683
                                continue
54✔
684
                        }
685

686
                        return &chainntnfs.TxConfirmation{
5✔
687
                                Tx:          tx.Copy(),
5✔
688
                                BlockHash:   blockHash,
5✔
689
                                BlockHeight: height,
5✔
690
                                TxIndex:     uint32(txIndex),
5✔
691
                                Block:       block,
5✔
692
                        }, chainntnfs.TxFoundManually, nil
5✔
693
                }
694
        }
695

696
        // If we reach here, then we were not able to find the transaction
697
        // within a block, so we avoid returning an error.
698
        return nil, chainntnfs.TxNotFoundManually, nil
19✔
699
}
700

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

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

729
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
896✔
730
                epoch.Hash)
896✔
731

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

896✔
739
        err = b.txNotifier.NotifyHeight(uint32(epoch.Height))
896✔
740
        if err != nil {
896✔
741
                return fmt.Errorf("unable to notify height: %w", err)
×
742
        }
×
743

744
        b.notifyBlockEpochs(
896✔
745
                epoch.Height, epoch.Hash, epoch.BlockHeader,
896✔
746
        )
896✔
747

896✔
748
        return nil
896✔
749
}
750

751
// notifyBlockEpochs notifies all registered block epoch clients of the newly
752
// connected block to the main chain.
753
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
754
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
896✔
755

896✔
756
        for _, client := range b.blockEpochClients {
1,167✔
757
                b.notifyBlockEpochClient(
271✔
758
                        client, newHeight, newSha, blockHeader,
271✔
759
                )
271✔
760
        }
271✔
761
}
762

763
// notifyBlockEpochClient sends a registered block epoch client a notification
764
// about a specific block.
765
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
766
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
340✔
767

340✔
768
        epoch := &chainntnfs.BlockEpoch{
340✔
769
                Height:      height,
340✔
770
                Hash:        sha,
340✔
771
                BlockHeader: blockHeader,
340✔
772
        }
340✔
773

340✔
774
        select {
340✔
775
        case epochClient.epochQueue.ChanIn() <- epoch:
340✔
776
        case <-epochClient.cancelChan:
×
777
        case <-b.quit:
×
778
        }
779
}
780

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

26✔
792
        // Register the conf notification with the TxNotifier. A non-nil value
26✔
793
        // for `dispatch` will be returned if we are required to perform a
26✔
794
        // manual scan for the confirmation. Otherwise the notifier will begin
26✔
795
        // watching at tip for the transaction to confirm.
26✔
796
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
26✔
797
        if err != nil {
26✔
UNCOV
798
                return nil, err
×
UNCOV
799
        }
×
800

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

823
        // If the txNotifier didn't return any details to perform a historical
824
        // scan of the chain, then we can return early as there's nothing left
825
        // for us to do.
826
        if ntfn.HistoricalDispatch == nil {
48✔
827
                return ntfn.Event, nil
22✔
828
        }
22✔
829

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

844
                // TODO(wilmer): add retry logic if rescan fails?
845
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
3✔
846
                        pkScript, b.chainParams,
3✔
847
                )
3✔
848
                if err != nil {
3✔
849
                        return nil, fmt.Errorf("unable to parse address: %w",
×
850
                                err)
×
851
                }
×
852

853
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
3✔
854
                go func() {
6✔
855
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
3✔
856
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
857
                                        "the spend details of %v failed: %v",
×
858
                                        ntfn.HistoricalDispatch.SpendRequest,
×
859
                                        rescanErr)
×
860
                        }
×
861
                }()
862

863
                return ntfn.Event, nil
3✔
864
        }
865

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

UNCOV
887
                return ntfn.Event, nil
×
888
        }
889

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

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

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

UNCOV
926
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
×
UNCOV
927
                if err != nil {
×
928
                        return nil, err
×
929
                }
×
UNCOV
930
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
×
UNCOV
931
                if err != nil {
×
932
                        return nil, fmt.Errorf("unable to get header for "+
×
933
                                "block %v: %v", blockHash, err)
×
934
                }
×
935

UNCOV
936
                spentHeight := uint32(blockHeader.Height)
×
UNCOV
937
                chainntnfs.Log.Debugf("Outpoint(%v) has spent at height %v",
×
UNCOV
938
                        outpoint, spentHeight)
×
UNCOV
939

×
UNCOV
940
                // Since the tx has already been spent at spentHeight, the
×
UNCOV
941
                // heightHint specified by the caller is no longer relevant. We
×
UNCOV
942
                // now update the starting height to be the spent height to make
×
UNCOV
943
                // sure we won't miss it in the rescan.
×
UNCOV
944
                if spentHeight != ntfn.HistoricalDispatch.StartHeight {
×
UNCOV
945
                        startHash, err = b.chainConn.GetBlockHash(
×
UNCOV
946
                                int64(spentHeight),
×
UNCOV
947
                        )
×
UNCOV
948
                        if err != nil {
×
949
                                return nil, fmt.Errorf("unable to get block "+
×
950
                                        "hash for height %d: %v",
×
951
                                        blockHeader.Height, err)
×
952
                        }
×
953

UNCOV
954
                        ntfn.HistoricalDispatch.StartHeight = spentHeight
×
955
                }
956
        }
957

958
        // Now that we've determined the best starting point for our rescan,
959
        // we can go ahead and dispatch it.
960
        //
961
        // In order to ensure that we don't block the caller on what may be a
962
        // long rescan, we'll launch a new goroutine to handle the async result
963
        // of the rescan. We purposefully prevent from adding this goroutine to
964
        // the WaitGroup as we cannot wait for a quit signal due to the
965
        // asyncResult channel not being exposed.
966
        //
967
        // TODO(wilmer): add retry logic if rescan fails?
968
        asyncResult := b.chainConn.RescanAsync(
1✔
969
                startHash, nil, []*wire.OutPoint{outpoint},
1✔
970
        )
1✔
971
        go func() {
2✔
972
                if rescanErr := asyncResult.Receive(); rescanErr != nil {
1✔
973
                        chainntnfs.Log.Errorf("Rescan to determine the spend "+
×
974
                                "details of %v failed: %v", outpoint, rescanErr)
×
975
                }
×
976
        }()
977

978
        return ntfn.Event, nil
1✔
979
}
980

981
// RegisterConfirmationsNtfn registers an intent to be notified once the target
982
// txid/output script has reached numConfs confirmations on-chain. When
983
// intending to be notified of the confirmation of an output script, a nil txid
984
// must be used. The heightHint should represent the earliest height at which
985
// the txid/output script could have been included in the chain.
986
//
987
// Progress on the number of confirmations left can be read from the 'Updates'
988
// channel. Once it has reached all of its confirmations, a notification will be
989
// sent across the 'Confirmed' channel.
990
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
991
        pkScript []byte, numConfs, heightHint uint32,
992
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
48✔
993

48✔
994
        // Register the conf notification with the TxNotifier. A non-nil value
48✔
995
        // for `dispatch` will be returned if we are required to perform a
48✔
996
        // manual scan for the confirmation. Otherwise the notifier will begin
48✔
997
        // watching at tip for the transaction to confirm.
48✔
998
        ntfn, err := b.txNotifier.RegisterConf(
48✔
999
                txid, pkScript, numConfs, heightHint, opts...,
48✔
1000
        )
48✔
1001
        if err != nil {
48✔
1002
                return nil, err
×
1003
        }
×
1004

1005
        if ntfn.HistoricalDispatch == nil {
62✔
1006
                return ntfn.Event, nil
14✔
1007
        }
14✔
1008

1009
        select {
34✔
1010
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
34✔
1011
                return ntfn.Event, nil
34✔
1012
        case <-b.quit:
×
1013
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1014
        }
1015
}
1016

1017
// blockEpochRegistration represents a client's intent to receive a
1018
// notification with each newly connected block.
1019
type blockEpochRegistration struct {
1020
        epochID uint64
1021

1022
        epochChan chan *chainntnfs.BlockEpoch
1023

1024
        epochQueue *queue.ConcurrentQueue
1025

1026
        bestBlock *chainntnfs.BlockEpoch
1027

1028
        errorChan chan error
1029

1030
        cancelChan chan struct{}
1031

1032
        wg sync.WaitGroup
1033
}
1034

1035
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1036
// cancel an outstanding epoch notification that has yet to be dispatched.
1037
type epochCancel struct {
1038
        epochID uint64
1039
}
1040

1041
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1042
// caller to receive notifications, of each new block connected to the main
1043
// chain. Clients have the option of passing in their best known block, which
1044
// the notifier uses to check if they are behind on blocks and catch them up. If
1045
// they do not provide one, then a notification will be dispatched immediately
1046
// for the current tip of the chain upon a successful registration.
1047
func (b *BtcdNotifier) RegisterBlockEpochNtfn(
1048
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
24✔
1049

24✔
1050
        reg := &blockEpochRegistration{
24✔
1051
                epochQueue: queue.NewConcurrentQueue(20),
24✔
1052
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
24✔
1053
                cancelChan: make(chan struct{}),
24✔
1054
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
24✔
1055
                bestBlock:  bestBlock,
24✔
1056
                errorChan:  make(chan error, 1),
24✔
1057
        }
24✔
1058

24✔
1059
        reg.epochQueue.Start()
24✔
1060

24✔
1061
        // Before we send the request to the main goroutine, we'll launch a new
24✔
1062
        // goroutine to proxy items added to our queue to the client itself.
24✔
1063
        // This ensures that all notifications are received *in order*.
24✔
1064
        reg.wg.Add(1)
24✔
1065
        go func() {
48✔
1066
                defer reg.wg.Done()
24✔
1067

24✔
1068
                for {
342✔
1069
                        select {
318✔
1070
                        case ntfn := <-reg.epochQueue.ChanOut():
296✔
1071
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
296✔
1072
                                select {
296✔
1073
                                case reg.epochChan <- blockNtfn:
294✔
1074

UNCOV
1075
                                case <-reg.cancelChan:
×
UNCOV
1076
                                        return
×
1077

1078
                                case <-b.quit:
2✔
1079
                                        return
2✔
1080
                                }
1081

1082
                        case <-reg.cancelChan:
1✔
1083
                                return
1✔
1084

1085
                        case <-b.quit:
21✔
1086
                                return
21✔
1087
                        }
1088
                }
1089
        }()
1090

1091
        select {
24✔
1092
        case <-b.quit:
×
1093
                // As we're exiting before the registration could be sent,
×
1094
                // we'll stop the queue now ourselves.
×
1095
                reg.epochQueue.Stop()
×
1096

×
1097
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1098
                        "attempting to register for block epoch notification.")
×
1099
        case b.notificationRegistry <- reg:
24✔
1100
                return &chainntnfs.BlockEpochEvent{
24✔
1101
                        Epochs: reg.epochChan,
24✔
1102
                        Cancel: func() {
25✔
1103
                                cancel := &epochCancel{
1✔
1104
                                        epochID: reg.epochID,
1✔
1105
                                }
1✔
1106

1✔
1107
                                // Submit epoch cancellation to notification dispatcher.
1✔
1108
                                select {
1✔
1109
                                case b.notificationCancels <- cancel:
1✔
1110
                                        // Cancellation is being handled, drain
1✔
1111
                                        // the epoch channel until it is closed
1✔
1112
                                        // before yielding to caller.
1✔
1113
                                        for {
3✔
1114
                                                select {
2✔
1115
                                                case _, ok := <-reg.epochChan:
2✔
1116
                                                        if !ok {
3✔
1117
                                                                return
1✔
1118
                                                        }
1✔
1119
                                                case <-b.quit:
×
1120
                                                        return
×
1121
                                                }
1122
                                        }
UNCOV
1123
                                case <-b.quit:
×
1124
                                }
1125
                        },
1126
                }, nil
1127
        }
1128
}
1129

1130
// GetBlock is used to retrieve the block with the given hash. This function
1131
// wraps the blockCache's GetBlock function.
1132
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1133
        error) {
933✔
1134

933✔
1135
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
933✔
1136
}
933✔
1137

1138
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1139
// for a spend of an outpoint in the mempool.The event will be dispatched once
1140
// the outpoint is spent in the mempool.
1141
//
1142
// NOTE: part of the MempoolWatcher interface.
1143
func (b *BtcdNotifier) SubscribeMempoolSpent(
UNCOV
1144
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
×
UNCOV
1145

×
UNCOV
1146
        event := b.memNotifier.SubscribeInput(outpoint)
×
UNCOV
1147

×
UNCOV
1148
        ops := []*wire.OutPoint{&outpoint}
×
UNCOV
1149

×
UNCOV
1150
        return event, b.chainConn.NotifySpent(ops)
×
UNCOV
1151
}
×
1152

1153
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1154
// for a spend of an outpoint in the mempool.
1155
//
1156
// NOTE: part of the MempoolWatcher interface.
1157
func (b *BtcdNotifier) CancelMempoolSpendEvent(
UNCOV
1158
        sub *chainntnfs.MempoolSpendEvent) {
×
UNCOV
1159

×
UNCOV
1160
        b.memNotifier.UnsubscribeEvent(sub)
×
UNCOV
1161
}
×
1162

1163
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1164
// its spending tx. Returns the tx if found, otherwise fn.None.
1165
//
1166
// NOTE: part of the MempoolWatcher interface.
1167
func (b *BtcdNotifier) LookupInputMempoolSpend(
UNCOV
1168
        op wire.OutPoint) fn.Option[wire.MsgTx] {
×
UNCOV
1169

×
UNCOV
1170
        // Find the spending txid.
×
UNCOV
1171
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
×
UNCOV
1172
        if !found {
×
UNCOV
1173
                return fn.None[wire.MsgTx]()
×
UNCOV
1174
        }
×
1175

1176
        // Query the spending tx using the id.
UNCOV
1177
        tx, err := b.chainConn.GetRawTransaction(&txid)
×
UNCOV
1178
        if err != nil {
×
1179
                // TODO(yy): enable logging errors in this package.
×
1180
                return fn.None[wire.MsgTx]()
×
1181
        }
×
1182

UNCOV
1183
        return fn.Some(*tx.MsgTx().Copy())
×
1184
}
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