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

lightningnetwork / lnd / 16005100421

01 Jul 2025 04:35PM UTC coverage: 57.772% (+0.6%) from 57.216%
16005100421

Pull #10018

github

web-flow
Merge 0b73fe73c into d8a12a5e5
Pull Request #10018: Refactor link's long methods

390 of 746 new or added lines in 1 file covered. (52.28%)

41 existing lines in 11 files now uncovered.

98433 of 170383 relevant lines covered (57.77%)

1.79 hits per line

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

72.25
/chainntnfs/bitcoindnotify/bitcoind.go
1
package bitcoindnotify
2

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

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

22
const (
23
        // notifierType uniquely identifies a concrete implementation of the
24
        // ChainNotifier interface that makes use of the bitcoind ZMQ interface.
25
        notifierTypeZMQ = "bitcoind"
26

27
        // notifierTypeRPCPolling uniquely identifies a concrete implementation
28
        // of the ChainNotifier interface that makes use of the bitcoind RPC
29
        // interface.
30
        notifierTypeRPCPolling = "bitcoind-rpc-polling"
31
)
32

33
// TODO(roasbeef): generalize struct below:
34
//  * move chans to config
35
//  * extract common code
36
//  * allow outside callers to handle send conditions
37

38
// BitcoindNotifier implements the ChainNotifier interface using a bitcoind
39
// chain client. Multiple concurrent clients are supported. All notifications
40
// are achieved via non-blocking sends on client channels.
41
type BitcoindNotifier struct {
42
        epochClientCounter uint64 // To be used atomically.
43

44
        start   sync.Once
45
        active  int32 // To be used atomically.
46
        stopped int32 // To be used atomically.
47

48
        chainConn   *chain.BitcoindClient
49
        chainParams *chaincfg.Params
50

51
        notificationCancels  chan interface{}
52
        notificationRegistry chan interface{}
53

54
        txNotifier *chainntnfs.TxNotifier
55

56
        blockEpochClients map[uint64]*blockEpochRegistration
57

58
        bestBlock chainntnfs.BlockEpoch
59

60
        // blockCache is a LRU block cache.
61
        blockCache *blockcache.BlockCache
62

63
        // spendHintCache is a cache used to query and update the latest height
64
        // hints for an outpoint. Each height hint represents the earliest
65
        // height at which the outpoint could have been spent within the chain.
66
        spendHintCache chainntnfs.SpendHintCache
67

68
        // confirmHintCache is a cache used to query the latest height hints for
69
        // a transaction. Each height hint represents the earliest height at
70
        // which the transaction could have confirmed within the chain.
71
        confirmHintCache chainntnfs.ConfirmHintCache
72

73
        // memNotifier notifies clients of events related to the mempool.
74
        memNotifier *chainntnfs.MempoolNotifier
75

76
        wg   sync.WaitGroup
77
        quit chan struct{}
78
}
79

80
// Ensure BitcoindNotifier implements the ChainNotifier interface at compile
81
// time.
82
var _ chainntnfs.ChainNotifier = (*BitcoindNotifier)(nil)
83

84
// Ensure BitcoindNotifier implements the MempoolWatcher interface at compile
85
// time.
86
var _ chainntnfs.MempoolWatcher = (*BitcoindNotifier)(nil)
87

88
// New returns a new BitcoindNotifier instance. This function assumes the
89
// bitcoind node detailed in the passed configuration is already running, and
90
// willing to accept RPC requests and new zmq clients.
91
func New(chainConn *chain.BitcoindConn, chainParams *chaincfg.Params,
92
        spendHintCache chainntnfs.SpendHintCache,
93
        confirmHintCache chainntnfs.ConfirmHintCache,
94
        blockCache *blockcache.BlockCache) *BitcoindNotifier {
1✔
95

1✔
96
        notifier := &BitcoindNotifier{
1✔
97
                chainParams: chainParams,
1✔
98

1✔
99
                notificationCancels:  make(chan interface{}),
1✔
100
                notificationRegistry: make(chan interface{}),
1✔
101

1✔
102
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
1✔
103

1✔
104
                spendHintCache:   spendHintCache,
1✔
105
                confirmHintCache: confirmHintCache,
1✔
106

1✔
107
                blockCache:  blockCache,
1✔
108
                memNotifier: chainntnfs.NewMempoolNotifier(),
1✔
109

1✔
110
                quit: make(chan struct{}),
1✔
111
        }
1✔
112

1✔
113
        notifier.chainConn = chainConn.NewBitcoindClient()
1✔
114

1✔
115
        return notifier
1✔
116
}
1✔
117

118
// Start connects to the running bitcoind node over websockets, registers for
119
// block notifications, and finally launches all related helper goroutines.
120
func (b *BitcoindNotifier) Start() error {
1✔
121
        var startErr error
1✔
122
        b.start.Do(func() {
2✔
123
                startErr = b.startNotifier()
1✔
124
        })
1✔
125

126
        return startErr
1✔
127
}
128

129
// Stop shutsdown the BitcoindNotifier.
130
func (b *BitcoindNotifier) Stop() error {
1✔
131
        // Already shutting down?
1✔
132
        if atomic.AddInt32(&b.stopped, 1) != 1 {
1✔
133
                return nil
×
134
        }
×
135

136
        chainntnfs.Log.Info("bitcoind notifier shutting down...")
1✔
137
        defer chainntnfs.Log.Debug("bitcoind notifier shutdown complete")
1✔
138

1✔
139
        // Shutdown the rpc client, this gracefully disconnects from bitcoind,
1✔
140
        // and cleans up all related resources.
1✔
141
        b.chainConn.Stop()
1✔
142
        b.chainConn.WaitForShutdown()
1✔
143

1✔
144
        close(b.quit)
1✔
145
        b.wg.Wait()
1✔
146

1✔
147
        // Notify all pending clients of our shutdown by closing the related
1✔
148
        // notification channels.
1✔
149
        for _, epochClient := range b.blockEpochClients {
2✔
150
                close(epochClient.cancelChan)
1✔
151
                epochClient.wg.Wait()
1✔
152

1✔
153
                close(epochClient.epochChan)
1✔
154
        }
1✔
155

156
        // The txNotifier is only initialized in the start method therefore we
157
        // need to make sure we don't access a nil pointer here.
158
        if b.txNotifier != nil {
2✔
159
                b.txNotifier.TearDown()
1✔
160
        }
1✔
161

162
        // Stop the mempool notifier.
163
        b.memNotifier.TearDown()
1✔
164

1✔
165
        return nil
1✔
166
}
167

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

173
func (b *BitcoindNotifier) startNotifier() error {
1✔
174
        chainntnfs.Log.Infof("bitcoind notifier starting...")
1✔
175

1✔
176
        // Connect to bitcoind, and register for notifications on connected,
1✔
177
        // and disconnected blocks.
1✔
178
        if err := b.chainConn.Start(); err != nil {
1✔
179
                return err
×
180
        }
×
181
        if err := b.chainConn.NotifyBlocks(); err != nil {
1✔
182
                return err
×
183
        }
×
184

185
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
1✔
186
        if err != nil {
1✔
187
                return err
×
188
        }
×
189
        blockHeader, err := b.chainConn.GetBlockHeader(currentHash)
1✔
190
        if err != nil {
1✔
191
                return err
×
192
        }
×
193

194
        b.txNotifier = chainntnfs.NewTxNotifier(
1✔
195
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
1✔
196
                b.confirmHintCache, b.spendHintCache,
1✔
197
        )
1✔
198

1✔
199
        b.bestBlock = chainntnfs.BlockEpoch{
1✔
200
                Height:      currentHeight,
1✔
201
                Hash:        currentHash,
1✔
202
                BlockHeader: blockHeader,
1✔
203
        }
1✔
204

1✔
205
        b.wg.Add(1)
1✔
206
        go b.notificationDispatcher()
1✔
207

1✔
208
        // Set the active flag now that we've completed the full
1✔
209
        // startup.
1✔
210
        atomic.StoreInt32(&b.active, 1)
1✔
211

1✔
212
        chainntnfs.Log.Debugf("bitcoind notifier started")
1✔
213

1✔
214
        return nil
1✔
215
}
216

217
// notificationDispatcher is the primary goroutine which handles client
218
// notification registrations, as well as notification dispatches.
219
func (b *BitcoindNotifier) notificationDispatcher() {
1✔
220
        defer b.wg.Done()
1✔
221

1✔
222
out:
1✔
223
        for {
2✔
224
                select {
1✔
225
                case cancelMsg := <-b.notificationCancels:
1✔
226
                        switch msg := cancelMsg.(type) {
1✔
227
                        case *epochCancel:
1✔
228
                                chainntnfs.Log.Infof("Cancelling epoch "+
1✔
229
                                        "notification, epoch_id=%v", msg.epochID)
1✔
230

1✔
231
                                // First, we'll lookup the original
1✔
232
                                // registration in order to stop the active
1✔
233
                                // queue goroutine.
1✔
234
                                reg := b.blockEpochClients[msg.epochID]
1✔
235
                                reg.epochQueue.Stop()
1✔
236

1✔
237
                                // Next, close the cancel channel for this
1✔
238
                                // specific client, and wait for the client to
1✔
239
                                // exit.
1✔
240
                                close(b.blockEpochClients[msg.epochID].cancelChan)
1✔
241
                                b.blockEpochClients[msg.epochID].wg.Wait()
1✔
242

1✔
243
                                // Once the client has exited, we can then
1✔
244
                                // safely close the channel used to send epoch
1✔
245
                                // notifications, in order to notify any
1✔
246
                                // listeners that the intent has been
1✔
247
                                // canceled.
1✔
248
                                close(b.blockEpochClients[msg.epochID].epochChan)
1✔
249
                                delete(b.blockEpochClients, msg.epochID)
1✔
250

251
                        }
252
                case registerMsg := <-b.notificationRegistry:
1✔
253
                        switch msg := registerMsg.(type) {
1✔
254
                        case *chainntnfs.HistoricalConfDispatch:
1✔
255
                                // Look up whether the transaction is already
1✔
256
                                // included in the active chain. We'll do this
1✔
257
                                // in a goroutine to prevent blocking
1✔
258
                                // potentially long rescans.
1✔
259
                                //
1✔
260
                                // TODO(wilmer): add retry logic if rescan fails?
1✔
261
                                b.wg.Add(1)
1✔
262

1✔
263
                                //nolint:ll
1✔
264
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
2✔
265
                                        defer b.wg.Done()
1✔
266

1✔
267
                                        confDetails, _, err := b.historicalConfDetails(
1✔
268
                                                msg.ConfRequest,
1✔
269
                                                msg.StartHeight, msg.EndHeight,
1✔
270
                                        )
1✔
271
                                        if err != nil {
1✔
272
                                                chainntnfs.Log.Errorf("Rescan to "+
×
273
                                                        "determine the conf "+
×
274
                                                        "details of %v within "+
×
275
                                                        "range %d-%d failed: %v",
×
276
                                                        msg.ConfRequest,
×
277
                                                        msg.StartHeight,
×
278
                                                        msg.EndHeight, err)
×
279
                                                return
×
280
                                        }
×
281

282
                                        // If the historical dispatch finished
283
                                        // without error, we will invoke
284
                                        // UpdateConfDetails even if none were
285
                                        // found. This allows the notifier to
286
                                        // begin safely updating the height hint
287
                                        // cache at tip, since any pending
288
                                        // rescans have now completed.
289
                                        err = b.txNotifier.UpdateConfDetails(
1✔
290
                                                msg.ConfRequest, confDetails,
1✔
291
                                        )
1✔
292
                                        if err != nil {
1✔
293
                                                chainntnfs.Log.Errorf("Unable "+
×
294
                                                        "to update conf "+
×
295
                                                        "details of %v: %v",
×
296
                                                        msg.ConfRequest, err)
×
297
                                        }
×
298
                                }(msg)
299

300
                        case *chainntnfs.HistoricalSpendDispatch:
1✔
301
                                // In order to ensure we don't block the caller
1✔
302
                                // on what may be a long rescan, we'll launch a
1✔
303
                                // goroutine to do so in the background.
1✔
304
                                //
1✔
305
                                // TODO(wilmer): add retry logic if rescan fails?
1✔
306
                                b.wg.Add(1)
1✔
307

1✔
308
                                //nolint:ll
1✔
309
                                go func(msg *chainntnfs.HistoricalSpendDispatch) {
2✔
310
                                        defer b.wg.Done()
1✔
311

1✔
312
                                        spendDetails, err := b.historicalSpendDetails(
1✔
313
                                                msg.SpendRequest,
1✔
314
                                                msg.StartHeight, msg.EndHeight,
1✔
315
                                        )
1✔
316
                                        if err != nil {
1✔
317
                                                chainntnfs.Log.Errorf("Rescan to "+
×
318
                                                        "determine the spend "+
×
319
                                                        "details of %v within "+
×
320
                                                        "range %d-%d failed: %v",
×
321
                                                        msg.SpendRequest,
×
322
                                                        msg.StartHeight,
×
323
                                                        msg.EndHeight, err)
×
324
                                                return
×
325
                                        }
×
326

327
                                        chainntnfs.Log.Infof("Historical "+
1✔
328
                                                "spend dispatch finished "+
1✔
329
                                                "for request %v (start=%v "+
1✔
330
                                                "end=%v) with details: %v",
1✔
331
                                                msg.SpendRequest,
1✔
332
                                                msg.StartHeight, msg.EndHeight,
1✔
333
                                                spendDetails)
1✔
334

1✔
335
                                        // If the historical dispatch finished
1✔
336
                                        // without error, we will invoke
1✔
337
                                        // UpdateSpendDetails even if none were
1✔
338
                                        // found. This allows the notifier to
1✔
339
                                        // begin safely updating the height hint
1✔
340
                                        // cache at tip, since any pending
1✔
341
                                        // rescans have now completed.
1✔
342
                                        err = b.txNotifier.UpdateSpendDetails(
1✔
343
                                                msg.SpendRequest, spendDetails,
1✔
344
                                        )
1✔
345
                                        if err != nil {
1✔
346
                                                chainntnfs.Log.Errorf("Unable "+
×
347
                                                        "to update spend "+
×
348
                                                        "details of %v: %v",
×
349
                                                        msg.SpendRequest, err)
×
350
                                        }
×
351
                                }(msg)
352

353
                        case *blockEpochRegistration:
1✔
354
                                chainntnfs.Log.Infof("New block epoch subscription")
1✔
355

1✔
356
                                b.blockEpochClients[msg.epochID] = msg
1✔
357

1✔
358
                                // If the client did not provide their best
1✔
359
                                // known block, then we'll immediately dispatch
1✔
360
                                // a notification for the current tip.
1✔
361
                                if msg.bestBlock == nil {
2✔
362
                                        b.notifyBlockEpochClient(
1✔
363
                                                msg, b.bestBlock.Height,
1✔
364
                                                b.bestBlock.Hash,
1✔
365
                                                b.bestBlock.BlockHeader,
1✔
366
                                        )
1✔
367

1✔
368
                                        msg.errorChan <- nil
1✔
369
                                        continue
1✔
370
                                }
371

372
                                // Otherwise, we'll attempt to deliver the
373
                                // backlog of notifications from their best
374
                                // known block.
375
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
1✔
376
                                        b.chainConn, msg.bestBlock,
1✔
377
                                        b.bestBlock.Height, true,
1✔
378
                                )
1✔
379
                                if err != nil {
2✔
380
                                        msg.errorChan <- err
1✔
381
                                        continue
1✔
382
                                }
383

384
                                for _, block := range missedBlocks {
2✔
385
                                        b.notifyBlockEpochClient(
1✔
386
                                                msg, block.Height, block.Hash,
1✔
387
                                                block.BlockHeader,
1✔
388
                                        )
1✔
389
                                }
1✔
390

391
                                msg.errorChan <- nil
1✔
392
                        }
393

394
                case ntfn := <-b.chainConn.Notifications():
1✔
395
                        switch item := ntfn.(type) {
1✔
396
                        case chain.BlockConnected:
1✔
397
                                blockHeader, err :=
1✔
398
                                        b.chainConn.GetBlockHeader(&item.Hash)
1✔
399
                                if err != nil {
1✔
400
                                        chainntnfs.Log.Errorf("Unable to fetch "+
×
401
                                                "block header: %v", err)
×
402
                                        continue
×
403
                                }
404

405
                                if blockHeader.PrevBlock != *b.bestBlock.Hash {
1✔
406
                                        // Handle the case where the notifier
×
407
                                        // missed some blocks from its chain
×
408
                                        // backend.
×
409
                                        chainntnfs.Log.Infof("Missed blocks, " +
×
410
                                                "attempting to catch up")
×
411
                                        newBestBlock, missedBlocks, err :=
×
412
                                                chainntnfs.HandleMissedBlocks(
×
413
                                                        b.chainConn,
×
414
                                                        b.txNotifier,
×
415
                                                        b.bestBlock, item.Height,
×
416
                                                        true,
×
417
                                                )
×
418

×
419
                                        if err != nil {
×
420
                                                // Set the bestBlock here in case
×
421
                                                // a catch up partially completed.
×
422
                                                b.bestBlock = newBestBlock
×
423
                                                chainntnfs.Log.Error(err)
×
424
                                                continue
×
425
                                        }
426

427
                                        for _, block := range missedBlocks {
×
428
                                                err := b.handleBlockConnected(block)
×
429
                                                if err != nil {
×
430
                                                        chainntnfs.Log.Error(err)
×
431
                                                        continue out
×
432
                                                }
433
                                        }
434
                                }
435

436
                                newBlock := chainntnfs.BlockEpoch{
1✔
437
                                        Height:      item.Height,
1✔
438
                                        Hash:        &item.Hash,
1✔
439
                                        BlockHeader: blockHeader,
1✔
440
                                }
1✔
441
                                if err := b.handleBlockConnected(newBlock); err != nil {
1✔
442
                                        chainntnfs.Log.Error(err)
×
443
                                }
×
444

445
                                continue
1✔
446

447
                        case chain.BlockDisconnected:
1✔
448
                                if item.Height != b.bestBlock.Height {
1✔
449
                                        chainntnfs.Log.Infof("Missed disconnected" +
×
450
                                                "blocks, attempting to catch up")
×
451
                                }
×
452

453
                                newBestBlock, err := chainntnfs.RewindChain(
1✔
454
                                        b.chainConn, b.txNotifier,
1✔
455
                                        b.bestBlock, item.Height-1,
1✔
456
                                )
1✔
457
                                if err != nil {
1✔
458
                                        chainntnfs.Log.Errorf("Unable to rewind chain "+
×
459
                                                "from height %d to height %d: %v",
×
460
                                                b.bestBlock.Height, item.Height-1, err)
×
461
                                }
×
462

463
                                // Set the bestBlock here in case a chain
464
                                // rewind partially completed.
465
                                b.bestBlock = newBestBlock
1✔
466

467
                        case chain.RelevantTx:
1✔
468
                                tx := btcutil.NewTx(&item.TxRecord.MsgTx)
1✔
469

1✔
470
                                // Init values.
1✔
471
                                isMempool := false
1✔
472
                                height := uint32(0)
1✔
473

1✔
474
                                // Unwrap values.
1✔
475
                                if item.Block == nil {
2✔
476
                                        isMempool = true
1✔
477
                                } else {
2✔
478
                                        height = uint32(item.Block.Height)
1✔
479
                                }
1✔
480

481
                                // Handle the transaction.
482
                                b.handleRelevantTx(tx, isMempool, height)
1✔
483
                        }
484

485
                case <-b.quit:
1✔
486
                        break out
1✔
487
                }
488
        }
489
}
490

491
// handleRelevantTx handles a new transaction that has been seen either in a
492
// block or in the mempool. If in mempool, it will ask the mempool notifier to
493
// handle it. If in a block, it will ask the txNotifier to handle it, and
494
// cancel any relevant subscriptions made in the mempool.
495
func (b *BitcoindNotifier) handleRelevantTx(tx *btcutil.Tx,
496
        mempool bool, height uint32) {
1✔
497

1✔
498
        // If this is a mempool spend, we'll ask the mempool notifier to handle
1✔
499
        // it.
1✔
500
        if mempool {
2✔
501
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
1✔
502
                if err != nil {
1✔
503
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
504
                                "%v: %v", tx.Hash(), err)
×
505
                }
×
506

507
                return
1✔
508
        }
509

510
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
511
        // to handle it.
512
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
1✔
513
        if err != nil {
1✔
514
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
515
                        tx.Hash(), err)
×
516

×
517
                return
×
518
        }
×
519

520
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
521
        // the input.
522
        //
523
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
524
        // but choose to implement it here so we can easily decouple the two
525
        // notifiers in the future.
526
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
1✔
527
}
528

529
// historicalConfDetails looks up whether a confirmation request (txid/output
530
// script) has already been included in a block in the active chain and, if so,
531
// returns details about said block.
532
func (b *BitcoindNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
533
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
534
        chainntnfs.TxConfStatus, error) {
1✔
535

1✔
536
        // If a txid was not provided, then we should dispatch upon seeing the
1✔
537
        // script on-chain, so we'll short-circuit straight to scanning manually
1✔
538
        // as there doesn't exist a script index to query.
1✔
539
        if confRequest.TxID == chainntnfs.ZeroHash {
1✔
540
                return b.confDetailsManually(
×
541
                        confRequest, startHeight, endHeight,
×
542
                )
×
543
        }
×
544

545
        // Otherwise, we'll dispatch upon seeing a transaction on-chain with the
546
        // given hash.
547
        //
548
        // We'll first attempt to retrieve the transaction using the node's
549
        // txindex.
550
        txNotFoundErr := "No such mempool or blockchain transaction"
1✔
551
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
1✔
552
                b.chainConn, confRequest, txNotFoundErr,
1✔
553
        )
1✔
554

1✔
555
        // We'll then check the status of the transaction lookup returned to
1✔
556
        // determine whether we should proceed with any fallback methods.
1✔
557
        switch {
1✔
558

559
        // We failed querying the index for the transaction, fall back to
560
        // scanning manually.
561
        case err != nil:
×
562
                chainntnfs.Log.Debugf("Failed getting conf details from "+
×
563
                        "index (%v), scanning manually", err)
×
564
                return b.confDetailsManually(confRequest, startHeight, endHeight)
×
565

566
        // The transaction was found within the node's mempool.
567
        case txStatus == chainntnfs.TxFoundMempool:
1✔
568

569
        // The transaction was found within the node's txindex.
570
        case txStatus == chainntnfs.TxFoundIndex:
1✔
571

572
        // The transaction was not found within the node's mempool or txindex.
573
        case txStatus == chainntnfs.TxNotFoundIndex:
1✔
574

575
        // Unexpected txStatus returned.
576
        default:
×
577
                return nil, txStatus,
×
578
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
579
        }
580

581
        return txConf, txStatus, nil
1✔
582
}
583

584
// confDetailsManually looks up whether a transaction/output script has already
585
// been included in a block in the active chain by scanning the chain's blocks
586
// within the given range. If the transaction/output script is found, its
587
// confirmation details are returned. Otherwise, nil is returned.
588
func (b *BitcoindNotifier) confDetailsManually(confRequest chainntnfs.ConfRequest,
589
        heightHint, currentHeight uint32) (*chainntnfs.TxConfirmation,
590
        chainntnfs.TxConfStatus, error) {
×
591

×
592
        // Begin scanning blocks at every height to determine where the
×
593
        // transaction was included in.
×
594
        for height := currentHeight; height >= heightHint && height > 0; height-- {
×
595
                // Ensure we haven't been requested to shut down before
×
596
                // processing the next height.
×
597
                select {
×
598
                case <-b.quit:
×
599
                        return nil, chainntnfs.TxNotFoundManually,
×
600
                                chainntnfs.ErrChainNotifierShuttingDown
×
601
                default:
×
602
                }
603

604
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
605
                if err != nil {
×
606
                        return nil, chainntnfs.TxNotFoundManually,
×
607
                                fmt.Errorf("unable to get hash from block "+
×
608
                                        "with height %d", height)
×
609
                }
×
610

611
                block, err := b.GetBlock(blockHash)
×
612
                if err != nil {
×
613
                        return nil, chainntnfs.TxNotFoundManually,
×
614
                                fmt.Errorf("unable to get block with hash "+
×
615
                                        "%v: %v", blockHash, err)
×
616
                }
×
617

618
                // For every transaction in the block, check which one matches
619
                // our request. If we find one that does, we can dispatch its
620
                // confirmation details.
621
                for txIndex, tx := range block.Transactions {
×
622
                        if !confRequest.MatchesTx(tx) {
×
623
                                continue
×
624
                        }
625

626
                        return &chainntnfs.TxConfirmation{
×
627
                                Tx:          tx.Copy(),
×
628
                                BlockHash:   blockHash,
×
629
                                BlockHeight: height,
×
630
                                TxIndex:     uint32(txIndex),
×
631
                                Block:       block,
×
632
                        }, chainntnfs.TxFoundManually, nil
×
633
                }
634
        }
635

636
        // If we reach here, then we were not able to find the transaction
637
        // within a block, so we avoid returning an error.
638
        return nil, chainntnfs.TxNotFoundManually, nil
×
639
}
640

641
// handleBlockConnected applies a chain update for a new block. Any watched
642
// transactions included this block will processed to either send notifications
643
// now or after numConfirmations confs.
644
func (b *BitcoindNotifier) handleBlockConnected(block chainntnfs.BlockEpoch) error {
1✔
645
        // First, we'll fetch the raw block as we'll need to gather all the
1✔
646
        // transactions to determine whether any are relevant to our registered
1✔
647
        // clients.
1✔
648
        rawBlock, err := b.GetBlock(block.Hash)
1✔
649
        if err != nil {
1✔
650
                return fmt.Errorf("unable to get block: %w", err)
×
651
        }
×
652
        utilBlock := btcutil.NewBlock(rawBlock)
1✔
653

1✔
654
        // We'll then extend the txNotifier's height with the information of
1✔
655
        // this new block, which will handle all of the notification logic for
1✔
656
        // us.
1✔
657
        err = b.txNotifier.ConnectTip(utilBlock, uint32(block.Height))
1✔
658
        if err != nil {
1✔
659
                return fmt.Errorf("unable to connect tip: %w", err)
×
660
        }
×
661

662
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", block.Height,
1✔
663
                block.Hash)
1✔
664

1✔
665
        // Now that we've guaranteed the new block extends the txNotifier's
1✔
666
        // current tip, we'll proceed to dispatch notifications to all of our
1✔
667
        // registered clients whom have had notifications fulfilled. Before
1✔
668
        // doing so, we'll make sure update our in memory state in order to
1✔
669
        // satisfy any client requests based upon the new block.
1✔
670
        b.bestBlock = block
1✔
671

1✔
672
        err = b.txNotifier.NotifyHeight(uint32(block.Height))
1✔
673
        if err != nil {
1✔
674
                return fmt.Errorf("unable to notify height: %w", err)
×
675
        }
×
676

677
        b.notifyBlockEpochs(block.Height, block.Hash, block.BlockHeader)
1✔
678

1✔
679
        return nil
1✔
680
}
681

682
// notifyBlockEpochs notifies all registered block epoch clients of the newly
683
// connected block to the main chain.
684
func (b *BitcoindNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
685
        blockHeader *wire.BlockHeader) {
1✔
686

1✔
687
        for _, client := range b.blockEpochClients {
2✔
688
                b.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
1✔
689
        }
1✔
690
}
691

692
// notifyBlockEpochClient sends a registered block epoch client a notification
693
// about a specific block.
694
func (b *BitcoindNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
695
        height int32, sha *chainhash.Hash, header *wire.BlockHeader) {
1✔
696

1✔
697
        epoch := &chainntnfs.BlockEpoch{
1✔
698
                Height:      height,
1✔
699
                Hash:        sha,
1✔
700
                BlockHeader: header,
1✔
701
        }
1✔
702

1✔
703
        select {
1✔
704
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
705
        case <-epochClient.cancelChan:
×
UNCOV
706
        case <-b.quit:
×
707
        }
708
}
709

710
// RegisterSpendNtfn registers an intent to be notified once the target
711
// outpoint/output script has been spent by a transaction on-chain. When
712
// intending to be notified of the spend of an output script, a nil outpoint
713
// must be used. The heightHint should represent the earliest height in the
714
// chain of the transaction that spent the outpoint/output script.
715
//
716
// Once a spend of has been detected, the details of the spending event will be
717
// sent across the 'Spend' channel.
718
func (b *BitcoindNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
719
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
1✔
720

1✔
721
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
722
        // for `dispatch` will be returned if we are required to perform a
1✔
723
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
724
        // watching at tip for the transaction to confirm.
1✔
725
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
1✔
726
        if err != nil {
2✔
727
                return nil, err
1✔
728
        }
1✔
729

730
        // We'll then request the backend to notify us when it has detected the
731
        // outpoint/output script as spent.
732
        //
733
        // TODO(wilmer): use LoadFilter API instead.
734
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
1✔
735
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
736
                        pkScript, b.chainParams,
×
737
                )
×
738
                if err != nil {
×
739
                        return nil, fmt.Errorf("unable to parse script: %w",
×
740
                                err)
×
741
                }
×
742
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
×
743
                        return nil, err
×
744
                }
×
745
        } else {
1✔
746
                ops := []*wire.OutPoint{outpoint}
1✔
747
                if err := b.chainConn.NotifySpent(ops); err != nil {
1✔
748
                        return nil, err
×
749
                }
×
750
        }
751

752
        // If the txNotifier didn't return any details to perform a historical
753
        // scan of the chain, then we can return early as there's nothing left
754
        // for us to do.
755
        if ntfn.HistoricalDispatch == nil {
2✔
756
                return ntfn.Event, nil
1✔
757
        }
1✔
758

759
        // Otherwise, we'll need to dispatch a historical rescan to determine if
760
        // the outpoint was already spent at a previous height.
761
        //
762
        // We'll short-circuit the path when dispatching the spend of a script,
763
        // rather than an outpoint, as there aren't any additional checks we can
764
        // make for scripts.
765
        if ntfn.HistoricalDispatch.OutPoint == chainntnfs.ZeroOutPoint {
1✔
766
                select {
×
767
                case b.notificationRegistry <- ntfn.HistoricalDispatch:
×
768
                case <-b.quit:
×
769
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
770
                }
771

772
                return ntfn.Event, nil
×
773
        }
774

775
        // When dispatching spends of outpoints, there are a number of checks we
776
        // can make to start our rescan from a better height or completely avoid
777
        // it.
778
        //
779
        // We'll start by checking the backend's UTXO set to determine whether
780
        // the outpoint has been spent. If it hasn't, we can return to the
781
        // caller as well.
782
        txOut, err := b.chainConn.GetTxOut(&outpoint.Hash, outpoint.Index, true)
1✔
783
        if err != nil {
1✔
784
                return nil, err
×
785
        }
×
786
        if txOut != nil {
2✔
787
                // We'll let the txNotifier know the outpoint is still unspent
1✔
788
                // in order to begin updating its spend hint.
1✔
789
                err := b.txNotifier.UpdateSpendDetails(
1✔
790
                        ntfn.HistoricalDispatch.SpendRequest, nil,
1✔
791
                )
1✔
792
                if err != nil {
1✔
793
                        return nil, err
×
794
                }
×
795

796
                return ntfn.Event, nil
1✔
797
        }
798

799
        // Since the outpoint was spent, as it no longer exists within the UTXO
800
        // set, we'll determine when it happened by scanning the chain.
801
        //
802
        // As a minimal optimization, we'll query the backend's transaction
803
        // index (if enabled) to determine if we have a better rescan starting
804
        // height. We can do this as the GetRawTransaction call will return the
805
        // hash of the block it was included in within the chain.
806
        tx, err := b.chainConn.GetRawTransactionVerbose(&outpoint.Hash)
1✔
807
        if err != nil {
2✔
808
                // Avoid returning an error if the transaction was not found to
1✔
809
                // proceed with fallback methods.
1✔
810
                jsonErr, ok := err.(*btcjson.RPCError)
1✔
811
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
1✔
812
                        return nil, fmt.Errorf("unable to query for txid "+
×
813
                                "%v: %w", outpoint.Hash, err)
×
814
                }
×
815
        }
816

817
        // If the transaction index was enabled, we'll use the block's hash to
818
        // retrieve its height and check whether it provides a better starting
819
        // point for our rescan.
820
        if tx != nil {
2✔
821
                // If the transaction containing the outpoint hasn't confirmed
1✔
822
                // on-chain, then there's no need to perform a rescan.
1✔
823
                if tx.BlockHash == "" {
2✔
824
                        return ntfn.Event, nil
1✔
825
                }
1✔
826

827
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
828
                if err != nil {
1✔
829
                        return nil, err
×
830
                }
×
831
                blockHeight, err := b.chainConn.GetBlockHeight(blockHash)
1✔
832
                if err != nil {
1✔
833
                        return nil, err
×
834
                }
×
835

836
                spentHeight := uint32(blockHeight)
1✔
837
                chainntnfs.Log.Debugf("Outpoint(%v) has spent at height %v",
1✔
838
                        outpoint, spentHeight)
1✔
839

1✔
840
                // Since the tx has already been spent at spentHeight, the
1✔
841
                // heightHint specified by the caller is no longer relevant. We
1✔
842
                // now update the starting height to be the spent height to make
1✔
843
                // sure we won't miss it in the rescan.
1✔
844
                if spentHeight != ntfn.HistoricalDispatch.StartHeight {
2✔
845
                        ntfn.HistoricalDispatch.StartHeight = spentHeight
1✔
846
                }
1✔
847
        }
848

849
        // Now that we've determined the starting point of our rescan, we can
850
        // dispatch it and return.
851
        select {
1✔
852
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
853
        case <-b.quit:
×
854
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
855
        }
856

857
        return ntfn.Event, nil
1✔
858
}
859

860
// historicalSpendDetails attempts to manually scan the chain within the given
861
// height range for a transaction that spends the given outpoint/output script.
862
// If one is found, the spend details are assembled and returned to the caller.
863
// If the spend is not found, a nil spend detail will be returned.
864
func (b *BitcoindNotifier) historicalSpendDetails(
865
        spendRequest chainntnfs.SpendRequest, startHeight, endHeight uint32) (
866
        *chainntnfs.SpendDetail, error) {
1✔
867

1✔
868
        // Begin scanning blocks at every height to determine if the outpoint
1✔
869
        // was spent.
1✔
870
        for height := endHeight; height >= startHeight && height > 0; height-- {
2✔
871
                // Ensure we haven't been requested to shut down before
1✔
872
                // processing the next height.
1✔
873
                select {
1✔
874
                case <-b.quit:
×
875
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
876
                default:
1✔
877
                }
878

879
                // First, we'll fetch the block for the current height.
880
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
1✔
881
                if err != nil {
1✔
882
                        return nil, fmt.Errorf("unable to retrieve hash for "+
×
883
                                "block with height %d: %v", height, err)
×
884
                }
×
885
                block, err := b.GetBlock(blockHash)
1✔
886
                if err != nil {
1✔
887
                        return nil, fmt.Errorf("unable to retrieve block "+
×
888
                                "with hash %v: %v", blockHash, err)
×
889
                }
×
890

891
                // Then, we'll manually go over every input in every transaction
892
                // in it and determine whether it spends the request in
893
                // question. If we find one, we'll dispatch the spend details.
894
                for _, tx := range block.Transactions {
2✔
895
                        matches, inputIdx, err := spendRequest.MatchesTx(tx)
1✔
896
                        if err != nil {
1✔
897
                                return nil, err
×
898
                        }
×
899
                        if !matches {
2✔
900
                                continue
1✔
901
                        }
902

903
                        txCopy := tx.Copy()
1✔
904
                        txHash := txCopy.TxHash()
1✔
905
                        spendOutPoint := &txCopy.TxIn[inputIdx].PreviousOutPoint
1✔
906
                        return &chainntnfs.SpendDetail{
1✔
907
                                SpentOutPoint:     spendOutPoint,
1✔
908
                                SpenderTxHash:     &txHash,
1✔
909
                                SpendingTx:        txCopy,
1✔
910
                                SpenderInputIndex: inputIdx,
1✔
911
                                SpendingHeight:    int32(height),
1✔
912
                        }, nil
1✔
913
                }
914
        }
915

916
        return nil, nil
1✔
917
}
918

919
// RegisterConfirmationsNtfn registers an intent to be notified once the target
920
// txid/output script has reached numConfs confirmations on-chain. When
921
// intending to be notified of the confirmation of an output script, a nil txid
922
// must be used. The heightHint should represent the earliest height at which
923
// the txid/output script could have been included in the chain.
924
//
925
// Progress on the number of confirmations left can be read from the 'Updates'
926
// channel. Once it has reached all of its confirmations, a notification will be
927
// sent across the 'Confirmed' channel.
928
func (b *BitcoindNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
929
        pkScript []byte, numConfs, heightHint uint32,
930
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
1✔
931

1✔
932
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
933
        // for `dispatch` will be returned if we are required to perform a
1✔
934
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
935
        // watching at tip for the transaction to confirm.
1✔
936
        ntfn, err := b.txNotifier.RegisterConf(
1✔
937
                txid, pkScript, numConfs, heightHint, opts...,
1✔
938
        )
1✔
939
        if err != nil {
1✔
940
                return nil, err
×
941
        }
×
942

943
        if ntfn.HistoricalDispatch == nil {
2✔
944
                return ntfn.Event, nil
1✔
945
        }
1✔
946

947
        select {
1✔
948
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
949
                return ntfn.Event, nil
1✔
950
        case <-b.quit:
×
951
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
952
        }
953
}
954

955
// blockEpochRegistration represents a client's intent to receive a
956
// notification with each newly connected block.
957
type blockEpochRegistration struct {
958
        epochID uint64
959

960
        epochChan chan *chainntnfs.BlockEpoch
961

962
        epochQueue *queue.ConcurrentQueue
963

964
        bestBlock *chainntnfs.BlockEpoch
965

966
        errorChan chan error
967

968
        cancelChan chan struct{}
969

970
        wg sync.WaitGroup
971
}
972

973
// epochCancel is a message sent to the BitcoindNotifier when a client wishes
974
// to cancel an outstanding epoch notification that has yet to be dispatched.
975
type epochCancel struct {
976
        epochID uint64
977
}
978

979
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
980
// caller to receive notifications, of each new block connected to the main
981
// chain. Clients have the option of passing in their best known block, which
982
// the notifier uses to check if they are behind on blocks and catch them up. If
983
// they do not provide one, then a notification will be dispatched immediately
984
// for the current tip of the chain upon a successful registration.
985
func (b *BitcoindNotifier) RegisterBlockEpochNtfn(
986
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
1✔
987

1✔
988
        reg := &blockEpochRegistration{
1✔
989
                epochQueue: queue.NewConcurrentQueue(20),
1✔
990
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
991
                cancelChan: make(chan struct{}),
1✔
992
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
993
                bestBlock:  bestBlock,
1✔
994
                errorChan:  make(chan error, 1),
1✔
995
        }
1✔
996
        reg.epochQueue.Start()
1✔
997

1✔
998
        // Before we send the request to the main goroutine, we'll launch a new
1✔
999
        // goroutine to proxy items added to our queue to the client itself.
1✔
1000
        // This ensures that all notifications are received *in order*.
1✔
1001
        reg.wg.Add(1)
1✔
1002
        go func() {
2✔
1003
                defer reg.wg.Done()
1✔
1004

1✔
1005
                for {
2✔
1006
                        select {
1✔
1007
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
1008
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
1009
                                select {
1✔
1010
                                case reg.epochChan <- blockNtfn:
1✔
1011

1012
                                case <-reg.cancelChan:
1✔
1013
                                        return
1✔
1014

1015
                                case <-b.quit:
×
1016
                                        return
×
1017
                                }
1018

1019
                        case <-reg.cancelChan:
1✔
1020
                                return
1✔
1021

1022
                        case <-b.quit:
1✔
1023
                                return
1✔
1024
                        }
1025
                }
1026
        }()
1027

1028
        select {
1✔
1029
        case <-b.quit:
×
1030
                // As we're exiting before the registration could be sent,
×
1031
                // we'll stop the queue now ourselves.
×
1032
                reg.epochQueue.Stop()
×
1033

×
1034
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1035
                        "attempting to register for block epoch notification.")
×
1036
        case b.notificationRegistry <- reg:
1✔
1037
                return &chainntnfs.BlockEpochEvent{
1✔
1038
                        Epochs: reg.epochChan,
1✔
1039
                        Cancel: func() {
2✔
1040
                                cancel := &epochCancel{
1✔
1041
                                        epochID: reg.epochID,
1✔
1042
                                }
1✔
1043

1✔
1044
                                // Submit epoch cancellation to notification dispatcher.
1✔
1045
                                select {
1✔
1046
                                case b.notificationCancels <- cancel:
1✔
1047
                                        // Cancellation is being handled, drain the epoch channel until it is
1✔
1048
                                        // closed before yielding to caller.
1✔
1049
                                        for {
2✔
1050
                                                select {
1✔
1051
                                                case _, ok := <-reg.epochChan:
1✔
1052
                                                        if !ok {
2✔
1053
                                                                return
1✔
1054
                                                        }
1✔
1055
                                                case <-b.quit:
×
1056
                                                        return
×
1057
                                                }
1058
                                        }
1059
                                case <-b.quit:
1✔
1060
                                }
1061
                        },
1062
                }, nil
1063
        }
1064
}
1065

1066
// GetBlock is used to retrieve the block with the given hash. This function
1067
// wraps the blockCache's GetBlock function.
1068
func (b *BitcoindNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1069
        error) {
1✔
1070

1✔
1071
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1072
}
1✔
1073

1074
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1075
// for a spend of an outpoint in the mempool.The event will be dispatched once
1076
// the outpoint is spent in the mempool.
1077
//
1078
// NOTE: part of the MempoolWatcher interface.
1079
func (b *BitcoindNotifier) SubscribeMempoolSpent(
1080
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1081

1✔
1082
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1083

1✔
1084
        ops := []*wire.OutPoint{&outpoint}
1✔
1085

1✔
1086
        return event, b.chainConn.NotifySpent(ops)
1✔
1087
}
1✔
1088

1089
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1090
// for a spend of an outpoint in the mempool.
1091
//
1092
// NOTE: part of the MempoolWatcher interface.
1093
func (b *BitcoindNotifier) CancelMempoolSpendEvent(
1094
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1095

1✔
1096
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1097
}
1✔
1098

1099
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1100
// its spending tx. Returns the tx if found, otherwise fn.None.
1101
//
1102
// NOTE: part of the MempoolWatcher interface.
1103
func (b *BitcoindNotifier) LookupInputMempoolSpend(
1104
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1105

1✔
1106
        // Find the spending txid.
1✔
1107
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1108
        if !found {
2✔
1109
                return fn.None[wire.MsgTx]()
1✔
1110
        }
1✔
1111

1112
        // Query the spending tx using the id.
1113
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1114
        if err != nil {
1✔
1115
                // TODO(yy): enable logging errors in this package.
×
1116
                return fn.None[wire.MsgTx]()
×
1117
        }
×
1118

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