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

lightningnetwork / lnd / 14494133921

16 Apr 2025 01:37PM UTC coverage: 58.55% (-10.5%) from 69.084%
14494133921

Pull #9722

github

web-flow
Merge b35d38c89 into 06f1ef47f
Pull Request #9722: Change RPC call order for the btcd notifier

1 of 5 new or added lines in 1 file covered. (20.0%)

28260 existing lines in 450 files now uncovered.

97090 of 165824 relevant lines covered (58.55%)

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
        // Before we fetch the best block/blockheight we need to register the
227
        // notifications for connected blocks, otherwise we might think we are
228
        // at an earlier blockheight because during block notification we
229
        // might have already mined some new blocks. Hence we will not get
230
        // notified accordingly.
231
        //
232
        // NOTE: This is only a problem in itests where the block generation
233
        // happens very fast and there is a chance of blocks being mined
234
        // between two rpc calls.
235
        if err := b.chainConn.NotifyBlocks(); err != nil {
1✔
NEW
236
                b.txUpdates.Stop()
×
NEW
237
                b.chainUpdates.Stop()
×
NEW
238
                return err
×
NEW
239
        }
×
240

241
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
1✔
242
        if err != nil {
1✔
243
                b.txUpdates.Stop()
×
244
                b.chainUpdates.Stop()
×
245
                return err
×
246
        }
×
247

248
        bestBlock, err := b.chainConn.GetBlock(currentHash)
1✔
249
        if err != nil {
1✔
250
                b.txUpdates.Stop()
×
251
                b.chainUpdates.Stop()
×
252
                return err
×
253
        }
×
254

255
        b.txNotifier = chainntnfs.NewTxNotifier(
1✔
256
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
1✔
257
                b.confirmHintCache, b.spendHintCache,
1✔
258
        )
1✔
259

1✔
260
        b.bestBlock = chainntnfs.BlockEpoch{
1✔
261
                Height:      currentHeight,
1✔
262
                Hash:        currentHash,
1✔
263
                BlockHeader: &bestBlock.Header,
1✔
264
        }
1✔
265

1✔
266
        b.wg.Add(1)
1✔
267
        go b.notificationDispatcher()
1✔
268

1✔
269
        // Set the active flag now that we've completed the full
1✔
270
        // startup.
1✔
271
        atomic.StoreInt32(&b.active, 1)
1✔
272

1✔
273
        chainntnfs.Log.Debugf("btcd notifier started")
1✔
274

1✔
275
        return nil
1✔
276
}
277

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

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

308
        // connected is true if this update is a new block and false if it is a
309
        // disconnected block.
310
        connect bool
311
}
312

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

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

339
// notificationDispatcher is the primary goroutine which handles client
340
// notification registrations, as well as notification dispatches.
341
func (b *BtcdNotifier) notificationDispatcher() {
1✔
342
        defer b.wg.Done()
1✔
343

1✔
344
out:
1✔
345
        for {
2✔
346
                select {
1✔
347
                case cancelMsg := <-b.notificationCancels:
1✔
348
                        switch msg := cancelMsg.(type) {
1✔
349
                        case *epochCancel:
1✔
350
                                chainntnfs.Log.Infof("Cancelling epoch "+
1✔
351
                                        "notification, epoch_id=%v", msg.epochID)
1✔
352

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

1✔
359
                                // Next, close the cancel channel for this
1✔
360
                                // specific client, and wait for the client to
1✔
361
                                // exit.
1✔
362
                                close(b.blockEpochClients[msg.epochID].cancelChan)
1✔
363
                                b.blockEpochClients[msg.epochID].wg.Wait()
1✔
364

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

1✔
384
                                //nolint:ll
1✔
385
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
2✔
386
                                        defer b.wg.Done()
1✔
387

1✔
388
                                        confDetails, _, err := b.historicalConfDetails(
1✔
389
                                                msg.ConfRequest,
1✔
390
                                                msg.StartHeight, msg.EndHeight,
1✔
391
                                        )
1✔
392
                                        if err != nil {
1✔
393
                                                chainntnfs.Log.Error(err)
×
394
                                                return
×
395
                                        }
×
396

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

412
                        case *blockEpochRegistration:
1✔
413
                                chainntnfs.Log.Infof("New block epoch subscription")
1✔
414

1✔
415
                                b.blockEpochClients[msg.epochID] = msg
1✔
416

1✔
417
                                // If the client did not provide their best
1✔
418
                                // known block, then we'll immediately dispatch
1✔
419
                                // a notification for the current tip.
1✔
420
                                if msg.bestBlock == nil {
2✔
421
                                        b.notifyBlockEpochClient(
1✔
422
                                                msg, b.bestBlock.Height,
1✔
423
                                                b.bestBlock.Hash,
1✔
424
                                                b.bestBlock.BlockHeader,
1✔
425
                                        )
1✔
426

1✔
427
                                        msg.errorChan <- nil
1✔
428
                                        continue
1✔
429
                                }
430

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

443
                                for _, block := range missedBlocks {
1✔
UNCOV
444
                                        b.notifyBlockEpochClient(
×
UNCOV
445
                                                msg, block.Height, block.Hash,
×
UNCOV
446
                                                block.BlockHeader,
×
UNCOV
447
                                        )
×
UNCOV
448
                                }
×
449

450
                                msg.errorChan <- nil
1✔
451
                        }
452

453
                case item := <-b.chainUpdates.ChanOut():
1✔
454
                        update := item.(*chainUpdate)
1✔
455
                        if update.connect {
2✔
456
                                blockHeader, err := b.chainConn.GetBlockHeader(
1✔
457
                                        update.blockHash,
1✔
458
                                )
1✔
459
                                if err != nil {
1✔
UNCOV
460
                                        chainntnfs.Log.Errorf("Unable to fetch "+
×
UNCOV
461
                                                "block header: %v", err)
×
UNCOV
462
                                        continue
×
463
                                }
464

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

UNCOV
487
                                        for _, block := range missedBlocks {
×
UNCOV
488
                                                err := b.handleBlockConnected(block)
×
UNCOV
489
                                                if err != nil {
×
490
                                                        chainntnfs.Log.Error(err)
×
491
                                                        continue out
×
492
                                                }
493
                                        }
494
                                }
495

496
                                newBlock := chainntnfs.BlockEpoch{
1✔
497
                                        Height:      update.blockHeight,
1✔
498
                                        Hash:        update.blockHash,
1✔
499
                                        BlockHeader: blockHeader,
1✔
500
                                }
1✔
501
                                if err := b.handleBlockConnected(newBlock); err != nil {
1✔
502
                                        chainntnfs.Log.Error(err)
×
503
                                }
×
504
                                continue
1✔
505
                        }
506

507
                        if update.blockHeight != b.bestBlock.Height {
2✔
508
                                chainntnfs.Log.Infof("Missed disconnected" +
1✔
509
                                        "blocks, attempting to catch up")
1✔
510
                        }
1✔
511

512
                        newBestBlock, err := chainntnfs.RewindChain(
1✔
513
                                b.chainConn, b.txNotifier, b.bestBlock,
1✔
514
                                update.blockHeight-1,
1✔
515
                        )
1✔
516
                        if err != nil {
2✔
517
                                chainntnfs.Log.Errorf("Unable to rewind chain "+
1✔
518
                                        "from height %d to height %d: %v",
1✔
519
                                        b.bestBlock.Height, update.blockHeight-1, err)
1✔
520
                        }
1✔
521

522
                        // Set the bestBlock here in case a chain rewind
523
                        // partially completed.
524
                        b.bestBlock = newBestBlock
1✔
525

526
                case item := <-b.txUpdates.ChanOut():
1✔
527
                        newSpend := item.(*txUpdate)
1✔
528
                        tx := newSpend.tx
1✔
529

1✔
530
                        // Init values.
1✔
531
                        isMempool := false
1✔
532
                        height := uint32(0)
1✔
533

1✔
534
                        // Unwrap values.
1✔
535
                        if newSpend.details == nil {
2✔
536
                                isMempool = true
1✔
537
                        } else {
2✔
538
                                height = uint32(newSpend.details.Height)
1✔
539
                        }
1✔
540

541
                        // Handle the transaction.
542
                        b.handleRelevantTx(tx, isMempool, height)
1✔
543

544
                case <-b.quit:
1✔
545
                        break out
1✔
546
                }
547
        }
548
}
549

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

1✔
557
        // If this is a mempool spend, we'll ask the mempool notifier to handle
1✔
558
        // it.
1✔
559
        if mempool {
2✔
560
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
1✔
561
                if err != nil {
1✔
562
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
563
                                "%v: %v", tx.Hash(), err)
×
564
                }
×
565

566
                return
1✔
567
        }
568

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

×
576
                return
×
577
        }
×
578

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

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

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

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

1✔
614
        // We'll then check the status of the transaction lookup returned to
1✔
615
        // determine whether we should proceed with any fallback methods.
1✔
616
        switch {
1✔
617

618
        // We failed querying the index for the transaction, fall back to
619
        // scanning manually.
UNCOV
620
        case err != nil:
×
UNCOV
621
                chainntnfs.Log.Debugf("Unable to determine confirmation of %v "+
×
UNCOV
622
                        "through the backend's txindex (%v), scanning manually",
×
UNCOV
623
                        confRequest.TxID, err)
×
UNCOV
624

×
UNCOV
625
                return b.confDetailsManually(
×
UNCOV
626
                        confRequest, startHeight, endHeight,
×
UNCOV
627
                )
×
628

629
        // The transaction was found within the node's mempool.
630
        case txStatus == chainntnfs.TxFoundMempool:
1✔
631

632
        // The transaction was found within the node's txindex.
633
        case txStatus == chainntnfs.TxFoundIndex:
1✔
634

635
        // The transaction was not found within the node's mempool or txindex.
636
        case txStatus == chainntnfs.TxNotFoundIndex:
1✔
637

638
        // Unexpected txStatus returned.
639
        default:
×
640
                return nil, txStatus,
×
641
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
642
        }
643

644
        return txConf, txStatus, nil
1✔
645
}
646

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

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

UNCOV
667
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
UNCOV
668
                if err != nil {
×
669
                        return nil, chainntnfs.TxNotFoundManually,
×
670
                                fmt.Errorf("unable to get hash from block "+
×
671
                                        "with height %d", height)
×
672
                }
×
673

674
                // TODO: fetch the neutrino filters instead.
UNCOV
675
                block, err := b.GetBlock(blockHash)
×
UNCOV
676
                if err != nil {
×
677
                        return nil, chainntnfs.TxNotFoundManually,
×
678
                                fmt.Errorf("unable to get block with hash "+
×
679
                                        "%v: %v", blockHash, err)
×
680
                }
×
681

682
                // For every transaction in the block, check which one matches
683
                // our request. If we find one that does, we can dispatch its
684
                // confirmation details.
UNCOV
685
                for txIndex, tx := range block.Transactions {
×
UNCOV
686
                        if !confRequest.MatchesTx(tx) {
×
UNCOV
687
                                continue
×
688
                        }
689

UNCOV
690
                        return &chainntnfs.TxConfirmation{
×
UNCOV
691
                                Tx:          tx.Copy(),
×
UNCOV
692
                                BlockHash:   blockHash,
×
UNCOV
693
                                BlockHeight: height,
×
UNCOV
694
                                TxIndex:     uint32(txIndex),
×
UNCOV
695
                                Block:       block,
×
UNCOV
696
                        }, chainntnfs.TxFoundManually, nil
×
697
                }
698
        }
699

700
        // If we reach here, then we were not able to find the transaction
701
        // within a block, so we avoid returning an error.
UNCOV
702
        return nil, chainntnfs.TxNotFoundManually, nil
×
703
}
704

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

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

733
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
1✔
734
                epoch.Hash)
1✔
735

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

1✔
743
        err = b.txNotifier.NotifyHeight(uint32(epoch.Height))
1✔
744
        if err != nil {
1✔
745
                return fmt.Errorf("unable to notify height: %w", err)
×
746
        }
×
747

748
        b.notifyBlockEpochs(
1✔
749
                epoch.Height, epoch.Hash, epoch.BlockHeader,
1✔
750
        )
1✔
751

1✔
752
        return nil
1✔
753
}
754

755
// notifyBlockEpochs notifies all registered block epoch clients of the newly
756
// connected block to the main chain.
757
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
758
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
759

1✔
760
        for _, client := range b.blockEpochClients {
2✔
761
                b.notifyBlockEpochClient(
1✔
762
                        client, newHeight, newSha, blockHeader,
1✔
763
                )
1✔
764
        }
1✔
765
}
766

767
// notifyBlockEpochClient sends a registered block epoch client a notification
768
// about a specific block.
769
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
770
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
1✔
771

1✔
772
        epoch := &chainntnfs.BlockEpoch{
1✔
773
                Height:      height,
1✔
774
                Hash:        sha,
1✔
775
                BlockHeader: blockHeader,
1✔
776
        }
1✔
777

1✔
778
        select {
1✔
779
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
780
        case <-epochClient.cancelChan:
×
781
        case <-b.quit:
×
782
        }
783
}
784

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

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

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

827
        // If the txNotifier didn't return any details to perform a historical
828
        // scan of the chain, then we can return early as there's nothing left
829
        // for us to do.
830
        if ntfn.HistoricalDispatch == nil {
2✔
831
                return ntfn.Event, nil
1✔
832
        }
1✔
833

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

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

UNCOV
857
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
×
UNCOV
858
                go func() {
×
UNCOV
859
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
×
860
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
861
                                        "the spend details of %v failed: %v",
×
862
                                        ntfn.HistoricalDispatch.SpendRequest,
×
863
                                        rescanErr)
×
864
                        }
×
865
                }()
866

UNCOV
867
                return ntfn.Event, nil
×
868
        }
869

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

891
                return ntfn.Event, nil
1✔
892
        }
893

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

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

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

930
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
931
                if err != nil {
1✔
932
                        return nil, err
×
933
                }
×
934
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
1✔
935
                if err != nil {
1✔
936
                        return nil, fmt.Errorf("unable to get header for "+
×
937
                                "block %v: %v", blockHash, err)
×
938
                }
×
939

940
                if uint32(blockHeader.Height) > ntfn.HistoricalDispatch.StartHeight {
2✔
941
                        startHash, err = b.chainConn.GetBlockHash(
1✔
942
                                int64(blockHeader.Height),
1✔
943
                        )
1✔
944
                        if err != nil {
1✔
945
                                return nil, fmt.Errorf("unable to get block "+
×
946
                                        "hash for height %d: %v",
×
947
                                        blockHeader.Height, err)
×
948
                        }
×
949
                }
950
        }
951

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

972
        return ntfn.Event, nil
1✔
973
}
974

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

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

999
        if ntfn.HistoricalDispatch == nil {
2✔
1000
                return ntfn.Event, nil
1✔
1001
        }
1✔
1002

1003
        select {
1✔
1004
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
1005
                return ntfn.Event, nil
1✔
1006
        case <-b.quit:
×
1007
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1008
        }
1009
}
1010

1011
// blockEpochRegistration represents a client's intent to receive a
1012
// notification with each newly connected block.
1013
type blockEpochRegistration struct {
1014
        epochID uint64
1015

1016
        epochChan chan *chainntnfs.BlockEpoch
1017

1018
        epochQueue *queue.ConcurrentQueue
1019

1020
        bestBlock *chainntnfs.BlockEpoch
1021

1022
        errorChan chan error
1023

1024
        cancelChan chan struct{}
1025

1026
        wg sync.WaitGroup
1027
}
1028

1029
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1030
// cancel an outstanding epoch notification that has yet to be dispatched.
1031
type epochCancel struct {
1032
        epochID uint64
1033
}
1034

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

1✔
1044
        reg := &blockEpochRegistration{
1✔
1045
                epochQueue: queue.NewConcurrentQueue(20),
1✔
1046
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
1047
                cancelChan: make(chan struct{}),
1✔
1048
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
1049
                bestBlock:  bestBlock,
1✔
1050
                errorChan:  make(chan error, 1),
1✔
1051
        }
1✔
1052

1✔
1053
        reg.epochQueue.Start()
1✔
1054

1✔
1055
        // Before we send the request to the main goroutine, we'll launch a new
1✔
1056
        // goroutine to proxy items added to our queue to the client itself.
1✔
1057
        // This ensures that all notifications are received *in order*.
1✔
1058
        reg.wg.Add(1)
1✔
1059
        go func() {
2✔
1060
                defer reg.wg.Done()
1✔
1061

1✔
1062
                for {
2✔
1063
                        select {
1✔
1064
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
1065
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
1066
                                select {
1✔
1067
                                case reg.epochChan <- blockNtfn:
1✔
1068

1069
                                case <-reg.cancelChan:
1✔
1070
                                        return
1✔
1071

UNCOV
1072
                                case <-b.quit:
×
UNCOV
1073
                                        return
×
1074
                                }
1075

1076
                        case <-reg.cancelChan:
1✔
1077
                                return
1✔
1078

1079
                        case <-b.quit:
1✔
1080
                                return
1✔
1081
                        }
1082
                }
1083
        }()
1084

1085
        select {
1✔
1086
        case <-b.quit:
×
1087
                // As we're exiting before the registration could be sent,
×
1088
                // we'll stop the queue now ourselves.
×
1089
                reg.epochQueue.Stop()
×
1090

×
1091
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1092
                        "attempting to register for block epoch notification.")
×
1093
        case b.notificationRegistry <- reg:
1✔
1094
                return &chainntnfs.BlockEpochEvent{
1✔
1095
                        Epochs: reg.epochChan,
1✔
1096
                        Cancel: func() {
2✔
1097
                                cancel := &epochCancel{
1✔
1098
                                        epochID: reg.epochID,
1✔
1099
                                }
1✔
1100

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

1124
// GetBlock is used to retrieve the block with the given hash. This function
1125
// wraps the blockCache's GetBlock function.
1126
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1127
        error) {
1✔
1128

1✔
1129
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1130
}
1✔
1131

1132
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1133
// for a spend of an outpoint in the mempool.The event will be dispatched once
1134
// the outpoint is spent in the mempool.
1135
//
1136
// NOTE: part of the MempoolWatcher interface.
1137
func (b *BtcdNotifier) SubscribeMempoolSpent(
1138
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1139

1✔
1140
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1141

1✔
1142
        ops := []*wire.OutPoint{&outpoint}
1✔
1143

1✔
1144
        return event, b.chainConn.NotifySpent(ops)
1✔
1145
}
1✔
1146

1147
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1148
// for a spend of an outpoint in the mempool.
1149
//
1150
// NOTE: part of the MempoolWatcher interface.
1151
func (b *BtcdNotifier) CancelMempoolSpendEvent(
1152
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1153

1✔
1154
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1155
}
1✔
1156

1157
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1158
// its spending tx. Returns the tx if found, otherwise fn.None.
1159
//
1160
// NOTE: part of the MempoolWatcher interface.
1161
func (b *BtcdNotifier) LookupInputMempoolSpend(
1162
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1163

1✔
1164
        // Find the spending txid.
1✔
1165
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1166
        if !found {
2✔
1167
                return fn.None[wire.MsgTx]()
1✔
1168
        }
1✔
1169

1170
        // Query the spending tx using the id.
1171
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1172
        if err != nil {
1✔
1173
                // TODO(yy): enable logging errors in this package.
×
1174
                return fn.None[wire.MsgTx]()
×
1175
        }
×
1176

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