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

lightningnetwork / lnd / 13536249039

26 Feb 2025 03:42AM UTC coverage: 57.462% (-1.4%) from 58.835%
13536249039

Pull #8453

github

Roasbeef
peer: update chooseDeliveryScript to gen script if needed

In this commit, we update `chooseDeliveryScript` to generate a new
script if needed. This allows us to fold in a few other lines that
always followed this function into this expanded function.

The tests have been updated accordingly.
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

275 of 1318 new or added lines in 22 files covered. (20.86%)

19521 existing lines in 257 files now uncovered.

103858 of 180741 relevant lines covered (57.46%)

24750.23 hits per line

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

72.05
/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 {
12✔
95

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

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

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

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

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

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

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

12✔
115
        return notifier
12✔
116
}
12✔
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 {
6✔
121
        var startErr error
6✔
122
        b.start.Do(func() {
12✔
123
                startErr = b.startNotifier()
6✔
124
        })
6✔
125

126
        return startErr
6✔
127
}
128

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

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

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

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

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

46✔
153
                close(epochClient.epochChan)
46✔
154
        }
46✔
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 {
24✔
159
                b.txNotifier.TearDown()
12✔
160
        }
12✔
161

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

12✔
165
        return nil
12✔
166
}
167

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

173
func (b *BitcoindNotifier) startNotifier() error {
6✔
174
        // Connect to bitcoind, and register for notifications on connected,
6✔
175
        // and disconnected blocks.
6✔
176
        if err := b.chainConn.Start(); err != nil {
6✔
177
                return err
×
178
        }
×
179
        if err := b.chainConn.NotifyBlocks(); err != nil {
6✔
180
                return err
×
181
        }
×
182

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

192
        b.txNotifier = chainntnfs.NewTxNotifier(
6✔
193
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
6✔
194
                b.confirmHintCache, b.spendHintCache,
6✔
195
        )
6✔
196

6✔
197
        b.bestBlock = chainntnfs.BlockEpoch{
6✔
198
                Height:      currentHeight,
6✔
199
                Hash:        currentHash,
6✔
200
                BlockHeader: blockHeader,
6✔
201
        }
6✔
202

6✔
203
        b.wg.Add(1)
6✔
204
        go b.notificationDispatcher()
6✔
205

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

6✔
210
        return nil
6✔
211
}
212

213
// notificationDispatcher is the primary goroutine which handles client
214
// notification registrations, as well as notification dispatches.
215
func (b *BitcoindNotifier) notificationDispatcher() {
12✔
216
        defer b.wg.Done()
12✔
217

12✔
218
out:
12✔
219
        for {
853✔
220
                select {
841✔
221
                case cancelMsg := <-b.notificationCancels:
2✔
222
                        switch msg := cancelMsg.(type) {
2✔
223
                        case *epochCancel:
2✔
224
                                chainntnfs.Log.Infof("Cancelling epoch "+
2✔
225
                                        "notification, epoch_id=%v", msg.epochID)
2✔
226

2✔
227
                                // First, we'll lookup the original
2✔
228
                                // registration in order to stop the active
2✔
229
                                // queue goroutine.
2✔
230
                                reg := b.blockEpochClients[msg.epochID]
2✔
231
                                reg.epochQueue.Stop()
2✔
232

2✔
233
                                // Next, close the cancel channel for this
2✔
234
                                // specific client, and wait for the client to
2✔
235
                                // exit.
2✔
236
                                close(b.blockEpochClients[msg.epochID].cancelChan)
2✔
237
                                b.blockEpochClients[msg.epochID].wg.Wait()
2✔
238

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

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

66✔
259
                                //nolint:ll
66✔
260
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
132✔
261
                                        defer b.wg.Done()
66✔
262

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

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

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

4✔
304
                                //nolint:ll
4✔
305
                                go func(msg *chainntnfs.HistoricalSpendDispatch) {
8✔
306
                                        defer b.wg.Done()
4✔
307

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

323
                                        chainntnfs.Log.Infof("Historical "+
4✔
324
                                                "spend dispatch finished "+
4✔
325
                                                "for request %v (start=%v "+
4✔
326
                                                "end=%v) with details: %v",
4✔
327
                                                msg.SpendRequest,
4✔
328
                                                msg.StartHeight, msg.EndHeight,
4✔
329
                                                spendDetails)
4✔
330

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

349
                        case *blockEpochRegistration:
48✔
350
                                chainntnfs.Log.Infof("New block epoch subscription")
48✔
351

48✔
352
                                b.blockEpochClients[msg.epochID] = msg
48✔
353

48✔
354
                                // If the client did not provide their best
48✔
355
                                // known block, then we'll immediately dispatch
48✔
356
                                // a notification for the current tip.
48✔
357
                                if msg.bestBlock == nil {
86✔
358
                                        b.notifyBlockEpochClient(
38✔
359
                                                msg, b.bestBlock.Height,
38✔
360
                                                b.bestBlock.Hash,
38✔
361
                                                b.bestBlock.BlockHeader,
38✔
362
                                        )
38✔
363

38✔
364
                                        msg.errorChan <- nil
38✔
365
                                        continue
38✔
366
                                }
367

368
                                // Otherwise, we'll attempt to deliver the
369
                                // backlog of notifications from their best
370
                                // known block.
371
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
10✔
372
                                        b.chainConn, msg.bestBlock,
10✔
373
                                        b.bestBlock.Height, true,
10✔
374
                                )
10✔
375
                                if err != nil {
10✔
UNCOV
376
                                        msg.errorChan <- err
×
UNCOV
377
                                        continue
×
378
                                }
379

380
                                for _, block := range missedBlocks {
110✔
381
                                        b.notifyBlockEpochClient(
100✔
382
                                                msg, block.Height, block.Hash,
100✔
383
                                                block.BlockHeader,
100✔
384
                                        )
100✔
385
                                }
100✔
386

387
                                msg.errorChan <- nil
10✔
388
                        }
389

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

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

4✔
415
                                        if err != nil {
4✔
416
                                                // Set the bestBlock here in case
×
417
                                                // a catch up partially completed.
×
418
                                                b.bestBlock = newBestBlock
×
419
                                                chainntnfs.Log.Error(err)
×
420
                                                continue
×
421
                                        }
422

423
                                        for _, block := range missedBlocks {
46✔
424
                                                err := b.handleBlockConnected(block)
42✔
425
                                                if err != nil {
42✔
426
                                                        chainntnfs.Log.Error(err)
×
427
                                                        continue out
×
428
                                                }
429
                                        }
430
                                }
431

432
                                newBlock := chainntnfs.BlockEpoch{
316✔
433
                                        Height:      item.Height,
316✔
434
                                        Hash:        &item.Hash,
316✔
435
                                        BlockHeader: blockHeader,
316✔
436
                                }
316✔
437
                                if err := b.handleBlockConnected(newBlock); err != nil {
316✔
438
                                        chainntnfs.Log.Error(err)
×
439
                                }
×
440

441
                                continue
316✔
442

443
                        case chain.BlockDisconnected:
8✔
444
                                if item.Height != b.bestBlock.Height {
8✔
445
                                        chainntnfs.Log.Infof("Missed disconnected" +
×
446
                                                "blocks, attempting to catch up")
×
447
                                }
×
448

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

459
                                // Set the bestBlock here in case a chain
460
                                // rewind partially completed.
461
                                b.bestBlock = newBestBlock
8✔
462

463
                        case chain.RelevantTx:
61✔
464
                                tx := btcutil.NewTx(&item.TxRecord.MsgTx)
61✔
465

61✔
466
                                // Init values.
61✔
467
                                isMempool := false
61✔
468
                                height := uint32(0)
61✔
469

61✔
470
                                // Unwrap values.
61✔
471
                                if item.Block == nil {
96✔
472
                                        isMempool = true
35✔
473
                                } else {
61✔
474
                                        height = uint32(item.Block.Height)
26✔
475
                                }
26✔
476

477
                                // Handle the transaction.
478
                                b.handleRelevantTx(tx, isMempool, height)
61✔
479
                        }
480

481
                case <-b.quit:
12✔
482
                        break out
12✔
483
                }
484
        }
485
}
486

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

61✔
494
        // If this is a mempool spend, we'll ask the mempool notifier to handle
61✔
495
        // it.
61✔
496
        if mempool {
96✔
497
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
35✔
498
                if err != nil {
35✔
499
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
500
                                "%v: %v", tx.Hash(), err)
×
501
                }
×
502

503
                return
35✔
504
        }
505

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

×
513
                return
×
514
        }
×
515

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

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

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

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

45✔
551
        // We'll then check the status of the transaction lookup returned to
45✔
552
        // determine whether we should proceed with any fallback methods.
45✔
553
        switch {
45✔
554

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

562
        // The transaction was found within the node's mempool.
563
        case txStatus == chainntnfs.TxFoundMempool:
14✔
564

565
        // The transaction was found within the node's txindex.
566
        case txStatus == chainntnfs.TxFoundIndex:
9✔
567

568
        // The transaction was not found within the node's mempool or txindex.
569
        case txStatus == chainntnfs.TxNotFoundIndex:
14✔
570

571
        // Unexpected txStatus returned.
572
        default:
×
573
                return nil, txStatus,
×
574
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
575
        }
576

577
        return txConf, txStatus, nil
37✔
578
}
579

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

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

600
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
63✔
601
                if err != nil {
63✔
602
                        return nil, chainntnfs.TxNotFoundManually,
×
603
                                fmt.Errorf("unable to get hash from block "+
×
604
                                        "with height %d", height)
×
605
                }
×
606

607
                block, err := b.GetBlock(blockHash)
63✔
608
                if err != nil {
63✔
609
                        return nil, chainntnfs.TxNotFoundManually,
×
610
                                fmt.Errorf("unable to get block with hash "+
×
611
                                        "%v: %v", blockHash, err)
×
612
                }
×
613

614
                // For every transaction in the block, check which one matches
615
                // our request. If we find one that does, we can dispatch its
616
                // confirmation details.
617
                for txIndex, tx := range block.Transactions {
162✔
618
                        if !confRequest.MatchesTx(tx) {
192✔
619
                                continue
93✔
620
                        }
621

622
                        return &chainntnfs.TxConfirmation{
6✔
623
                                Tx:          tx.Copy(),
6✔
624
                                BlockHash:   blockHash,
6✔
625
                                BlockHeight: height,
6✔
626
                                TxIndex:     uint32(txIndex),
6✔
627
                                Block:       block,
6✔
628
                        }, chainntnfs.TxFoundManually, nil
6✔
629
                }
630
        }
631

632
        // If we reach here, then we were not able to find the transaction
633
        // within a block, so we avoid returning an error.
634
        return nil, chainntnfs.TxNotFoundManually, nil
33✔
635
}
636

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

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

658
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", block.Height,
358✔
659
                block.Hash)
358✔
660

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

358✔
668
        err = b.txNotifier.NotifyHeight(uint32(block.Height))
358✔
669
        if err != nil {
358✔
670
                return fmt.Errorf("unable to notify height: %w", err)
×
671
        }
×
672

673
        b.notifyBlockEpochs(block.Height, block.Hash, block.BlockHeader)
358✔
674

358✔
675
        return nil
358✔
676
}
677

678
// notifyBlockEpochs notifies all registered block epoch clients of the newly
679
// connected block to the main chain.
680
func (b *BitcoindNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
681
        blockHeader *wire.BlockHeader) {
358✔
682

358✔
683
        for _, client := range b.blockEpochClients {
900✔
684
                b.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
542✔
685
        }
542✔
686
}
687

688
// notifyBlockEpochClient sends a registered block epoch client a notification
689
// about a specific block.
690
func (b *BitcoindNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
691
        height int32, sha *chainhash.Hash, header *wire.BlockHeader) {
680✔
692

680✔
693
        epoch := &chainntnfs.BlockEpoch{
680✔
694
                Height:      height,
680✔
695
                Hash:        sha,
680✔
696
                BlockHeader: header,
680✔
697
        }
680✔
698

680✔
699
        select {
680✔
700
        case epochClient.epochQueue.ChanIn() <- epoch:
680✔
701
        case <-epochClient.cancelChan:
×
702
        case <-b.quit:
×
703
        }
704
}
705

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

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

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

748
        // If the txNotifier didn't return any details to perform a historical
749
        // scan of the chain, then we can return early as there's nothing left
750
        // for us to do.
751
        if ntfn.HistoricalDispatch == nil {
100✔
752
                return ntfn.Event, nil
48✔
753
        }
48✔
754

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

768
                return ntfn.Event, nil
2✔
769
        }
770

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

UNCOV
792
                return ntfn.Event, nil
×
793
        }
794

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

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

823
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
2✔
824
                if err != nil {
2✔
825
                        return nil, err
×
826
                }
×
827
                blockHeight, err := b.chainConn.GetBlockHeight(blockHash)
2✔
828
                if err != nil {
2✔
829
                        return nil, err
×
830
                }
×
831

832
                if uint32(blockHeight) > ntfn.HistoricalDispatch.StartHeight {
2✔
UNCOV
833
                        ntfn.HistoricalDispatch.StartHeight = uint32(blockHeight)
×
UNCOV
834
                }
×
835
        }
836

837
        // Now that we've determined the starting point of our rescan, we can
838
        // dispatch it and return.
839
        select {
2✔
840
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
2✔
841
        case <-b.quit:
×
842
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
843
        }
844

845
        return ntfn.Event, nil
2✔
846
}
847

848
// historicalSpendDetails attempts to manually scan the chain within the given
849
// height range for a transaction that spends the given outpoint/output script.
850
// If one is found, the spend details are assembled and returned to the caller.
851
// If the spend is not found, a nil spend detail will be returned.
852
func (b *BitcoindNotifier) historicalSpendDetails(
853
        spendRequest chainntnfs.SpendRequest, startHeight, endHeight uint32) (
854
        *chainntnfs.SpendDetail, error) {
4✔
855

4✔
856
        // Begin scanning blocks at every height to determine if the outpoint
4✔
857
        // was spent.
4✔
858
        for height := endHeight; height >= startHeight && height > 0; height-- {
8✔
859
                // Ensure we haven't been requested to shut down before
4✔
860
                // processing the next height.
4✔
861
                select {
4✔
862
                case <-b.quit:
×
863
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
864
                default:
4✔
865
                }
866

867
                // First, we'll fetch the block for the current height.
868
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
4✔
869
                if err != nil {
4✔
870
                        return nil, fmt.Errorf("unable to retrieve hash for "+
×
871
                                "block with height %d: %v", height, err)
×
872
                }
×
873
                block, err := b.GetBlock(blockHash)
4✔
874
                if err != nil {
4✔
875
                        return nil, fmt.Errorf("unable to retrieve block "+
×
876
                                "with hash %v: %v", blockHash, err)
×
877
                }
×
878

879
                // Then, we'll manually go over every input in every transaction
880
                // in it and determine whether it spends the request in
881
                // question. If we find one, we'll dispatch the spend details.
882
                for _, tx := range block.Transactions {
12✔
883
                        matches, inputIdx, err := spendRequest.MatchesTx(tx)
8✔
884
                        if err != nil {
8✔
885
                                return nil, err
×
886
                        }
×
887
                        if !matches {
16✔
888
                                continue
8✔
889
                        }
890

UNCOV
891
                        txCopy := tx.Copy()
×
UNCOV
892
                        txHash := txCopy.TxHash()
×
UNCOV
893
                        spendOutPoint := &txCopy.TxIn[inputIdx].PreviousOutPoint
×
UNCOV
894
                        return &chainntnfs.SpendDetail{
×
UNCOV
895
                                SpentOutPoint:     spendOutPoint,
×
UNCOV
896
                                SpenderTxHash:     &txHash,
×
UNCOV
897
                                SpendingTx:        txCopy,
×
UNCOV
898
                                SpenderInputIndex: inputIdx,
×
UNCOV
899
                                SpendingHeight:    int32(height),
×
UNCOV
900
                        }, nil
×
901
                }
902
        }
903

904
        return nil, nil
4✔
905
}
906

907
// RegisterConfirmationsNtfn registers an intent to be notified once the target
908
// txid/output script has reached numConfs confirmations on-chain. When
909
// intending to be notified of the confirmation of an output script, a nil txid
910
// must be used. The heightHint should represent the earliest height at which
911
// the txid/output script could have been included in the chain.
912
//
913
// Progress on the number of confirmations left can be read from the 'Updates'
914
// channel. Once it has reached all of its confirmations, a notification will be
915
// sent across the 'Confirmed' channel.
916
func (b *BitcoindNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
917
        pkScript []byte, numConfs, heightHint uint32,
918
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
96✔
919

96✔
920
        // Register the conf notification with the TxNotifier. A non-nil value
96✔
921
        // for `dispatch` will be returned if we are required to perform a
96✔
922
        // manual scan for the confirmation. Otherwise the notifier will begin
96✔
923
        // watching at tip for the transaction to confirm.
96✔
924
        ntfn, err := b.txNotifier.RegisterConf(
96✔
925
                txid, pkScript, numConfs, heightHint, opts...,
96✔
926
        )
96✔
927
        if err != nil {
96✔
928
                return nil, err
×
929
        }
×
930

931
        if ntfn.HistoricalDispatch == nil {
126✔
932
                return ntfn.Event, nil
30✔
933
        }
30✔
934

935
        select {
66✔
936
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
66✔
937
                return ntfn.Event, nil
66✔
938
        case <-b.quit:
×
939
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
940
        }
941
}
942

943
// blockEpochRegistration represents a client's intent to receive a
944
// notification with each newly connected block.
945
type blockEpochRegistration struct {
946
        epochID uint64
947

948
        epochChan chan *chainntnfs.BlockEpoch
949

950
        epochQueue *queue.ConcurrentQueue
951

952
        bestBlock *chainntnfs.BlockEpoch
953

954
        errorChan chan error
955

956
        cancelChan chan struct{}
957

958
        wg sync.WaitGroup
959
}
960

961
// epochCancel is a message sent to the BitcoindNotifier when a client wishes
962
// to cancel an outstanding epoch notification that has yet to be dispatched.
963
type epochCancel struct {
964
        epochID uint64
965
}
966

967
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
968
// caller to receive notifications, of each new block connected to the main
969
// chain. Clients have the option of passing in their best known block, which
970
// the notifier uses to check if they are behind on blocks and catch them up. If
971
// they do not provide one, then a notification will be dispatched immediately
972
// for the current tip of the chain upon a successful registration.
973
func (b *BitcoindNotifier) RegisterBlockEpochNtfn(
974
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
48✔
975

48✔
976
        reg := &blockEpochRegistration{
48✔
977
                epochQueue: queue.NewConcurrentQueue(20),
48✔
978
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
48✔
979
                cancelChan: make(chan struct{}),
48✔
980
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
48✔
981
                bestBlock:  bestBlock,
48✔
982
                errorChan:  make(chan error, 1),
48✔
983
        }
48✔
984
        reg.epochQueue.Start()
48✔
985

48✔
986
        // Before we send the request to the main goroutine, we'll launch a new
48✔
987
        // goroutine to proxy items added to our queue to the client itself.
48✔
988
        // This ensures that all notifications are received *in order*.
48✔
989
        reg.wg.Add(1)
48✔
990
        go func() {
96✔
991
                defer reg.wg.Done()
48✔
992

48✔
993
                for {
684✔
994
                        select {
636✔
995
                        case ntfn := <-reg.epochQueue.ChanOut():
592✔
996
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
592✔
997
                                select {
592✔
998
                                case reg.epochChan <- blockNtfn:
588✔
999

UNCOV
1000
                                case <-reg.cancelChan:
×
UNCOV
1001
                                        return
×
1002

1003
                                case <-b.quit:
4✔
1004
                                        return
4✔
1005
                                }
1006

1007
                        case <-reg.cancelChan:
2✔
1008
                                return
2✔
1009

1010
                        case <-b.quit:
42✔
1011
                                return
42✔
1012
                        }
1013
                }
1014
        }()
1015

1016
        select {
48✔
1017
        case <-b.quit:
×
1018
                // As we're exiting before the registration could be sent,
×
1019
                // we'll stop the queue now ourselves.
×
1020
                reg.epochQueue.Stop()
×
1021

×
1022
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1023
                        "attempting to register for block epoch notification.")
×
1024
        case b.notificationRegistry <- reg:
48✔
1025
                return &chainntnfs.BlockEpochEvent{
48✔
1026
                        Epochs: reg.epochChan,
48✔
1027
                        Cancel: func() {
50✔
1028
                                cancel := &epochCancel{
2✔
1029
                                        epochID: reg.epochID,
2✔
1030
                                }
2✔
1031

2✔
1032
                                // Submit epoch cancellation to notification dispatcher.
2✔
1033
                                select {
2✔
1034
                                case b.notificationCancels <- cancel:
2✔
1035
                                        // Cancellation is being handled, drain the epoch channel until it is
2✔
1036
                                        // closed before yielding to caller.
2✔
1037
                                        for {
6✔
1038
                                                select {
4✔
1039
                                                case _, ok := <-reg.epochChan:
4✔
1040
                                                        if !ok {
6✔
1041
                                                                return
2✔
1042
                                                        }
2✔
1043
                                                case <-b.quit:
×
1044
                                                        return
×
1045
                                                }
1046
                                        }
UNCOV
1047
                                case <-b.quit:
×
1048
                                }
1049
                        },
1050
                }, nil
1051
        }
1052
}
1053

1054
// GetBlock is used to retrieve the block with the given hash. This function
1055
// wraps the blockCache's GetBlock function.
1056
func (b *BitcoindNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1057
        error) {
425✔
1058

425✔
1059
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
425✔
1060
}
425✔
1061

1062
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1063
// for a spend of an outpoint in the mempool.The event will be dispatched once
1064
// the outpoint is spent in the mempool.
1065
//
1066
// NOTE: part of the MempoolWatcher interface.
1067
func (b *BitcoindNotifier) SubscribeMempoolSpent(
UNCOV
1068
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
×
UNCOV
1069

×
UNCOV
1070
        event := b.memNotifier.SubscribeInput(outpoint)
×
UNCOV
1071

×
UNCOV
1072
        ops := []*wire.OutPoint{&outpoint}
×
UNCOV
1073

×
UNCOV
1074
        return event, b.chainConn.NotifySpent(ops)
×
UNCOV
1075
}
×
1076

1077
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1078
// for a spend of an outpoint in the mempool.
1079
//
1080
// NOTE: part of the MempoolWatcher interface.
1081
func (b *BitcoindNotifier) CancelMempoolSpendEvent(
UNCOV
1082
        sub *chainntnfs.MempoolSpendEvent) {
×
UNCOV
1083

×
UNCOV
1084
        b.memNotifier.UnsubscribeEvent(sub)
×
UNCOV
1085
}
×
1086

1087
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1088
// its spending tx. Returns the tx if found, otherwise fn.None.
1089
//
1090
// NOTE: part of the MempoolWatcher interface.
1091
func (b *BitcoindNotifier) LookupInputMempoolSpend(
UNCOV
1092
        op wire.OutPoint) fn.Option[wire.MsgTx] {
×
UNCOV
1093

×
UNCOV
1094
        // Find the spending txid.
×
UNCOV
1095
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
×
UNCOV
1096
        if !found {
×
UNCOV
1097
                return fn.None[wire.MsgTx]()
×
UNCOV
1098
        }
×
1099

1100
        // Query the spending tx using the id.
UNCOV
1101
        tx, err := b.chainConn.GetRawTransaction(&txid)
×
UNCOV
1102
        if err != nil {
×
1103
                // TODO(yy): enable logging errors in this package.
×
1104
                return fn.None[wire.MsgTx]()
×
1105
        }
×
1106

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