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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

72.1
/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 {
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

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

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

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

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

12✔
164
        return nil
12✔
165
}
166

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

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

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

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

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

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

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

6✔
209
        return nil
6✔
210
}
211

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

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

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

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

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

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

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

64✔
262
                                        confDetails, _, err := b.historicalConfDetails(
64✔
263
                                                msg.ConfRequest,
64✔
264
                                                msg.StartHeight, msg.EndHeight,
64✔
265
                                        )
64✔
266
                                        if err != nil {
64✔
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(
64✔
285
                                                msg.ConfRequest, confDetails,
64✔
286
                                        )
64✔
287
                                        if err != nil {
64✔
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:
4✔
296
                                // In order to ensure we don't block the caller
4✔
297
                                // on what may be a long rescan, we'll launch a
4✔
298
                                // goroutine to do so in the background.
4✔
299
                                //
4✔
300
                                // TODO(wilmer): add retry logic if rescan fails?
4✔
301
                                b.wg.Add(1)
4✔
302

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

4✔
307
                                        spendDetails, err := b.historicalSpendDetails(
4✔
308
                                                msg.SpendRequest,
4✔
309
                                                msg.StartHeight, msg.EndHeight,
4✔
310
                                        )
4✔
311
                                        if err != nil {
4✔
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 "+
4✔
323
                                                "spend dispatch finished "+
4✔
324
                                                "for request %v (start=%v "+
4✔
325
                                                "end=%v) with details: %v",
4✔
326
                                                msg.SpendRequest,
4✔
327
                                                msg.StartHeight, msg.EndHeight,
4✔
328
                                                spendDetails)
4✔
329

4✔
330
                                        // If the historical dispatch finished
4✔
331
                                        // without error, we will invoke
4✔
332
                                        // UpdateSpendDetails even if none were
4✔
333
                                        // found. This allows the notifier to
4✔
334
                                        // begin safely updating the height hint
4✔
335
                                        // cache at tip, since any pending
4✔
336
                                        // rescans have now completed.
4✔
337
                                        err = b.txNotifier.UpdateSpendDetails(
4✔
338
                                                msg.SpendRequest, spendDetails,
4✔
339
                                        )
4✔
340
                                        if err != nil {
4✔
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:
48✔
349
                                chainntnfs.Log.Infof("New block epoch subscription")
48✔
350

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

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

38✔
363
                                        msg.errorChan <- nil
38✔
364
                                        continue
38✔
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(
10✔
371
                                        b.chainConn, msg.bestBlock,
10✔
372
                                        b.bestBlock.Height, true,
10✔
373
                                )
10✔
374
                                if err != nil {
10✔
375
                                        msg.errorChan <- err
×
376
                                        continue
×
377
                                }
378

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

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

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

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

4✔
414
                                        if err != nil {
4✔
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

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

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

440
                                continue
316✔
441

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

448
                                newBestBlock, err := chainntnfs.RewindChain(
8✔
449
                                        b.chainConn, b.txNotifier,
8✔
450
                                        b.bestBlock, item.Height-1,
8✔
451
                                )
8✔
452
                                if err != nil {
8✔
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
8✔
461

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

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

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

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

480
                case <-b.quit:
12✔
481
                        break out
12✔
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) {
61✔
492

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

502
                return
35✔
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)
26✔
508
        if err != nil {
26✔
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)
26✔
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) {
74✔
530

74✔
531
        // If a txid was not provided, then we should dispatch upon seeing the
74✔
532
        // script on-chain, so we'll short-circuit straight to scanning manually
74✔
533
        // as there doesn't exist a script index to query.
74✔
534
        if confRequest.TxID == chainntnfs.ZeroHash {
104✔
535
                return b.confDetailsManually(
30✔
536
                        confRequest, startHeight, endHeight,
30✔
537
                )
30✔
538
        }
30✔
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"
44✔
546
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
44✔
547
                b.chainConn, confRequest, txNotFoundErr,
44✔
548
        )
44✔
549

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

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

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

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

567
        // The transaction was not found within the node's mempool or txindex.
568
        case txStatus == chainntnfs.TxNotFoundIndex:
14✔
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
36✔
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,
585
        chainntnfs.TxConfStatus, error) {
38✔
586

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

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

606
                block, err := b.GetBlock(blockHash)
62✔
607
                if err != nil {
62✔
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.
616
                for txIndex, tx := range block.Transactions {
158✔
617
                        if !confRequest.MatchesTx(tx) {
186✔
618
                                continue
90✔
619
                        }
620

621
                        return &chainntnfs.TxConfirmation{
6✔
622
                                Tx:          tx.Copy(),
6✔
623
                                BlockHash:   blockHash,
6✔
624
                                BlockHeight: height,
6✔
625
                                TxIndex:     uint32(txIndex),
6✔
626
                                Block:       block,
6✔
627
                        }, chainntnfs.TxFoundManually, nil
6✔
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.
633
        return nil, chainntnfs.TxNotFoundManually, nil
32✔
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 {
358✔
640
        // First, we'll fetch the raw block as we'll need to gather all the
358✔
641
        // transactions to determine whether any are relevant to our registered
358✔
642
        // clients.
358✔
643
        rawBlock, err := b.GetBlock(block.Hash)
358✔
644
        if err != nil {
358✔
645
                return fmt.Errorf("unable to get block: %w", err)
×
646
        }
×
647
        utilBlock := btcutil.NewBlock(rawBlock)
358✔
648

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

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

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

358✔
667
        b.notifyBlockEpochs(block.Height, block.Hash, block.BlockHeader)
358✔
668
        return b.txNotifier.NotifyHeight(uint32(block.Height))
358✔
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) {
358✔
675

358✔
676
        for _, client := range b.blockEpochClients {
900✔
677
                b.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
542✔
678
        }
542✔
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) {
680✔
685

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

680✔
692
        select {
680✔
693
        case epochClient.epochQueue.ChanIn() <- epoch:
680✔
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) {
52✔
709

52✔
710
        // Register the conf notification with the TxNotifier. A non-nil value
52✔
711
        // for `dispatch` will be returned if we are required to perform a
52✔
712
        // manual scan for the confirmation. Otherwise the notifier will begin
52✔
713
        // watching at tip for the transaction to confirm.
52✔
714
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
52✔
715
        if err != nil {
52✔
UNCOV
716
                return nil, err
×
UNCOV
717
        }
×
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 {
78✔
724
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
26✔
725
                        pkScript, b.chainParams,
26✔
726
                )
26✔
727
                if err != nil {
26✔
728
                        return nil, fmt.Errorf("unable to parse script: %w",
×
729
                                err)
×
730
                }
×
731
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
26✔
732
                        return nil, err
×
733
                }
×
734
        } else {
26✔
735
                ops := []*wire.OutPoint{outpoint}
26✔
736
                if err := b.chainConn.NotifySpent(ops); err != nil {
26✔
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 {
100✔
745
                return ntfn.Event, nil
48✔
746
        }
48✔
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 {
6✔
755
                select {
2✔
756
                case b.notificationRegistry <- ntfn.HistoricalDispatch:
2✔
757
                case <-b.quit:
×
758
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
759
                }
760

761
                return ntfn.Event, nil
2✔
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)
2✔
772
        if err != nil {
2✔
773
                return nil, err
×
774
        }
×
775
        if txOut != nil {
2✔
UNCOV
776
                // We'll let the txNotifier know the outpoint is still unspent
×
UNCOV
777
                // in order to begin updating its spend hint.
×
UNCOV
778
                err := b.txNotifier.UpdateSpendDetails(
×
UNCOV
779
                        ntfn.HistoricalDispatch.SpendRequest, nil,
×
UNCOV
780
                )
×
UNCOV
781
                if err != nil {
×
782
                        return nil, err
×
783
                }
×
784

UNCOV
785
                return ntfn.Event, nil
×
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)
2✔
796
        if err != nil {
2✔
UNCOV
797
                // Avoid returning an error if the transaction was not found to
×
UNCOV
798
                // proceed with fallback methods.
×
UNCOV
799
                jsonErr, ok := err.(*btcjson.RPCError)
×
UNCOV
800
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
×
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 {
4✔
810
                // If the transaction containing the outpoint hasn't confirmed
2✔
811
                // on-chain, then there's no need to perform a rescan.
2✔
812
                if tx.BlockHash == "" {
2✔
UNCOV
813
                        return ntfn.Event, nil
×
UNCOV
814
                }
×
815

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

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

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

838
        return ntfn.Event, nil
2✔
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) {
4✔
848

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

860
                // First, we'll fetch the block for the current height.
861
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
4✔
862
                if err != nil {
4✔
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)
4✔
867
                if err != nil {
4✔
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 {
12✔
876
                        matches, inputIdx, err := spendRequest.MatchesTx(tx)
8✔
877
                        if err != nil {
8✔
878
                                return nil, err
×
879
                        }
×
880
                        if !matches {
16✔
881
                                continue
8✔
882
                        }
883

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

897
        return nil, nil
4✔
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) {
96✔
912

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

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

928
        select {
64✔
929
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
64✔
930
                return ntfn.Event, nil
64✔
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) {
48✔
968

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

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

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

UNCOV
993
                                case <-reg.cancelChan:
×
UNCOV
994
                                        return
×
995

996
                                case <-b.quit:
4✔
997
                                        return
4✔
998
                                }
999

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

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

1009
        select {
48✔
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:
48✔
1018
                return &chainntnfs.BlockEpochEvent{
48✔
1019
                        Epochs: reg.epochChan,
48✔
1020
                        Cancel: func() {
50✔
1021
                                cancel := &epochCancel{
2✔
1022
                                        epochID: reg.epochID,
2✔
1023
                                }
2✔
1024

2✔
1025
                                // Submit epoch cancellation to notification dispatcher.
2✔
1026
                                select {
2✔
1027
                                case b.notificationCancels <- cancel:
2✔
1028
                                        // Cancellation is being handled, drain the epoch channel until it is
2✔
1029
                                        // closed before yielding to caller.
2✔
1030
                                        for {
6✔
1031
                                                select {
4✔
1032
                                                case _, ok := <-reg.epochChan:
4✔
1033
                                                        if !ok {
6✔
1034
                                                                return
2✔
1035
                                                        }
2✔
UNCOV
1036
                                                case <-b.quit:
×
UNCOV
1037
                                                        return
×
1038
                                                }
1039
                                        }
UNCOV
1040
                                case <-b.quit:
×
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) {
424✔
1051

424✔
1052
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
424✔
1053
}
424✔
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(
UNCOV
1061
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
×
UNCOV
1062

×
UNCOV
1063
        event := b.memNotifier.SubscribeInput(outpoint)
×
UNCOV
1064

×
UNCOV
1065
        ops := []*wire.OutPoint{&outpoint}
×
UNCOV
1066

×
UNCOV
1067
        return event, b.chainConn.NotifySpent(ops)
×
UNCOV
1068
}
×
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(
UNCOV
1075
        sub *chainntnfs.MempoolSpendEvent) {
×
UNCOV
1076

×
UNCOV
1077
        b.memNotifier.UnsubscribeEvent(sub)
×
UNCOV
1078
}
×
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(
UNCOV
1085
        op wire.OutPoint) fn.Option[wire.MsgTx] {
×
UNCOV
1086

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

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

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