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

lightningnetwork / lnd / 11170835610

03 Oct 2024 10:41PM UTC coverage: 49.188% (-9.6%) from 58.738%
11170835610

push

github

web-flow
Merge pull request #9154 from ziggie1984/master

multi: bump btcd version.

3 of 6 new or added lines in 6 files covered. (50.0%)

26110 existing lines in 428 files now uncovered.

97359 of 197934 relevant lines covered (49.19%)

1.04 hits per line

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

71.81
/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"
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

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

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

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

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

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

1✔
164
        return nil
1✔
165
}
166

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

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

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

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

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

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

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

1✔
209
        return nil
1✔
210
}
211

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

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

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

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

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

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

1✔
258
                                //nolint:lll
1✔
259
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
2✔
260
                                        defer b.wg.Done()
1✔
261

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

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

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

1✔
303
                                //nolint:lll
1✔
304
                                go func(msg *chainntnfs.HistoricalSpendDispatch) {
2✔
305
                                        defer b.wg.Done()
1✔
306

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

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

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

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

1✔
351
                                b.blockEpochClients[msg.epochID] = msg
1✔
352

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

1✔
363
                                        msg.errorChan <- nil
1✔
364
                                        continue
1✔
365
                                }
366

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

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

386
                                msg.errorChan <- nil
1✔
387
                        }
388

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

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

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

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

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

440
                                continue
1✔
441

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

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

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

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

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

1✔
469
                                // Unwrap values.
1✔
470
                                if item.Block == nil {
2✔
471
                                        isMempool = true
1✔
472
                                } else {
2✔
473
                                        height = uint32(item.Block.Height)
1✔
474
                                }
1✔
475

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

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

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

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

502
                return
1✔
503
        }
504

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

×
512
                return
×
513
        }
×
514

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

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

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

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

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

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

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

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

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

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

576
        return txConf, txStatus, nil
1✔
577
}
578

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

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

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

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

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

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

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

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

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

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

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

1✔
667
        b.notifyBlockEpochs(block.Height, block.Hash, block.BlockHeader)
1✔
668
        return b.txNotifier.NotifyHeight(uint32(block.Height))
1✔
669
}
670

671
// notifyBlockEpochs notifies all registered block epoch clients of the newly
672
// connected block to the main chain.
673
func (b *BitcoindNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
674
        blockHeader *wire.BlockHeader) {
1✔
675

1✔
676
        for _, client := range b.blockEpochClients {
2✔
677
                b.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
1✔
678
        }
1✔
679
}
680

681
// notifyBlockEpochClient sends a registered block epoch client a notification
682
// about a specific block.
683
func (b *BitcoindNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
684
        height int32, sha *chainhash.Hash, header *wire.BlockHeader) {
1✔
685

1✔
686
        epoch := &chainntnfs.BlockEpoch{
1✔
687
                Height:      height,
1✔
688
                Hash:        sha,
1✔
689
                BlockHeader: header,
1✔
690
        }
1✔
691

1✔
692
        select {
1✔
693
        case epochClient.epochQueue.ChanIn() <- epoch:
1✔
694
        case <-epochClient.cancelChan:
×
695
        case <-b.quit:
×
696
        }
697
}
698

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

1✔
710
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
711
        // for `dispatch` will be returned if we are required to perform a
1✔
712
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
713
        // watching at tip for the transaction to confirm.
1✔
714
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
1✔
715
        if err != nil {
2✔
716
                return nil, err
1✔
717
        }
1✔
718

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

741
        // If the txNotifier didn't return any details to perform a historical
742
        // scan of the chain, then we can return early as there's nothing left
743
        // for us to do.
744
        if ntfn.HistoricalDispatch == nil {
2✔
745
                return ntfn.Event, nil
1✔
746
        }
1✔
747

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

UNCOV
761
                return ntfn.Event, nil
×
762
        }
763

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

785
                return ntfn.Event, nil
1✔
786
        }
787

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

806
        // If the transaction index was enabled, we'll use the block's hash to
807
        // retrieve its height and check whether it provides a better starting
808
        // point for our rescan.
809
        if tx != nil {
2✔
810
                // If the transaction containing the outpoint hasn't confirmed
1✔
811
                // on-chain, then there's no need to perform a rescan.
1✔
812
                if tx.BlockHash == "" {
2✔
813
                        return ntfn.Event, nil
1✔
814
                }
1✔
815

816
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
1✔
817
                if err != nil {
1✔
818
                        return nil, err
×
819
                }
×
820
                blockHeight, err := b.chainConn.GetBlockHeight(blockHash)
1✔
821
                if err != nil {
1✔
822
                        return nil, err
×
823
                }
×
824

825
                if uint32(blockHeight) > ntfn.HistoricalDispatch.StartHeight {
2✔
826
                        ntfn.HistoricalDispatch.StartHeight = uint32(blockHeight)
1✔
827
                }
1✔
828
        }
829

830
        // Now that we've determined the starting point of our rescan, we can
831
        // dispatch it and return.
832
        select {
1✔
833
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
834
        case <-b.quit:
×
835
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
836
        }
837

838
        return ntfn.Event, nil
1✔
839
}
840

841
// historicalSpendDetails attempts to manually scan the chain within the given
842
// height range for a transaction that spends the given outpoint/output script.
843
// If one is found, the spend details are assembled and returned to the caller.
844
// If the spend is not found, a nil spend detail will be returned.
845
func (b *BitcoindNotifier) historicalSpendDetails(
846
        spendRequest chainntnfs.SpendRequest, startHeight, endHeight uint32) (
847
        *chainntnfs.SpendDetail, error) {
1✔
848

1✔
849
        // Begin scanning blocks at every height to determine if the outpoint
1✔
850
        // was spent.
1✔
851
        for height := endHeight; height >= startHeight && height > 0; height-- {
2✔
852
                // Ensure we haven't been requested to shut down before
1✔
853
                // processing the next height.
1✔
854
                select {
1✔
855
                case <-b.quit:
×
856
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
857
                default:
1✔
858
                }
859

860
                // First, we'll fetch the block for the current height.
861
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
1✔
862
                if err != nil {
1✔
863
                        return nil, fmt.Errorf("unable to retrieve hash for "+
×
864
                                "block with height %d: %v", height, err)
×
865
                }
×
866
                block, err := b.GetBlock(blockHash)
1✔
867
                if err != nil {
1✔
868
                        return nil, fmt.Errorf("unable to retrieve block "+
×
869
                                "with hash %v: %v", blockHash, err)
×
870
                }
×
871

872
                // Then, we'll manually go over every input in every transaction
873
                // in it and determine whether it spends the request in
874
                // question. If we find one, we'll dispatch the spend details.
875
                for _, tx := range block.Transactions {
2✔
876
                        matches, inputIdx, err := spendRequest.MatchesTx(tx)
1✔
877
                        if err != nil {
1✔
878
                                return nil, err
×
879
                        }
×
880
                        if !matches {
2✔
881
                                continue
1✔
882
                        }
883

884
                        txCopy := tx.Copy()
1✔
885
                        txHash := txCopy.TxHash()
1✔
886
                        spendOutPoint := &txCopy.TxIn[inputIdx].PreviousOutPoint
1✔
887
                        return &chainntnfs.SpendDetail{
1✔
888
                                SpentOutPoint:     spendOutPoint,
1✔
889
                                SpenderTxHash:     &txHash,
1✔
890
                                SpendingTx:        txCopy,
1✔
891
                                SpenderInputIndex: inputIdx,
1✔
892
                                SpendingHeight:    int32(height),
1✔
893
                        }, nil
1✔
894
                }
895
        }
896

897
        return nil, nil
1✔
898
}
899

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

1✔
913
        // Register the conf notification with the TxNotifier. A non-nil value
1✔
914
        // for `dispatch` will be returned if we are required to perform a
1✔
915
        // manual scan for the confirmation. Otherwise the notifier will begin
1✔
916
        // watching at tip for the transaction to confirm.
1✔
917
        ntfn, err := b.txNotifier.RegisterConf(
1✔
918
                txid, pkScript, numConfs, heightHint, opts...,
1✔
919
        )
1✔
920
        if err != nil {
1✔
921
                return nil, err
×
922
        }
×
923

924
        if ntfn.HistoricalDispatch == nil {
2✔
925
                return ntfn.Event, nil
1✔
926
        }
1✔
927

928
        select {
1✔
929
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
1✔
930
                return ntfn.Event, nil
1✔
931
        case <-b.quit:
×
932
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
933
        }
934
}
935

936
// blockEpochRegistration represents a client's intent to receive a
937
// notification with each newly connected block.
938
type blockEpochRegistration struct {
939
        epochID uint64
940

941
        epochChan chan *chainntnfs.BlockEpoch
942

943
        epochQueue *queue.ConcurrentQueue
944

945
        bestBlock *chainntnfs.BlockEpoch
946

947
        errorChan chan error
948

949
        cancelChan chan struct{}
950

951
        wg sync.WaitGroup
952
}
953

954
// epochCancel is a message sent to the BitcoindNotifier when a client wishes
955
// to cancel an outstanding epoch notification that has yet to be dispatched.
956
type epochCancel struct {
957
        epochID uint64
958
}
959

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

1✔
969
        reg := &blockEpochRegistration{
1✔
970
                epochQueue: queue.NewConcurrentQueue(20),
1✔
971
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
1✔
972
                cancelChan: make(chan struct{}),
1✔
973
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
1✔
974
                bestBlock:  bestBlock,
1✔
975
                errorChan:  make(chan error, 1),
1✔
976
        }
1✔
977
        reg.epochQueue.Start()
1✔
978

1✔
979
        // Before we send the request to the main goroutine, we'll launch a new
1✔
980
        // goroutine to proxy items added to our queue to the client itself.
1✔
981
        // This ensures that all notifications are received *in order*.
1✔
982
        reg.wg.Add(1)
1✔
983
        go func() {
2✔
984
                defer reg.wg.Done()
1✔
985

1✔
986
                for {
2✔
987
                        select {
1✔
988
                        case ntfn := <-reg.epochQueue.ChanOut():
1✔
989
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
1✔
990
                                select {
1✔
991
                                case reg.epochChan <- blockNtfn:
1✔
992

993
                                case <-reg.cancelChan:
1✔
994
                                        return
1✔
995

UNCOV
996
                                case <-b.quit:
×
UNCOV
997
                                        return
×
998
                                }
999

1000
                        case <-reg.cancelChan:
1✔
1001
                                return
1✔
1002

1003
                        case <-b.quit:
1✔
1004
                                return
1✔
1005
                        }
1006
                }
1007
        }()
1008

1009
        select {
1✔
1010
        case <-b.quit:
×
1011
                // As we're exiting before the registration could be sent,
×
1012
                // we'll stop the queue now ourselves.
×
1013
                reg.epochQueue.Stop()
×
1014

×
1015
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1016
                        "attempting to register for block epoch notification.")
×
1017
        case b.notificationRegistry <- reg:
1✔
1018
                return &chainntnfs.BlockEpochEvent{
1✔
1019
                        Epochs: reg.epochChan,
1✔
1020
                        Cancel: func() {
2✔
1021
                                cancel := &epochCancel{
1✔
1022
                                        epochID: reg.epochID,
1✔
1023
                                }
1✔
1024

1✔
1025
                                // Submit epoch cancellation to notification dispatcher.
1✔
1026
                                select {
1✔
1027
                                case b.notificationCancels <- cancel:
1✔
1028
                                        // Cancellation is being handled, drain the epoch channel until it is
1✔
1029
                                        // closed before yielding to caller.
1✔
1030
                                        for {
2✔
1031
                                                select {
1✔
1032
                                                case _, ok := <-reg.epochChan:
1✔
1033
                                                        if !ok {
2✔
1034
                                                                return
1✔
1035
                                                        }
1✔
1036
                                                case <-b.quit:
1✔
1037
                                                        return
1✔
1038
                                                }
1039
                                        }
1040
                                case <-b.quit:
1✔
1041
                                }
1042
                        },
1043
                }, nil
1044
        }
1045
}
1046

1047
// GetBlock is used to retrieve the block with the given hash. This function
1048
// wraps the blockCache's GetBlock function.
1049
func (b *BitcoindNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
1050
        error) {
1✔
1051

1✔
1052
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
1✔
1053
}
1✔
1054

1055
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1056
// for a spend of an outpoint in the mempool.The event will be dispatched once
1057
// the outpoint is spent in the mempool.
1058
//
1059
// NOTE: part of the MempoolWatcher interface.
1060
func (b *BitcoindNotifier) SubscribeMempoolSpent(
1061
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
1✔
1062

1✔
1063
        event := b.memNotifier.SubscribeInput(outpoint)
1✔
1064

1✔
1065
        ops := []*wire.OutPoint{&outpoint}
1✔
1066

1✔
1067
        return event, b.chainConn.NotifySpent(ops)
1✔
1068
}
1✔
1069

1070
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1071
// for a spend of an outpoint in the mempool.
1072
//
1073
// NOTE: part of the MempoolWatcher interface.
1074
func (b *BitcoindNotifier) CancelMempoolSpendEvent(
1075
        sub *chainntnfs.MempoolSpendEvent) {
1✔
1076

1✔
1077
        b.memNotifier.UnsubscribeEvent(sub)
1✔
1078
}
1✔
1079

1080
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1081
// its spending tx. Returns the tx if found, otherwise fn.None.
1082
//
1083
// NOTE: part of the MempoolWatcher interface.
1084
func (b *BitcoindNotifier) LookupInputMempoolSpend(
1085
        op wire.OutPoint) fn.Option[wire.MsgTx] {
1✔
1086

1✔
1087
        // Find the spending txid.
1✔
1088
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
1✔
1089
        if !found {
2✔
1090
                return fn.None[wire.MsgTx]()
1✔
1091
        }
1✔
1092

1093
        // Query the spending tx using the id.
1094
        tx, err := b.chainConn.GetRawTransaction(&txid)
1✔
1095
        if err != nil {
1✔
1096
                // TODO(yy): enable logging errors in this package.
×
1097
                return fn.None[wire.MsgTx]()
×
1098
        }
×
1099

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