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

lightningnetwork / lnd / 12262048535

10 Dec 2024 06:05PM UTC coverage: 49.431% (-0.4%) from 49.82%
12262048535

Pull #9316

github

ziggie1984
docs: fix typos in release-notes 19.0
Pull Request #9316: routing: fix mc blinded path behaviour.

200 of 214 new or added lines in 4 files covered. (93.46%)

936 existing lines in 18 files now uncovered.

99466 of 201223 relevant lines covered (49.43%)

1.55 hits per line

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

0.0
/chainntnfs/btcdnotify/btcd.go
1
package btcdnotify
2

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

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

24
const (
25
        // notifierType uniquely identifies this concrete implementation of the
26
        // ChainNotifier interface.
27
        notifierType = "btcd"
28
)
29

30
// chainUpdate encapsulates an update to the current main chain. This struct is
31
// used as an element within an unbounded queue in order to avoid blocking the
32
// main rpc dispatch rule.
33
type chainUpdate struct {
34
        blockHash   *chainhash.Hash
35
        blockHeight int32
36

37
        // connected is true if this update is a new block and false if it is a
38
        // disconnected block.
39
        connect bool
40
}
41

42
// txUpdate encapsulates a transaction related notification sent from btcd to
43
// the registered RPC client. This struct is used as an element within an
44
// unbounded queue in order to avoid blocking the main rpc dispatch rule.
45
type txUpdate struct {
46
        tx      *btcutil.Tx
47
        details *btcjson.BlockDetails
48
}
49

50
// TODO(roasbeef): generalize struct below:
51
//  * move chans to config, allow outside callers to handle send conditions
52

53
// BtcdNotifier implements the ChainNotifier interface using btcd's websockets
54
// notifications. Multiple concurrent clients are supported. All notifications
55
// are achieved via non-blocking sends on client channels.
56
type BtcdNotifier struct {
57
        epochClientCounter uint64 // To be used atomically.
58

59
        start   sync.Once
60
        active  int32 // To be used atomically.
61
        stopped int32 // To be used atomically.
62

63
        chainConn   *chain.RPCClient
64
        chainParams *chaincfg.Params
65

66
        notificationCancels  chan interface{}
67
        notificationRegistry chan interface{}
68

69
        txNotifier *chainntnfs.TxNotifier
70

71
        blockEpochClients map[uint64]*blockEpochRegistration
72

73
        bestBlock chainntnfs.BlockEpoch
74

75
        // blockCache is a LRU block cache.
76
        blockCache *blockcache.BlockCache
77

78
        chainUpdates *queue.ConcurrentQueue
79
        txUpdates    *queue.ConcurrentQueue
80

81
        // spendHintCache is a cache used to query and update the latest height
82
        // hints for an outpoint. Each height hint represents the earliest
83
        // height at which the outpoint could have been spent within the chain.
84
        spendHintCache chainntnfs.SpendHintCache
85

86
        // confirmHintCache is a cache used to query the latest height hints for
87
        // a transaction. Each height hint represents the earliest height at
88
        // which the transaction could have confirmed within the chain.
89
        confirmHintCache chainntnfs.ConfirmHintCache
90

91
        // memNotifier notifies clients of events related to the mempool.
92
        memNotifier *chainntnfs.MempoolNotifier
93

94
        wg   sync.WaitGroup
95
        quit chan struct{}
96
}
97

98
// Ensure BtcdNotifier implements the ChainNotifier interface at compile time.
99
var _ chainntnfs.ChainNotifier = (*BtcdNotifier)(nil)
100

101
// Ensure BtcdNotifier implements the MempoolWatcher interface at compile time.
102
var _ chainntnfs.MempoolWatcher = (*BtcdNotifier)(nil)
103

104
// New returns a new BtcdNotifier instance. This function assumes the btcd node
105
// detailed in the passed configuration is already running, and willing to
106
// accept new websockets clients.
107
func New(config *rpcclient.ConnConfig, chainParams *chaincfg.Params,
108
        spendHintCache chainntnfs.SpendHintCache,
109
        confirmHintCache chainntnfs.ConfirmHintCache,
UNCOV
110
        blockCache *blockcache.BlockCache) (*BtcdNotifier, error) {
×
UNCOV
111

×
UNCOV
112
        notifier := &BtcdNotifier{
×
UNCOV
113
                chainParams: chainParams,
×
UNCOV
114

×
UNCOV
115
                notificationCancels:  make(chan interface{}),
×
UNCOV
116
                notificationRegistry: make(chan interface{}),
×
UNCOV
117

×
UNCOV
118
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
×
UNCOV
119

×
UNCOV
120
                chainUpdates: queue.NewConcurrentQueue(10),
×
UNCOV
121
                txUpdates:    queue.NewConcurrentQueue(10),
×
UNCOV
122

×
UNCOV
123
                spendHintCache:   spendHintCache,
×
UNCOV
124
                confirmHintCache: confirmHintCache,
×
UNCOV
125

×
UNCOV
126
                blockCache:  blockCache,
×
UNCOV
127
                memNotifier: chainntnfs.NewMempoolNotifier(),
×
UNCOV
128

×
UNCOV
129
                quit: make(chan struct{}),
×
UNCOV
130
        }
×
UNCOV
131

×
UNCOV
132
        ntfnCallbacks := &rpcclient.NotificationHandlers{
×
UNCOV
133
                OnBlockConnected:    notifier.onBlockConnected,
×
UNCOV
134
                OnBlockDisconnected: notifier.onBlockDisconnected,
×
UNCOV
135
                OnRedeemingTx:       notifier.onRedeemingTx,
×
UNCOV
136
        }
×
UNCOV
137

×
UNCOV
138
        rpcCfg := &chain.RPCClientConfig{
×
UNCOV
139
                ReconnectAttempts:    20,
×
UNCOV
140
                Conn:                 config,
×
UNCOV
141
                Chain:                chainParams,
×
UNCOV
142
                NotificationHandlers: ntfnCallbacks,
×
UNCOV
143
        }
×
UNCOV
144

×
UNCOV
145
        chainRPC, err := chain.NewRPCClientWithConfig(rpcCfg)
×
UNCOV
146
        if err != nil {
×
147
                return nil, err
×
148
        }
×
149

UNCOV
150
        notifier.chainConn = chainRPC
×
UNCOV
151

×
UNCOV
152
        return notifier, nil
×
153
}
154

155
// Start connects to the running btcd node over websockets, registers for block
156
// notifications, and finally launches all related helper goroutines.
UNCOV
157
func (b *BtcdNotifier) Start() error {
×
UNCOV
158
        var startErr error
×
UNCOV
159
        b.start.Do(func() {
×
UNCOV
160
                startErr = b.startNotifier()
×
UNCOV
161
        })
×
162

UNCOV
163
        return startErr
×
164
}
165

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

171
// Stop shutsdown the BtcdNotifier.
UNCOV
172
func (b *BtcdNotifier) Stop() error {
×
UNCOV
173
        // Already shutting down?
×
UNCOV
174
        if atomic.AddInt32(&b.stopped, 1) != 1 {
×
175
                return nil
×
176
        }
×
177

UNCOV
178
        chainntnfs.Log.Info("btcd notifier shutting down...")
×
UNCOV
179
        defer chainntnfs.Log.Debug("btcd notifier shutdown complete")
×
UNCOV
180

×
UNCOV
181
        // Shutdown the rpc client, this gracefully disconnects from btcd, and
×
UNCOV
182
        // cleans up all related resources.
×
UNCOV
183
        b.chainConn.Stop()
×
UNCOV
184

×
UNCOV
185
        close(b.quit)
×
UNCOV
186
        b.wg.Wait()
×
UNCOV
187

×
UNCOV
188
        b.chainUpdates.Stop()
×
UNCOV
189
        b.txUpdates.Stop()
×
UNCOV
190

×
UNCOV
191
        // Notify all pending clients of our shutdown by closing the related
×
UNCOV
192
        // notification channels.
×
UNCOV
193
        for _, epochClient := range b.blockEpochClients {
×
UNCOV
194
                close(epochClient.cancelChan)
×
UNCOV
195
                epochClient.wg.Wait()
×
UNCOV
196

×
UNCOV
197
                close(epochClient.epochChan)
×
UNCOV
198
        }
×
UNCOV
199
        b.txNotifier.TearDown()
×
UNCOV
200

×
UNCOV
201
        // Stop the mempool notifier.
×
UNCOV
202
        b.memNotifier.TearDown()
×
UNCOV
203

×
UNCOV
204
        return nil
×
205
}
206

UNCOV
207
func (b *BtcdNotifier) startNotifier() error {
×
UNCOV
208
        // Start our concurrent queues before starting the chain connection, to
×
UNCOV
209
        // ensure onBlockConnected and onRedeemingTx callbacks won't be
×
UNCOV
210
        // blocked.
×
UNCOV
211
        b.chainUpdates.Start()
×
UNCOV
212
        b.txUpdates.Start()
×
UNCOV
213

×
UNCOV
214
        // Connect to btcd, and register for notifications on connected, and
×
UNCOV
215
        // disconnected blocks.
×
UNCOV
216
        if err := b.chainConn.Connect(20); err != nil {
×
217
                b.txUpdates.Stop()
×
218
                b.chainUpdates.Stop()
×
219
                return err
×
220
        }
×
221

UNCOV
222
        currentHash, currentHeight, err := b.chainConn.GetBestBlock()
×
UNCOV
223
        if err != nil {
×
224
                b.txUpdates.Stop()
×
225
                b.chainUpdates.Stop()
×
226
                return err
×
227
        }
×
228

UNCOV
229
        bestBlock, err := b.chainConn.GetBlock(currentHash)
×
UNCOV
230
        if err != nil {
×
231
                b.txUpdates.Stop()
×
232
                b.chainUpdates.Stop()
×
233
                return err
×
234
        }
×
235

UNCOV
236
        b.txNotifier = chainntnfs.NewTxNotifier(
×
UNCOV
237
                uint32(currentHeight), chainntnfs.ReorgSafetyLimit,
×
UNCOV
238
                b.confirmHintCache, b.spendHintCache,
×
UNCOV
239
        )
×
UNCOV
240

×
UNCOV
241
        b.bestBlock = chainntnfs.BlockEpoch{
×
UNCOV
242
                Height:      currentHeight,
×
UNCOV
243
                Hash:        currentHash,
×
UNCOV
244
                BlockHeader: &bestBlock.Header,
×
UNCOV
245
        }
×
UNCOV
246

×
UNCOV
247
        if err := b.chainConn.NotifyBlocks(); err != nil {
×
248
                b.txUpdates.Stop()
×
249
                b.chainUpdates.Stop()
×
250
                return err
×
251
        }
×
252

UNCOV
253
        b.wg.Add(1)
×
UNCOV
254
        go b.notificationDispatcher()
×
UNCOV
255

×
UNCOV
256
        // Set the active flag now that we've completed the full
×
UNCOV
257
        // startup.
×
UNCOV
258
        atomic.StoreInt32(&b.active, 1)
×
UNCOV
259

×
UNCOV
260
        return nil
×
261
}
262

263
// onBlockConnected implements on OnBlockConnected callback for rpcclient.
264
// Ingesting a block updates the wallet's internal utxo state based on the
265
// outputs created and destroyed within each block.
UNCOV
266
func (b *BtcdNotifier) onBlockConnected(hash *chainhash.Hash, height int32, t time.Time) {
×
UNCOV
267
        // Append this new chain update to the end of the queue of new chain
×
UNCOV
268
        // updates.
×
UNCOV
269
        select {
×
270
        case b.chainUpdates.ChanIn() <- &chainUpdate{
271
                blockHash:   hash,
272
                blockHeight: height,
273
                connect:     true,
UNCOV
274
        }:
×
275
        case <-b.quit:
×
276
                return
×
277
        }
278
}
279

280
// filteredBlock represents a new block which has been connected to the main
281
// chain. The slice of transactions will only be populated if the block
282
// includes a transaction that confirmed one of our watched txids, or spends
283
// one of the outputs currently being watched.
284
//
285
// TODO(halseth): this is currently used for complete blocks. Change to use
286
// onFilteredBlockConnected and onFilteredBlockDisconnected, making it easier
287
// to unify with the Neutrino implementation.
288
type filteredBlock struct {
289
        hash   chainhash.Hash
290
        height uint32
291
        block  *btcutil.Block
292

293
        // connected is true if this update is a new block and false if it is a
294
        // disconnected block.
295
        connect bool
296
}
297

298
// onBlockDisconnected implements on OnBlockDisconnected callback for rpcclient.
UNCOV
299
func (b *BtcdNotifier) onBlockDisconnected(hash *chainhash.Hash, height int32, t time.Time) {
×
UNCOV
300
        // Append this new chain update to the end of the queue of new chain
×
UNCOV
301
        // updates.
×
UNCOV
302
        select {
×
303
        case b.chainUpdates.ChanIn() <- &chainUpdate{
304
                blockHash:   hash,
305
                blockHeight: height,
306
                connect:     false,
UNCOV
307
        }:
×
308
        case <-b.quit:
×
309
                return
×
310
        }
311
}
312

313
// onRedeemingTx implements on OnRedeemingTx callback for rpcclient.
UNCOV
314
func (b *BtcdNotifier) onRedeemingTx(tx *btcutil.Tx, details *btcjson.BlockDetails) {
×
UNCOV
315
        // Append this new transaction update to the end of the queue of new
×
UNCOV
316
        // chain updates.
×
UNCOV
317
        select {
×
UNCOV
318
        case b.txUpdates.ChanIn() <- &txUpdate{tx, details}:
×
319
        case <-b.quit:
×
320
                return
×
321
        }
322
}
323

324
// notificationDispatcher is the primary goroutine which handles client
325
// notification registrations, as well as notification dispatches.
UNCOV
326
func (b *BtcdNotifier) notificationDispatcher() {
×
UNCOV
327
        defer b.wg.Done()
×
UNCOV
328

×
UNCOV
329
out:
×
UNCOV
330
        for {
×
UNCOV
331
                select {
×
UNCOV
332
                case cancelMsg := <-b.notificationCancels:
×
UNCOV
333
                        switch msg := cancelMsg.(type) {
×
UNCOV
334
                        case *epochCancel:
×
UNCOV
335
                                chainntnfs.Log.Infof("Cancelling epoch "+
×
UNCOV
336
                                        "notification, epoch_id=%v", msg.epochID)
×
UNCOV
337

×
UNCOV
338
                                // First, we'll lookup the original
×
UNCOV
339
                                // registration in order to stop the active
×
UNCOV
340
                                // queue goroutine.
×
UNCOV
341
                                reg := b.blockEpochClients[msg.epochID]
×
UNCOV
342
                                reg.epochQueue.Stop()
×
UNCOV
343

×
UNCOV
344
                                // Next, close the cancel channel for this
×
UNCOV
345
                                // specific client, and wait for the client to
×
UNCOV
346
                                // exit.
×
UNCOV
347
                                close(b.blockEpochClients[msg.epochID].cancelChan)
×
UNCOV
348
                                b.blockEpochClients[msg.epochID].wg.Wait()
×
UNCOV
349

×
UNCOV
350
                                // Once the client has exited, we can then
×
UNCOV
351
                                // safely close the channel used to send epoch
×
UNCOV
352
                                // notifications, in order to notify any
×
UNCOV
353
                                // listeners that the intent has been
×
UNCOV
354
                                // canceled.
×
UNCOV
355
                                close(b.blockEpochClients[msg.epochID].epochChan)
×
UNCOV
356
                                delete(b.blockEpochClients, msg.epochID)
×
357
                        }
UNCOV
358
                case registerMsg := <-b.notificationRegistry:
×
UNCOV
359
                        switch msg := registerMsg.(type) {
×
UNCOV
360
                        case *chainntnfs.HistoricalConfDispatch:
×
UNCOV
361
                                // Look up whether the transaction/output script
×
UNCOV
362
                                // has already confirmed in the active chain.
×
UNCOV
363
                                // We'll do this in a goroutine to prevent
×
UNCOV
364
                                // blocking potentially long rescans.
×
UNCOV
365
                                //
×
UNCOV
366
                                // TODO(wilmer): add retry logic if rescan fails?
×
UNCOV
367
                                b.wg.Add(1)
×
UNCOV
368

×
UNCOV
369
                                //nolint:ll
×
UNCOV
370
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
×
UNCOV
371
                                        defer b.wg.Done()
×
UNCOV
372

×
UNCOV
373
                                        confDetails, _, err := b.historicalConfDetails(
×
UNCOV
374
                                                msg.ConfRequest,
×
UNCOV
375
                                                msg.StartHeight, msg.EndHeight,
×
UNCOV
376
                                        )
×
UNCOV
377
                                        if err != nil {
×
378
                                                chainntnfs.Log.Error(err)
×
379
                                                return
×
380
                                        }
×
381

382
                                        // If the historical dispatch finished
383
                                        // without error, we will invoke
384
                                        // UpdateConfDetails even if none were
385
                                        // found. This allows the notifier to
386
                                        // begin safely updating the height hint
387
                                        // cache at tip, since any pending
388
                                        // rescans have now completed.
UNCOV
389
                                        err = b.txNotifier.UpdateConfDetails(
×
UNCOV
390
                                                msg.ConfRequest, confDetails,
×
UNCOV
391
                                        )
×
UNCOV
392
                                        if err != nil {
×
393
                                                chainntnfs.Log.Error(err)
×
394
                                        }
×
395
                                }(msg)
396

UNCOV
397
                        case *blockEpochRegistration:
×
UNCOV
398
                                chainntnfs.Log.Infof("New block epoch subscription")
×
UNCOV
399

×
UNCOV
400
                                b.blockEpochClients[msg.epochID] = msg
×
UNCOV
401

×
UNCOV
402
                                // If the client did not provide their best
×
UNCOV
403
                                // known block, then we'll immediately dispatch
×
UNCOV
404
                                // a notification for the current tip.
×
UNCOV
405
                                if msg.bestBlock == nil {
×
UNCOV
406
                                        b.notifyBlockEpochClient(
×
UNCOV
407
                                                msg, b.bestBlock.Height,
×
UNCOV
408
                                                b.bestBlock.Hash,
×
UNCOV
409
                                                b.bestBlock.BlockHeader,
×
UNCOV
410
                                        )
×
UNCOV
411

×
UNCOV
412
                                        msg.errorChan <- nil
×
UNCOV
413
                                        continue
×
414
                                }
415

416
                                // Otherwise, we'll attempt to deliver the
417
                                // backlog of notifications from their best
418
                                // known block.
UNCOV
419
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
×
UNCOV
420
                                        b.chainConn, msg.bestBlock,
×
UNCOV
421
                                        b.bestBlock.Height, true,
×
UNCOV
422
                                )
×
UNCOV
423
                                if err != nil {
×
424
                                        msg.errorChan <- err
×
425
                                        continue
×
426
                                }
427

UNCOV
428
                                for _, block := range missedBlocks {
×
UNCOV
429
                                        b.notifyBlockEpochClient(
×
UNCOV
430
                                                msg, block.Height, block.Hash,
×
UNCOV
431
                                                block.BlockHeader,
×
UNCOV
432
                                        )
×
UNCOV
433
                                }
×
434

UNCOV
435
                                msg.errorChan <- nil
×
436
                        }
437

UNCOV
438
                case item := <-b.chainUpdates.ChanOut():
×
UNCOV
439
                        update := item.(*chainUpdate)
×
UNCOV
440
                        if update.connect {
×
UNCOV
441
                                blockHeader, err := b.chainConn.GetBlockHeader(
×
UNCOV
442
                                        update.blockHash,
×
UNCOV
443
                                )
×
UNCOV
444
                                if err != nil {
×
445
                                        chainntnfs.Log.Errorf("Unable to fetch "+
×
446
                                                "block header: %v", err)
×
447
                                        continue
×
448
                                }
449

UNCOV
450
                                if blockHeader.PrevBlock != *b.bestBlock.Hash {
×
451
                                        // Handle the case where the notifier
×
452
                                        // missed some blocks from its chain
×
453
                                        // backend
×
454
                                        chainntnfs.Log.Infof("Missed blocks, " +
×
455
                                                "attempting to catch up")
×
456
                                        newBestBlock, missedBlocks, err :=
×
457
                                                chainntnfs.HandleMissedBlocks(
×
458
                                                        b.chainConn,
×
459
                                                        b.txNotifier,
×
460
                                                        b.bestBlock,
×
461
                                                        update.blockHeight,
×
462
                                                        true,
×
463
                                                )
×
464
                                        if err != nil {
×
465
                                                // Set the bestBlock here in case
×
466
                                                // a catch up partially completed.
×
467
                                                b.bestBlock = newBestBlock
×
468
                                                chainntnfs.Log.Error(err)
×
469
                                                continue
×
470
                                        }
471

472
                                        for _, block := range missedBlocks {
×
473
                                                err := b.handleBlockConnected(block)
×
474
                                                if err != nil {
×
475
                                                        chainntnfs.Log.Error(err)
×
476
                                                        continue out
×
477
                                                }
478
                                        }
479
                                }
480

UNCOV
481
                                newBlock := chainntnfs.BlockEpoch{
×
UNCOV
482
                                        Height:      update.blockHeight,
×
UNCOV
483
                                        Hash:        update.blockHash,
×
UNCOV
484
                                        BlockHeader: blockHeader,
×
UNCOV
485
                                }
×
UNCOV
486
                                if err := b.handleBlockConnected(newBlock); err != nil {
×
487
                                        chainntnfs.Log.Error(err)
×
488
                                }
×
UNCOV
489
                                continue
×
490
                        }
491

UNCOV
492
                        if update.blockHeight != b.bestBlock.Height {
×
UNCOV
493
                                chainntnfs.Log.Infof("Missed disconnected" +
×
UNCOV
494
                                        "blocks, attempting to catch up")
×
UNCOV
495
                        }
×
496

UNCOV
497
                        newBestBlock, err := chainntnfs.RewindChain(
×
UNCOV
498
                                b.chainConn, b.txNotifier, b.bestBlock,
×
UNCOV
499
                                update.blockHeight-1,
×
UNCOV
500
                        )
×
UNCOV
501
                        if err != nil {
×
UNCOV
502
                                chainntnfs.Log.Errorf("Unable to rewind chain "+
×
UNCOV
503
                                        "from height %d to height %d: %v",
×
UNCOV
504
                                        b.bestBlock.Height, update.blockHeight-1, err)
×
UNCOV
505
                        }
×
506

507
                        // Set the bestBlock here in case a chain rewind
508
                        // partially completed.
UNCOV
509
                        b.bestBlock = newBestBlock
×
510

UNCOV
511
                case item := <-b.txUpdates.ChanOut():
×
UNCOV
512
                        newSpend := item.(*txUpdate)
×
UNCOV
513
                        tx := newSpend.tx
×
UNCOV
514

×
UNCOV
515
                        // Init values.
×
UNCOV
516
                        isMempool := false
×
UNCOV
517
                        height := uint32(0)
×
UNCOV
518

×
UNCOV
519
                        // Unwrap values.
×
UNCOV
520
                        if newSpend.details == nil {
×
UNCOV
521
                                isMempool = true
×
UNCOV
522
                        } else {
×
UNCOV
523
                                height = uint32(newSpend.details.Height)
×
UNCOV
524
                        }
×
525

526
                        // Handle the transaction.
UNCOV
527
                        b.handleRelevantTx(tx, isMempool, height)
×
528

UNCOV
529
                case <-b.quit:
×
UNCOV
530
                        break out
×
531
                }
532
        }
533
}
534

535
// handleRelevantTx handles a new transaction that has been seen either in a
536
// block or in the mempool. If in mempool, it will ask the mempool notifier to
537
// handle it. If in a block, it will ask the txNotifier to handle it, and
538
// cancel any relevant subscriptions made in the mempool.
539
func (b *BtcdNotifier) handleRelevantTx(tx *btcutil.Tx,
UNCOV
540
        mempool bool, height uint32) {
×
UNCOV
541

×
UNCOV
542
        // If this is a mempool spend, we'll ask the mempool notifier to hanlde
×
UNCOV
543
        // it.
×
UNCOV
544
        if mempool {
×
UNCOV
545
                err := b.memNotifier.ProcessRelevantSpendTx(tx)
×
UNCOV
546
                if err != nil {
×
547
                        chainntnfs.Log.Errorf("Unable to process transaction "+
×
548
                                "%v: %v", tx.Hash(), err)
×
549
                }
×
550

UNCOV
551
                return
×
552
        }
553

554
        // Otherwise this is a confirmed spend, and we'll ask the tx notifier
555
        // to handle it.
UNCOV
556
        err := b.txNotifier.ProcessRelevantSpendTx(tx, height)
×
UNCOV
557
        if err != nil {
×
558
                chainntnfs.Log.Errorf("Unable to process transaction %v: %v",
×
559
                        tx.Hash(), err)
×
560

×
561
                return
×
562
        }
×
563

564
        // Once the tx is processed, we will ask the memNotifier to unsubscribe
565
        // the input.
566
        //
567
        // NOTE(yy): we could build it into txNotifier.ProcessRelevantSpendTx,
568
        // but choose to implement it here so we can easily decouple the two
569
        // notifiers in the future.
UNCOV
570
        b.memNotifier.UnsubsribeConfirmedSpentTx(tx)
×
571
}
572

573
// historicalConfDetails looks up whether a confirmation request (txid/output
574
// script) has already been included in a block in the active chain and, if so,
575
// returns details about said block.
576
func (b *BtcdNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
577
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
UNCOV
578
        chainntnfs.TxConfStatus, error) {
×
UNCOV
579

×
UNCOV
580
        // If a txid was not provided, then we should dispatch upon seeing the
×
UNCOV
581
        // script on-chain, so we'll short-circuit straight to scanning manually
×
UNCOV
582
        // as there doesn't exist a script index to query.
×
UNCOV
583
        if confRequest.TxID == chainntnfs.ZeroHash {
×
584
                return b.confDetailsManually(
×
585
                        confRequest, startHeight, endHeight,
×
586
                )
×
587
        }
×
588

589
        // Otherwise, we'll dispatch upon seeing a transaction on-chain with the
590
        // given hash.
591
        //
592
        // We'll first attempt to retrieve the transaction using the node's
593
        // txindex.
UNCOV
594
        txNotFoundErr := "No information available about transaction"
×
UNCOV
595
        txConf, txStatus, err := chainntnfs.ConfDetailsFromTxIndex(
×
UNCOV
596
                b.chainConn, confRequest, txNotFoundErr,
×
UNCOV
597
        )
×
UNCOV
598

×
UNCOV
599
        // We'll then check the status of the transaction lookup returned to
×
UNCOV
600
        // determine whether we should proceed with any fallback methods.
×
UNCOV
601
        switch {
×
602

603
        // We failed querying the index for the transaction, fall back to
604
        // scanning manually.
605
        case err != nil:
×
606
                chainntnfs.Log.Debugf("Unable to determine confirmation of %v "+
×
607
                        "through the backend's txindex (%v), scanning manually",
×
608
                        confRequest.TxID, err)
×
609

×
610
                return b.confDetailsManually(
×
611
                        confRequest, startHeight, endHeight,
×
612
                )
×
613

614
        // The transaction was found within the node's mempool.
UNCOV
615
        case txStatus == chainntnfs.TxFoundMempool:
×
616

617
        // The transaction was found within the node's txindex.
UNCOV
618
        case txStatus == chainntnfs.TxFoundIndex:
×
619

620
        // The transaction was not found within the node's mempool or txindex.
UNCOV
621
        case txStatus == chainntnfs.TxNotFoundIndex:
×
622

623
        // Unexpected txStatus returned.
624
        default:
×
625
                return nil, txStatus,
×
626
                        fmt.Errorf("Got unexpected txConfStatus: %v", txStatus)
×
627
        }
628

UNCOV
629
        return txConf, txStatus, nil
×
630
}
631

632
// confDetailsManually looks up whether a transaction/output script has already
633
// been included in a block in the active chain by scanning the chain's blocks
634
// within the given range. If the transaction/output script is found, its
635
// confirmation details are returned. Otherwise, nil is returned.
636
func (b *BtcdNotifier) confDetailsManually(confRequest chainntnfs.ConfRequest,
637
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation,
638
        chainntnfs.TxConfStatus, error) {
×
639

×
640
        // Begin scanning blocks at every height to determine where the
×
641
        // transaction was included in.
×
642
        for height := endHeight; height >= startHeight && height > 0; height-- {
×
643
                // Ensure we haven't been requested to shut down before
×
644
                // processing the next height.
×
645
                select {
×
646
                case <-b.quit:
×
647
                        return nil, chainntnfs.TxNotFoundManually,
×
648
                                chainntnfs.ErrChainNotifierShuttingDown
×
649
                default:
×
650
                }
651

652
                blockHash, err := b.chainConn.GetBlockHash(int64(height))
×
653
                if err != nil {
×
654
                        return nil, chainntnfs.TxNotFoundManually,
×
655
                                fmt.Errorf("unable to get hash from block "+
×
656
                                        "with height %d", height)
×
657
                }
×
658

659
                // TODO: fetch the neutrino filters instead.
660
                block, err := b.GetBlock(blockHash)
×
661
                if err != nil {
×
662
                        return nil, chainntnfs.TxNotFoundManually,
×
663
                                fmt.Errorf("unable to get block with hash "+
×
664
                                        "%v: %v", blockHash, err)
×
665
                }
×
666

667
                // For every transaction in the block, check which one matches
668
                // our request. If we find one that does, we can dispatch its
669
                // confirmation details.
670
                for txIndex, tx := range block.Transactions {
×
671
                        if !confRequest.MatchesTx(tx) {
×
672
                                continue
×
673
                        }
674

675
                        return &chainntnfs.TxConfirmation{
×
676
                                Tx:          tx.Copy(),
×
677
                                BlockHash:   blockHash,
×
678
                                BlockHeight: height,
×
679
                                TxIndex:     uint32(txIndex),
×
680
                                Block:       block,
×
681
                        }, chainntnfs.TxFoundManually, nil
×
682
                }
683
        }
684

685
        // If we reach here, then we were not able to find the transaction
686
        // within a block, so we avoid returning an error.
687
        return nil, chainntnfs.TxNotFoundManually, nil
×
688
}
689

690
// handleBlockConnected applies a chain update for a new block. Any watched
691
// transactions included this block will processed to either send notifications
692
// now or after numConfirmations confs.
693
// TODO(halseth): this is reusing the neutrino notifier implementation, unify
694
// them.
UNCOV
695
func (b *BtcdNotifier) handleBlockConnected(epoch chainntnfs.BlockEpoch) error {
×
UNCOV
696
        // First, we'll fetch the raw block as we'll need to gather all the
×
UNCOV
697
        // transactions to determine whether any are relevant to our registered
×
UNCOV
698
        // clients.
×
UNCOV
699
        rawBlock, err := b.GetBlock(epoch.Hash)
×
UNCOV
700
        if err != nil {
×
701
                return fmt.Errorf("unable to get block: %w", err)
×
702
        }
×
UNCOV
703
        newBlock := &filteredBlock{
×
UNCOV
704
                hash:    *epoch.Hash,
×
UNCOV
705
                height:  uint32(epoch.Height),
×
UNCOV
706
                block:   btcutil.NewBlock(rawBlock),
×
UNCOV
707
                connect: true,
×
UNCOV
708
        }
×
UNCOV
709

×
UNCOV
710
        // We'll then extend the txNotifier's height with the information of
×
UNCOV
711
        // this new block, which will handle all of the notification logic for
×
UNCOV
712
        // us.
×
UNCOV
713
        err = b.txNotifier.ConnectTip(newBlock.block, newBlock.height)
×
UNCOV
714
        if err != nil {
×
715
                return fmt.Errorf("unable to connect tip: %w", err)
×
716
        }
×
717

UNCOV
718
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", epoch.Height,
×
UNCOV
719
                epoch.Hash)
×
UNCOV
720

×
UNCOV
721
        // Now that we've guaranteed the new block extends the txNotifier's
×
UNCOV
722
        // current tip, we'll proceed to dispatch notifications to all of our
×
UNCOV
723
        // registered clients whom have had notifications fulfilled. Before
×
UNCOV
724
        // doing so, we'll make sure update our in memory state in order to
×
UNCOV
725
        // satisfy any client requests based upon the new block.
×
UNCOV
726
        b.bestBlock = epoch
×
UNCOV
727

×
UNCOV
728
        err = b.txNotifier.NotifyHeight(uint32(epoch.Height))
×
UNCOV
729
        if err != nil {
×
730
                return fmt.Errorf("unable to notify height: %w", err)
×
731
        }
×
732

UNCOV
733
        b.notifyBlockEpochs(
×
UNCOV
734
                epoch.Height, epoch.Hash, epoch.BlockHeader,
×
UNCOV
735
        )
×
UNCOV
736

×
UNCOV
737
        return nil
×
738
}
739

740
// notifyBlockEpochs notifies all registered block epoch clients of the newly
741
// connected block to the main chain.
742
func (b *BtcdNotifier) notifyBlockEpochs(newHeight int32,
UNCOV
743
        newSha *chainhash.Hash, blockHeader *wire.BlockHeader) {
×
UNCOV
744

×
UNCOV
745
        for _, client := range b.blockEpochClients {
×
UNCOV
746
                b.notifyBlockEpochClient(
×
UNCOV
747
                        client, newHeight, newSha, blockHeader,
×
UNCOV
748
                )
×
UNCOV
749
        }
×
750
}
751

752
// notifyBlockEpochClient sends a registered block epoch client a notification
753
// about a specific block.
754
func (b *BtcdNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
UNCOV
755
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
×
UNCOV
756

×
UNCOV
757
        epoch := &chainntnfs.BlockEpoch{
×
UNCOV
758
                Height:      height,
×
UNCOV
759
                Hash:        sha,
×
UNCOV
760
                BlockHeader: blockHeader,
×
UNCOV
761
        }
×
UNCOV
762

×
UNCOV
763
        select {
×
UNCOV
764
        case epochClient.epochQueue.ChanIn() <- epoch:
×
765
        case <-epochClient.cancelChan:
×
766
        case <-b.quit:
×
767
        }
768
}
769

770
// RegisterSpendNtfn registers an intent to be notified once the target
771
// outpoint/output script has been spent by a transaction on-chain. When
772
// intending to be notified of the spend of an output script, a nil outpoint
773
// must be used. The heightHint should represent the earliest height in the
774
// chain of the transaction that spent the outpoint/output script.
775
//
776
// Once a spend of has been detected, the details of the spending event will be
777
// sent across the 'Spend' channel.
778
func (b *BtcdNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
UNCOV
779
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
×
UNCOV
780

×
UNCOV
781
        // Register the conf notification with the TxNotifier. A non-nil value
×
UNCOV
782
        // for `dispatch` will be returned if we are required to perform a
×
UNCOV
783
        // manual scan for the confirmation. Otherwise the notifier will begin
×
UNCOV
784
        // watching at tip for the transaction to confirm.
×
UNCOV
785
        ntfn, err := b.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
×
UNCOV
786
        if err != nil {
×
UNCOV
787
                return nil, err
×
UNCOV
788
        }
×
789

790
        // We'll then request the backend to notify us when it has detected the
791
        // outpoint/output script as spent.
792
        //
793
        // TODO(wilmer): use LoadFilter API instead.
UNCOV
794
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
×
795
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
796
                        pkScript, b.chainParams,
×
797
                )
×
798
                if err != nil {
×
799
                        return nil, fmt.Errorf("unable to parse script: %w",
×
800
                                err)
×
801
                }
×
802
                if err := b.chainConn.NotifyReceived(addrs); err != nil {
×
803
                        return nil, err
×
804
                }
×
UNCOV
805
        } else {
×
UNCOV
806
                ops := []*wire.OutPoint{outpoint}
×
UNCOV
807
                if err := b.chainConn.NotifySpent(ops); err != nil {
×
808
                        return nil, err
×
809
                }
×
810
        }
811

812
        // If the txNotifier didn't return any details to perform a historical
813
        // scan of the chain, then we can return early as there's nothing left
814
        // for us to do.
UNCOV
815
        if ntfn.HistoricalDispatch == nil {
×
UNCOV
816
                return ntfn.Event, nil
×
UNCOV
817
        }
×
818

819
        // Otherwise, we'll need to dispatch a historical rescan to determine if
820
        // the outpoint was already spent at a previous height.
821
        //
822
        // We'll short-circuit the path when dispatching the spend of a script,
823
        // rather than an outpoint, as there aren't any additional checks we can
824
        // make for scripts.
UNCOV
825
        if outpoint == nil || *outpoint == chainntnfs.ZeroOutPoint {
×
826
                startHash, err := b.chainConn.GetBlockHash(
×
827
                        int64(ntfn.HistoricalDispatch.StartHeight),
×
828
                )
×
829
                if err != nil {
×
830
                        return nil, err
×
831
                }
×
832

833
                // TODO(wilmer): add retry logic if rescan fails?
834
                _, addrs, _, err := txscript.ExtractPkScriptAddrs(
×
835
                        pkScript, b.chainParams,
×
836
                )
×
837
                if err != nil {
×
838
                        return nil, fmt.Errorf("unable to parse address: %w",
×
839
                                err)
×
840
                }
×
841

842
                asyncResult := b.chainConn.RescanAsync(startHash, addrs, nil)
×
843
                go func() {
×
844
                        if rescanErr := asyncResult.Receive(); rescanErr != nil {
×
845
                                chainntnfs.Log.Errorf("Rescan to determine "+
×
846
                                        "the spend details of %v failed: %v",
×
847
                                        ntfn.HistoricalDispatch.SpendRequest,
×
848
                                        rescanErr)
×
849
                        }
×
850
                }()
851

852
                return ntfn.Event, nil
×
853
        }
854

855
        // When dispatching spends of outpoints, there are a number of checks we
856
        // can make to start our rescan from a better height or completely avoid
857
        // it.
858
        //
859
        // We'll start by checking the backend's UTXO set to determine whether
860
        // the outpoint has been spent. If it hasn't, we can return to the
861
        // caller as well.
UNCOV
862
        txOut, err := b.chainConn.GetTxOut(&outpoint.Hash, outpoint.Index, true)
×
UNCOV
863
        if err != nil {
×
864
                return nil, err
×
865
        }
×
UNCOV
866
        if txOut != nil {
×
UNCOV
867
                // We'll let the txNotifier know the outpoint is still unspent
×
UNCOV
868
                // in order to begin updating its spend hint.
×
UNCOV
869
                err := b.txNotifier.UpdateSpendDetails(
×
UNCOV
870
                        ntfn.HistoricalDispatch.SpendRequest, nil,
×
UNCOV
871
                )
×
UNCOV
872
                if err != nil {
×
873
                        return nil, err
×
874
                }
×
875

UNCOV
876
                return ntfn.Event, nil
×
877
        }
878

879
        // Since the outpoint was spent, as it no longer exists within the UTXO
880
        // set, we'll determine when it happened by scanning the chain. We'll
881
        // begin by fetching the block hash of our starting height.
UNCOV
882
        startHash, err := b.chainConn.GetBlockHash(
×
UNCOV
883
                int64(ntfn.HistoricalDispatch.StartHeight),
×
UNCOV
884
        )
×
UNCOV
885
        if err != nil {
×
886
                return nil, fmt.Errorf("unable to get block hash for height "+
×
887
                        "%d: %v", ntfn.HistoricalDispatch.StartHeight, err)
×
888
        }
×
889

890
        // As a minimal optimization, we'll query the backend's transaction
891
        // index (if enabled) to determine if we have a better rescan starting
892
        // height. We can do this as the GetRawTransaction call will return the
893
        // hash of the block it was included in within the chain.
UNCOV
894
        tx, err := b.chainConn.GetRawTransactionVerbose(&outpoint.Hash)
×
UNCOV
895
        if err != nil {
×
UNCOV
896
                // Avoid returning an error if the transaction was not found to
×
UNCOV
897
                // proceed with fallback methods.
×
UNCOV
898
                jsonErr, ok := err.(*btcjson.RPCError)
×
UNCOV
899
                if !ok || jsonErr.Code != btcjson.ErrRPCNoTxInfo {
×
900
                        return nil, fmt.Errorf("unable to query for txid %v: "+
×
901
                                "%w", outpoint.Hash, err)
×
902
                }
×
903
        }
904

905
        // If the transaction index was enabled, we'll use the block's hash to
906
        // retrieve its height and check whether it provides a better starting
907
        // point for our rescan.
UNCOV
908
        if tx != nil {
×
UNCOV
909
                // If the transaction containing the outpoint hasn't confirmed
×
UNCOV
910
                // on-chain, then there's no need to perform a rescan.
×
UNCOV
911
                if tx.BlockHash == "" {
×
UNCOV
912
                        return ntfn.Event, nil
×
UNCOV
913
                }
×
914

UNCOV
915
                blockHash, err := chainhash.NewHashFromStr(tx.BlockHash)
×
UNCOV
916
                if err != nil {
×
917
                        return nil, err
×
918
                }
×
UNCOV
919
                blockHeader, err := b.chainConn.GetBlockHeaderVerbose(blockHash)
×
UNCOV
920
                if err != nil {
×
921
                        return nil, fmt.Errorf("unable to get header for "+
×
922
                                "block %v: %v", blockHash, err)
×
923
                }
×
924

UNCOV
925
                if uint32(blockHeader.Height) > ntfn.HistoricalDispatch.StartHeight {
×
UNCOV
926
                        startHash, err = b.chainConn.GetBlockHash(
×
UNCOV
927
                                int64(blockHeader.Height),
×
UNCOV
928
                        )
×
UNCOV
929
                        if err != nil {
×
930
                                return nil, fmt.Errorf("unable to get block "+
×
931
                                        "hash for height %d: %v",
×
932
                                        blockHeader.Height, err)
×
933
                        }
×
934
                }
935
        }
936

937
        // Now that we've determined the best starting point for our rescan,
938
        // we can go ahead and dispatch it.
939
        //
940
        // In order to ensure that we don't block the caller on what may be a
941
        // long rescan, we'll launch a new goroutine to handle the async result
942
        // of the rescan. We purposefully prevent from adding this goroutine to
943
        // the WaitGroup as we cannot wait for a quit signal due to the
944
        // asyncResult channel not being exposed.
945
        //
946
        // TODO(wilmer): add retry logic if rescan fails?
UNCOV
947
        asyncResult := b.chainConn.RescanAsync(
×
UNCOV
948
                startHash, nil, []*wire.OutPoint{outpoint},
×
UNCOV
949
        )
×
UNCOV
950
        go func() {
×
UNCOV
951
                if rescanErr := asyncResult.Receive(); rescanErr != nil {
×
952
                        chainntnfs.Log.Errorf("Rescan to determine the spend "+
×
953
                                "details of %v failed: %v", outpoint, rescanErr)
×
954
                }
×
955
        }()
956

UNCOV
957
        return ntfn.Event, nil
×
958
}
959

960
// RegisterConfirmationsNtfn registers an intent to be notified once the target
961
// txid/output script has reached numConfs confirmations on-chain. When
962
// intending to be notified of the confirmation of an output script, a nil txid
963
// must be used. The heightHint should represent the earliest height at which
964
// the txid/output script could have been included in the chain.
965
//
966
// Progress on the number of confirmations left can be read from the 'Updates'
967
// channel. Once it has reached all of its confirmations, a notification will be
968
// sent across the 'Confirmed' channel.
969
func (b *BtcdNotifier) RegisterConfirmationsNtfn(txid *chainhash.Hash,
970
        pkScript []byte, numConfs, heightHint uint32,
UNCOV
971
        opts ...chainntnfs.NotifierOption) (*chainntnfs.ConfirmationEvent, error) {
×
UNCOV
972

×
UNCOV
973
        // Register the conf notification with the TxNotifier. A non-nil value
×
UNCOV
974
        // for `dispatch` will be returned if we are required to perform a
×
UNCOV
975
        // manual scan for the confirmation. Otherwise the notifier will begin
×
UNCOV
976
        // watching at tip for the transaction to confirm.
×
UNCOV
977
        ntfn, err := b.txNotifier.RegisterConf(
×
UNCOV
978
                txid, pkScript, numConfs, heightHint, opts...,
×
UNCOV
979
        )
×
UNCOV
980
        if err != nil {
×
981
                return nil, err
×
982
        }
×
983

UNCOV
984
        if ntfn.HistoricalDispatch == nil {
×
UNCOV
985
                return ntfn.Event, nil
×
UNCOV
986
        }
×
987

UNCOV
988
        select {
×
UNCOV
989
        case b.notificationRegistry <- ntfn.HistoricalDispatch:
×
UNCOV
990
                return ntfn.Event, nil
×
991
        case <-b.quit:
×
992
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
993
        }
994
}
995

996
// blockEpochRegistration represents a client's intent to receive a
997
// notification with each newly connected block.
998
type blockEpochRegistration struct {
999
        epochID uint64
1000

1001
        epochChan chan *chainntnfs.BlockEpoch
1002

1003
        epochQueue *queue.ConcurrentQueue
1004

1005
        bestBlock *chainntnfs.BlockEpoch
1006

1007
        errorChan chan error
1008

1009
        cancelChan chan struct{}
1010

1011
        wg sync.WaitGroup
1012
}
1013

1014
// epochCancel is a message sent to the BtcdNotifier when a client wishes to
1015
// cancel an outstanding epoch notification that has yet to be dispatched.
1016
type epochCancel struct {
1017
        epochID uint64
1018
}
1019

1020
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1021
// caller to receive notifications, of each new block connected to the main
1022
// chain. Clients have the option of passing in their best known block, which
1023
// the notifier uses to check if they are behind on blocks and catch them up. If
1024
// they do not provide one, then a notification will be dispatched immediately
1025
// for the current tip of the chain upon a successful registration.
1026
func (b *BtcdNotifier) RegisterBlockEpochNtfn(
UNCOV
1027
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
×
UNCOV
1028

×
UNCOV
1029
        reg := &blockEpochRegistration{
×
UNCOV
1030
                epochQueue: queue.NewConcurrentQueue(20),
×
UNCOV
1031
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
×
UNCOV
1032
                cancelChan: make(chan struct{}),
×
UNCOV
1033
                epochID:    atomic.AddUint64(&b.epochClientCounter, 1),
×
UNCOV
1034
                bestBlock:  bestBlock,
×
UNCOV
1035
                errorChan:  make(chan error, 1),
×
UNCOV
1036
        }
×
UNCOV
1037

×
UNCOV
1038
        reg.epochQueue.Start()
×
UNCOV
1039

×
UNCOV
1040
        // Before we send the request to the main goroutine, we'll launch a new
×
UNCOV
1041
        // goroutine to proxy items added to our queue to the client itself.
×
UNCOV
1042
        // This ensures that all notifications are received *in order*.
×
UNCOV
1043
        reg.wg.Add(1)
×
UNCOV
1044
        go func() {
×
UNCOV
1045
                defer reg.wg.Done()
×
UNCOV
1046

×
UNCOV
1047
                for {
×
UNCOV
1048
                        select {
×
UNCOV
1049
                        case ntfn := <-reg.epochQueue.ChanOut():
×
UNCOV
1050
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
×
UNCOV
1051
                                select {
×
UNCOV
1052
                                case reg.epochChan <- blockNtfn:
×
1053

UNCOV
1054
                                case <-reg.cancelChan:
×
UNCOV
1055
                                        return
×
1056

1057
                                case <-b.quit:
×
1058
                                        return
×
1059
                                }
1060

UNCOV
1061
                        case <-reg.cancelChan:
×
UNCOV
1062
                                return
×
1063

UNCOV
1064
                        case <-b.quit:
×
UNCOV
1065
                                return
×
1066
                        }
1067
                }
1068
        }()
1069

UNCOV
1070
        select {
×
1071
        case <-b.quit:
×
1072
                // As we're exiting before the registration could be sent,
×
1073
                // we'll stop the queue now ourselves.
×
1074
                reg.epochQueue.Stop()
×
1075

×
1076
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1077
                        "attempting to register for block epoch notification.")
×
UNCOV
1078
        case b.notificationRegistry <- reg:
×
UNCOV
1079
                return &chainntnfs.BlockEpochEvent{
×
UNCOV
1080
                        Epochs: reg.epochChan,
×
UNCOV
1081
                        Cancel: func() {
×
UNCOV
1082
                                cancel := &epochCancel{
×
UNCOV
1083
                                        epochID: reg.epochID,
×
UNCOV
1084
                                }
×
UNCOV
1085

×
UNCOV
1086
                                // Submit epoch cancellation to notification dispatcher.
×
UNCOV
1087
                                select {
×
UNCOV
1088
                                case b.notificationCancels <- cancel:
×
UNCOV
1089
                                        // Cancellation is being handled, drain
×
UNCOV
1090
                                        // the epoch channel until it is closed
×
UNCOV
1091
                                        // before yielding to caller.
×
UNCOV
1092
                                        for {
×
UNCOV
1093
                                                select {
×
UNCOV
1094
                                                case _, ok := <-reg.epochChan:
×
UNCOV
1095
                                                        if !ok {
×
UNCOV
1096
                                                                return
×
UNCOV
1097
                                                        }
×
1098
                                                case <-b.quit:
×
1099
                                                        return
×
1100
                                                }
1101
                                        }
UNCOV
1102
                                case <-b.quit:
×
1103
                                }
1104
                        },
1105
                }, nil
1106
        }
1107
}
1108

1109
// GetBlock is used to retrieve the block with the given hash. This function
1110
// wraps the blockCache's GetBlock function.
1111
func (b *BtcdNotifier) GetBlock(hash *chainhash.Hash) (*wire.MsgBlock,
UNCOV
1112
        error) {
×
UNCOV
1113

×
UNCOV
1114
        return b.blockCache.GetBlock(hash, b.chainConn.GetBlock)
×
UNCOV
1115
}
×
1116

1117
// SubscribeMempoolSpent allows the caller to register a subscription to watch
1118
// for a spend of an outpoint in the mempool.The event will be dispatched once
1119
// the outpoint is spent in the mempool.
1120
//
1121
// NOTE: part of the MempoolWatcher interface.
1122
func (b *BtcdNotifier) SubscribeMempoolSpent(
UNCOV
1123
        outpoint wire.OutPoint) (*chainntnfs.MempoolSpendEvent, error) {
×
UNCOV
1124

×
UNCOV
1125
        event := b.memNotifier.SubscribeInput(outpoint)
×
UNCOV
1126

×
UNCOV
1127
        ops := []*wire.OutPoint{&outpoint}
×
UNCOV
1128

×
UNCOV
1129
        return event, b.chainConn.NotifySpent(ops)
×
UNCOV
1130
}
×
1131

1132
// CancelMempoolSpendEvent allows the caller to cancel a subscription to watch
1133
// for a spend of an outpoint in the mempool.
1134
//
1135
// NOTE: part of the MempoolWatcher interface.
1136
func (b *BtcdNotifier) CancelMempoolSpendEvent(
UNCOV
1137
        sub *chainntnfs.MempoolSpendEvent) {
×
UNCOV
1138

×
UNCOV
1139
        b.memNotifier.UnsubscribeEvent(sub)
×
UNCOV
1140
}
×
1141

1142
// LookupInputMempoolSpend takes an outpoint and queries the mempool to find
1143
// its spending tx. Returns the tx if found, otherwise fn.None.
1144
//
1145
// NOTE: part of the MempoolWatcher interface.
1146
func (b *BtcdNotifier) LookupInputMempoolSpend(
UNCOV
1147
        op wire.OutPoint) fn.Option[wire.MsgTx] {
×
UNCOV
1148

×
UNCOV
1149
        // Find the spending txid.
×
UNCOV
1150
        txid, found := b.chainConn.LookupInputMempoolSpend(op)
×
UNCOV
1151
        if !found {
×
UNCOV
1152
                return fn.None[wire.MsgTx]()
×
UNCOV
1153
        }
×
1154

1155
        // Query the spending tx using the id.
UNCOV
1156
        tx, err := b.chainConn.GetRawTransaction(&txid)
×
UNCOV
1157
        if err != nil {
×
UNCOV
1158
                // TODO(yy): enable logging errors in this package.
×
UNCOV
1159
                return fn.None[wire.MsgTx]()
×
UNCOV
1160
        }
×
1161

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