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

lightningnetwork / lnd / 15205630088

23 May 2025 08:14AM UTC coverage: 57.45% (-11.5%) from 68.996%
15205630088

Pull #9784

github

web-flow
Merge f8b9f36a3 into c52a6ddeb
Pull Request #9784: [wip] lnwallet+walletrpc: add SubmitPackage and related RPC call

47 of 96 new or added lines in 5 files covered. (48.96%)

30087 existing lines in 459 files now uncovered.

95586 of 166380 relevant lines covered (57.45%)

0.61 hits per line

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

0.0
/chainntnfs/neutrinonotify/neutrino.go
1
package neutrinonotify
2

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

11
        "github.com/btcsuite/btcd/btcjson"
12
        "github.com/btcsuite/btcd/btcutil"
13
        "github.com/btcsuite/btcd/btcutil/gcs/builder"
14
        "github.com/btcsuite/btcd/chaincfg/chainhash"
15
        "github.com/btcsuite/btcd/rpcclient"
16
        "github.com/btcsuite/btcd/txscript"
17
        "github.com/btcsuite/btcd/wire"
18
        "github.com/lightninglabs/neutrino"
19
        "github.com/lightninglabs/neutrino/headerfs"
20
        "github.com/lightningnetwork/lnd/blockcache"
21
        "github.com/lightningnetwork/lnd/chainntnfs"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/queue"
24
)
25

26
const (
27
        // notifierType uniquely identifies this concrete implementation of the
28
        // ChainNotifier interface.
29
        notifierType = "neutrino"
30
)
31

32
// NeutrinoNotifier is a version of ChainNotifier that's backed by the neutrino
33
// Bitcoin light client. Unlike other implementations, this implementation
34
// speaks directly to the p2p network. As a result, this implementation of the
35
// ChainNotifier interface is much more light weight that other implementation
36
// which rely of receiving notification over an RPC interface backed by a
37
// running full node.
38
//
39
// TODO(roasbeef): heavily consolidate with NeutrinoNotifier code
40
//   - maybe combine into single package?
41
type NeutrinoNotifier 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
        bestBlockMtx sync.RWMutex
49
        bestBlock    chainntnfs.BlockEpoch
50

51
        p2pNode   *neutrino.ChainService
52
        chainView *neutrino.Rescan
53

54
        chainConn *NeutrinoChainConn
55

56
        notificationCancels  chan interface{}
57
        notificationRegistry chan interface{}
58

59
        txNotifier *chainntnfs.TxNotifier
60

61
        blockEpochClients map[uint64]*blockEpochRegistration
62

63
        rescanErr <-chan error
64

65
        chainUpdates chan *filteredBlock
66

67
        txUpdates *queue.ConcurrentQueue
68

69
        // spendHintCache is a cache used to query and update the latest height
70
        // hints for an outpoint. Each height hint represents the earliest
71
        // height at which the outpoint could have been spent within the chain.
72
        spendHintCache chainntnfs.SpendHintCache
73

74
        // confirmHintCache is a cache used to query the latest height hints for
75
        // a transaction. Each height hint represents the earliest height at
76
        // which the transaction could have confirmed within the chain.
77
        confirmHintCache chainntnfs.ConfirmHintCache
78

79
        // blockCache is an LRU block cache.
80
        blockCache *blockcache.BlockCache
81

82
        wg   sync.WaitGroup
83
        quit chan struct{}
84
}
85

86
// Ensure NeutrinoNotifier implements the ChainNotifier interface at compile time.
87
var _ chainntnfs.ChainNotifier = (*NeutrinoNotifier)(nil)
88

89
// New creates a new instance of the NeutrinoNotifier concrete implementation
90
// of the ChainNotifier interface.
91
//
92
// NOTE: The passed neutrino node should already be running and active before
93
// being passed into this function.
94
func New(node *neutrino.ChainService, spendHintCache chainntnfs.SpendHintCache,
95
        confirmHintCache chainntnfs.ConfirmHintCache,
UNCOV
96
        blockCache *blockcache.BlockCache) *NeutrinoNotifier {
×
UNCOV
97

×
UNCOV
98
        return &NeutrinoNotifier{
×
UNCOV
99
                notificationCancels:  make(chan interface{}),
×
UNCOV
100
                notificationRegistry: make(chan interface{}),
×
UNCOV
101

×
UNCOV
102
                blockEpochClients: make(map[uint64]*blockEpochRegistration),
×
UNCOV
103

×
UNCOV
104
                p2pNode:   node,
×
UNCOV
105
                chainConn: &NeutrinoChainConn{node},
×
UNCOV
106

×
UNCOV
107
                rescanErr: make(chan error),
×
UNCOV
108

×
UNCOV
109
                chainUpdates: make(chan *filteredBlock, 100),
×
UNCOV
110

×
UNCOV
111
                txUpdates: queue.NewConcurrentQueue(10),
×
UNCOV
112

×
UNCOV
113
                spendHintCache:   spendHintCache,
×
UNCOV
114
                confirmHintCache: confirmHintCache,
×
UNCOV
115

×
UNCOV
116
                blockCache: blockCache,
×
UNCOV
117

×
UNCOV
118
                quit: make(chan struct{}),
×
UNCOV
119
        }
×
UNCOV
120
}
×
121

122
// Start contacts the running neutrino light client and kicks off an initial
123
// empty rescan.
UNCOV
124
func (n *NeutrinoNotifier) Start() error {
×
UNCOV
125
        var startErr error
×
UNCOV
126
        n.start.Do(func() {
×
UNCOV
127
                startErr = n.startNotifier()
×
UNCOV
128
        })
×
UNCOV
129
        return startErr
×
130
}
131

132
// Stop shuts down the NeutrinoNotifier.
UNCOV
133
func (n *NeutrinoNotifier) Stop() error {
×
UNCOV
134
        // Already shutting down?
×
UNCOV
135
        if atomic.AddInt32(&n.stopped, 1) != 1 {
×
136
                return nil
×
137
        }
×
138

UNCOV
139
        chainntnfs.Log.Info("neutrino notifier shutting down...")
×
UNCOV
140
        defer chainntnfs.Log.Debug("neutrino notifier shutdown complete")
×
UNCOV
141

×
UNCOV
142
        close(n.quit)
×
UNCOV
143
        n.wg.Wait()
×
UNCOV
144

×
UNCOV
145
        n.txUpdates.Stop()
×
UNCOV
146

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

×
UNCOV
153
                close(epochClient.epochChan)
×
UNCOV
154
        }
×
155

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

UNCOV
162
        return nil
×
163
}
164

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

UNCOV
170
func (n *NeutrinoNotifier) startNotifier() error {
×
UNCOV
171
        chainntnfs.Log.Infof("neutrino notifier starting...")
×
UNCOV
172

×
UNCOV
173
        // Start our concurrent queues before starting the rescan, to ensure
×
UNCOV
174
        // onFilteredBlockConnected and onRelavantTx callbacks won't be
×
UNCOV
175
        // blocked.
×
UNCOV
176
        n.txUpdates.Start()
×
UNCOV
177

×
UNCOV
178
        // First, we'll obtain the latest block height of the p2p node. We'll
×
UNCOV
179
        // start the auto-rescan from this point. Once a caller actually wishes
×
UNCOV
180
        // to register a chain view, the rescan state will be rewound
×
UNCOV
181
        // accordingly.
×
UNCOV
182
        startingPoint, err := n.p2pNode.BestBlock()
×
UNCOV
183
        if err != nil {
×
184
                n.txUpdates.Stop()
×
185
                return err
×
186
        }
×
UNCOV
187
        startingHeader, err := n.p2pNode.GetBlockHeader(
×
UNCOV
188
                &startingPoint.Hash,
×
UNCOV
189
        )
×
UNCOV
190
        if err != nil {
×
191
                n.txUpdates.Stop()
×
192
                return err
×
193
        }
×
194

UNCOV
195
        n.bestBlock.Hash = &startingPoint.Hash
×
UNCOV
196
        n.bestBlock.Height = startingPoint.Height
×
UNCOV
197
        n.bestBlock.BlockHeader = startingHeader
×
UNCOV
198

×
UNCOV
199
        n.txNotifier = chainntnfs.NewTxNotifier(
×
UNCOV
200
                uint32(n.bestBlock.Height), chainntnfs.ReorgSafetyLimit,
×
UNCOV
201
                n.confirmHintCache, n.spendHintCache,
×
UNCOV
202
        )
×
UNCOV
203

×
UNCOV
204
        // Next, we'll create our set of rescan options. Currently it's
×
UNCOV
205
        // required that a user MUST set an addr/outpoint/txid when creating a
×
UNCOV
206
        // rescan. To get around this, we'll add a "zero" outpoint, that won't
×
UNCOV
207
        // actually be matched.
×
UNCOV
208
        var zeroInput neutrino.InputWithScript
×
UNCOV
209
        rescanOptions := []neutrino.RescanOption{
×
UNCOV
210
                neutrino.StartBlock(startingPoint),
×
UNCOV
211
                neutrino.QuitChan(n.quit),
×
UNCOV
212
                neutrino.NotificationHandlers(
×
UNCOV
213
                        rpcclient.NotificationHandlers{
×
UNCOV
214
                                OnFilteredBlockConnected:    n.onFilteredBlockConnected,
×
UNCOV
215
                                OnFilteredBlockDisconnected: n.onFilteredBlockDisconnected,
×
UNCOV
216
                                OnRedeemingTx:               n.onRelevantTx,
×
UNCOV
217
                        },
×
UNCOV
218
                ),
×
UNCOV
219
                neutrino.WatchInputs(zeroInput),
×
UNCOV
220
        }
×
UNCOV
221

×
UNCOV
222
        // Finally, we'll create our rescan struct, start it, and launch all
×
UNCOV
223
        // the goroutines we need to operate this ChainNotifier instance.
×
UNCOV
224
        n.chainView = neutrino.NewRescan(
×
UNCOV
225
                &neutrino.RescanChainSource{
×
UNCOV
226
                        ChainService: n.p2pNode,
×
UNCOV
227
                },
×
UNCOV
228
                rescanOptions...,
×
UNCOV
229
        )
×
UNCOV
230
        n.rescanErr = n.chainView.Start()
×
UNCOV
231

×
UNCOV
232
        n.wg.Add(1)
×
UNCOV
233
        go n.notificationDispatcher()
×
UNCOV
234

×
UNCOV
235
        // Set the active flag now that we've completed the full
×
UNCOV
236
        // startup.
×
UNCOV
237
        atomic.StoreInt32(&n.active, 1)
×
UNCOV
238

×
UNCOV
239
        chainntnfs.Log.Debugf("neutrino notifier started")
×
UNCOV
240

×
UNCOV
241
        return nil
×
242
}
243

244
// filteredBlock represents a new block which has been connected to the main
245
// chain. The slice of transactions will only be populated if the block
246
// includes a transaction that confirmed one of our watched txids, or spends
247
// one of the outputs currently being watched.
248
type filteredBlock struct {
249
        header *wire.BlockHeader
250
        hash   chainhash.Hash
251
        height uint32
252
        txns   []*btcutil.Tx
253

254
        // connected is true if this update is a new block and false if it is a
255
        // disconnected block.
256
        connect bool
257
}
258

259
// rescanFilterUpdate represents a request that will be sent to the
260
// notificaionRegistry in order to prevent race conditions between the filter
261
// update and new block notifications.
262
type rescanFilterUpdate struct {
263
        updateOptions []neutrino.UpdateOption
264
        errChan       chan error
265
}
266

267
// onFilteredBlockConnected is a callback which is executed each a new block is
268
// connected to the end of the main chain.
269
func (n *NeutrinoNotifier) onFilteredBlockConnected(height int32,
UNCOV
270
        header *wire.BlockHeader, txns []*btcutil.Tx) {
×
UNCOV
271

×
UNCOV
272
        // Append this new chain update to the end of the queue of new chain
×
UNCOV
273
        // updates.
×
UNCOV
274
        select {
×
275
        case n.chainUpdates <- &filteredBlock{
276
                hash:    header.BlockHash(),
277
                height:  uint32(height),
278
                txns:    txns,
279
                header:  header,
280
                connect: true,
UNCOV
281
        }:
×
282
        case <-n.quit:
×
283
        }
284
}
285

286
// onFilteredBlockDisconnected is a callback which is executed each time a new
287
// block has been disconnected from the end of the mainchain due to a re-org.
288
func (n *NeutrinoNotifier) onFilteredBlockDisconnected(height int32,
UNCOV
289
        header *wire.BlockHeader) {
×
UNCOV
290

×
UNCOV
291
        // Append this new chain update to the end of the queue of new chain
×
UNCOV
292
        // disconnects.
×
UNCOV
293
        select {
×
294
        case n.chainUpdates <- &filteredBlock{
295
                hash:    header.BlockHash(),
296
                height:  uint32(height),
297
                connect: false,
UNCOV
298
        }:
×
299
        case <-n.quit:
×
300
        }
301
}
302

303
// relevantTx represents a relevant transaction to the notifier that fulfills
304
// any outstanding spend requests.
305
type relevantTx struct {
306
        tx      *btcutil.Tx
307
        details *btcjson.BlockDetails
308
}
309

310
// onRelevantTx is a callback that proxies relevant transaction notifications
311
// from the backend to the notifier's main event handler.
UNCOV
312
func (n *NeutrinoNotifier) onRelevantTx(tx *btcutil.Tx, details *btcjson.BlockDetails) {
×
UNCOV
313
        select {
×
UNCOV
314
        case n.txUpdates.ChanIn() <- &relevantTx{tx, details}:
×
315
        case <-n.quit:
×
316
        }
317
}
318

319
// connectFilteredBlock is called when we receive a filteredBlock from the
320
// backend. If the block is ahead of what we're expecting, we'll attempt to
321
// catch up and then process the block.
UNCOV
322
func (n *NeutrinoNotifier) connectFilteredBlock(update *filteredBlock) {
×
UNCOV
323
        n.bestBlockMtx.Lock()
×
UNCOV
324
        defer n.bestBlockMtx.Unlock()
×
UNCOV
325

×
UNCOV
326
        if update.height != uint32(n.bestBlock.Height+1) {
×
UNCOV
327
                chainntnfs.Log.Infof("Missed blocks, attempting to catch up")
×
UNCOV
328

×
UNCOV
329
                _, missedBlocks, err := chainntnfs.HandleMissedBlocks(
×
UNCOV
330
                        n.chainConn, n.txNotifier, n.bestBlock,
×
UNCOV
331
                        int32(update.height), false,
×
UNCOV
332
                )
×
UNCOV
333
                if err != nil {
×
UNCOV
334
                        chainntnfs.Log.Error(err)
×
UNCOV
335
                        return
×
UNCOV
336
                }
×
337

UNCOV
338
                for _, block := range missedBlocks {
×
UNCOV
339
                        filteredBlock, err := n.getFilteredBlock(block)
×
UNCOV
340
                        if err != nil {
×
341
                                chainntnfs.Log.Error(err)
×
342
                                return
×
343
                        }
×
UNCOV
344
                        err = n.handleBlockConnected(filteredBlock)
×
UNCOV
345
                        if err != nil {
×
346
                                chainntnfs.Log.Error(err)
×
347
                                return
×
348
                        }
×
349
                }
350
        }
351

UNCOV
352
        err := n.handleBlockConnected(update)
×
UNCOV
353
        if err != nil {
×
354
                chainntnfs.Log.Error(err)
×
355
        }
×
356
}
357

358
// disconnectFilteredBlock is called when our disconnected filtered block
359
// callback is fired. It attempts to rewind the chain to before the
360
// disconnection and updates our best block.
UNCOV
361
func (n *NeutrinoNotifier) disconnectFilteredBlock(update *filteredBlock) {
×
UNCOV
362
        n.bestBlockMtx.Lock()
×
UNCOV
363
        defer n.bestBlockMtx.Unlock()
×
UNCOV
364

×
UNCOV
365
        if update.height != uint32(n.bestBlock.Height) {
×
366
                chainntnfs.Log.Infof("Missed disconnected blocks, attempting" +
×
367
                        " to catch up")
×
368
        }
×
UNCOV
369
        newBestBlock, err := chainntnfs.RewindChain(n.chainConn, n.txNotifier,
×
UNCOV
370
                n.bestBlock, int32(update.height-1),
×
UNCOV
371
        )
×
UNCOV
372
        if err != nil {
×
373
                chainntnfs.Log.Errorf("Unable to rewind chain from height %d"+
×
374
                        "to height %d: %v", n.bestBlock.Height,
×
375
                        update.height-1, err,
×
376
                )
×
377
        }
×
378

UNCOV
379
        n.bestBlock = newBestBlock
×
380
}
381

382
// drainChainUpdates is called after updating the filter. It reads every
383
// buffered item off the chan and returns when no more are available. It is
384
// used to ensure that callers performing a historical scan properly update
385
// their EndHeight to scan blocks that did not have the filter applied at
386
// processing time. Without this, a race condition exists that could allow a
387
// spend or confirmation notification to be missed. It is unlikely this would
388
// occur in a real-world scenario, and instead would manifest itself in tests.
UNCOV
389
func (n *NeutrinoNotifier) drainChainUpdates() {
×
UNCOV
390
        for {
×
UNCOV
391
                select {
×
UNCOV
392
                case update := <-n.chainUpdates:
×
UNCOV
393
                        if update.connect {
×
UNCOV
394
                                n.connectFilteredBlock(update)
×
UNCOV
395
                                break
×
396
                        }
397
                        n.disconnectFilteredBlock(update)
×
UNCOV
398
                default:
×
UNCOV
399
                        return
×
400
                }
401
        }
402
}
403

404
// notificationDispatcher is the primary goroutine which handles client
405
// notification registrations, as well as notification dispatches.
UNCOV
406
func (n *NeutrinoNotifier) notificationDispatcher() {
×
UNCOV
407
        defer n.wg.Done()
×
UNCOV
408

×
UNCOV
409
        for {
×
UNCOV
410
                select {
×
UNCOV
411
                case cancelMsg := <-n.notificationCancels:
×
UNCOV
412
                        switch msg := cancelMsg.(type) {
×
UNCOV
413
                        case *epochCancel:
×
UNCOV
414
                                chainntnfs.Log.Infof("Cancelling epoch "+
×
UNCOV
415
                                        "notification, epoch_id=%v", msg.epochID)
×
UNCOV
416

×
UNCOV
417
                                // First, we'll lookup the original
×
UNCOV
418
                                // registration in order to stop the active
×
UNCOV
419
                                // queue goroutine.
×
UNCOV
420
                                reg := n.blockEpochClients[msg.epochID]
×
UNCOV
421
                                reg.epochQueue.Stop()
×
UNCOV
422

×
UNCOV
423
                                // Next, close the cancel channel for this
×
UNCOV
424
                                // specific client, and wait for the client to
×
UNCOV
425
                                // exit.
×
UNCOV
426
                                close(n.blockEpochClients[msg.epochID].cancelChan)
×
UNCOV
427
                                n.blockEpochClients[msg.epochID].wg.Wait()
×
UNCOV
428

×
UNCOV
429
                                // Once the client has exited, we can then
×
UNCOV
430
                                // safely close the channel used to send epoch
×
UNCOV
431
                                // notifications, in order to notify any
×
UNCOV
432
                                // listeners that the intent has been
×
UNCOV
433
                                // canceled.
×
UNCOV
434
                                close(n.blockEpochClients[msg.epochID].epochChan)
×
UNCOV
435
                                delete(n.blockEpochClients, msg.epochID)
×
436
                        }
437

UNCOV
438
                case registerMsg := <-n.notificationRegistry:
×
UNCOV
439
                        switch msg := registerMsg.(type) {
×
UNCOV
440
                        case *chainntnfs.HistoricalConfDispatch:
×
UNCOV
441
                                // We'll start a historical rescan chain of the
×
UNCOV
442
                                // chain asynchronously to prevent blocking
×
UNCOV
443
                                // potentially long rescans.
×
UNCOV
444
                                n.wg.Add(1)
×
UNCOV
445

×
UNCOV
446
                                //nolint:ll
×
UNCOV
447
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
×
UNCOV
448
                                        defer n.wg.Done()
×
UNCOV
449

×
UNCOV
450
                                        confDetails, err := n.historicalConfDetails(
×
UNCOV
451
                                                msg.ConfRequest,
×
UNCOV
452
                                                msg.StartHeight, msg.EndHeight,
×
UNCOV
453
                                        )
×
UNCOV
454
                                        if err != nil {
×
455
                                                chainntnfs.Log.Error(err)
×
456
                                                return
×
457
                                        }
×
458

459
                                        // If the historical dispatch finished
460
                                        // without error, we will invoke
461
                                        // UpdateConfDetails even if none were
462
                                        // found. This allows the notifier to
463
                                        // begin safely updating the height hint
464
                                        // cache at tip, since any pending
465
                                        // rescans have now completed.
UNCOV
466
                                        err = n.txNotifier.UpdateConfDetails(
×
UNCOV
467
                                                msg.ConfRequest, confDetails,
×
UNCOV
468
                                        )
×
UNCOV
469
                                        if err != nil {
×
470
                                                chainntnfs.Log.Error(err)
×
471
                                        }
×
472
                                }(msg)
473

UNCOV
474
                        case *blockEpochRegistration:
×
UNCOV
475
                                chainntnfs.Log.Infof("New block epoch subscription")
×
UNCOV
476

×
UNCOV
477
                                n.blockEpochClients[msg.epochID] = msg
×
UNCOV
478

×
UNCOV
479
                                // If the client did not provide their best
×
UNCOV
480
                                // known block, then we'll immediately dispatch
×
UNCOV
481
                                // a notification for the current tip.
×
UNCOV
482
                                if msg.bestBlock == nil {
×
UNCOV
483
                                        n.notifyBlockEpochClient(
×
UNCOV
484
                                                msg, n.bestBlock.Height,
×
UNCOV
485
                                                n.bestBlock.Hash,
×
UNCOV
486
                                                n.bestBlock.BlockHeader,
×
UNCOV
487
                                        )
×
UNCOV
488

×
UNCOV
489
                                        msg.errorChan <- nil
×
UNCOV
490
                                        continue
×
491
                                }
492

493
                                // Otherwise, we'll attempt to deliver the
494
                                // backlog of notifications from their best
495
                                // known block.
UNCOV
496
                                n.bestBlockMtx.Lock()
×
UNCOV
497
                                bestHeight := n.bestBlock.Height
×
UNCOV
498
                                n.bestBlockMtx.Unlock()
×
UNCOV
499

×
UNCOV
500
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
×
UNCOV
501
                                        n.chainConn, msg.bestBlock, bestHeight,
×
UNCOV
502
                                        false,
×
UNCOV
503
                                )
×
UNCOV
504
                                if err != nil {
×
505
                                        msg.errorChan <- err
×
506
                                        continue
×
507
                                }
508

UNCOV
509
                                for _, block := range missedBlocks {
×
UNCOV
510
                                        n.notifyBlockEpochClient(
×
UNCOV
511
                                                msg, block.Height, block.Hash,
×
UNCOV
512
                                                block.BlockHeader,
×
UNCOV
513
                                        )
×
UNCOV
514
                                }
×
515

UNCOV
516
                                msg.errorChan <- nil
×
517

UNCOV
518
                        case *rescanFilterUpdate:
×
UNCOV
519
                                err := n.chainView.Update(msg.updateOptions...)
×
UNCOV
520
                                if err != nil {
×
521
                                        chainntnfs.Log.Errorf("Unable to "+
×
522
                                                "update rescan filter: %v", err)
×
523
                                }
×
524

525
                                // Drain the chainUpdates chan so the caller
526
                                // listening on errChan can be sure that
527
                                // updates after receiving the error will have
528
                                // the filter applied. This allows the caller
529
                                // to update their EndHeight if they're
530
                                // performing a historical scan.
UNCOV
531
                                n.drainChainUpdates()
×
UNCOV
532

×
UNCOV
533
                                // After draining, send the error to the
×
UNCOV
534
                                // caller.
×
UNCOV
535
                                msg.errChan <- err
×
536
                        }
537

UNCOV
538
                case item := <-n.chainUpdates:
×
UNCOV
539
                        update := item
×
UNCOV
540
                        if update.connect {
×
UNCOV
541
                                n.connectFilteredBlock(update)
×
UNCOV
542
                                continue
×
543
                        }
544

UNCOV
545
                        n.disconnectFilteredBlock(update)
×
546

UNCOV
547
                case txUpdate := <-n.txUpdates.ChanOut():
×
UNCOV
548
                        // A new relevant transaction notification has been
×
UNCOV
549
                        // received from the backend. We'll attempt to process
×
UNCOV
550
                        // it to determine if it fulfills any outstanding
×
UNCOV
551
                        // confirmation and/or spend requests and dispatch
×
UNCOV
552
                        // notifications for them.
×
UNCOV
553
                        update := txUpdate.(*relevantTx)
×
UNCOV
554
                        err := n.txNotifier.ProcessRelevantSpendTx(
×
UNCOV
555
                                update.tx, uint32(update.details.Height),
×
UNCOV
556
                        )
×
UNCOV
557
                        if err != nil {
×
558
                                chainntnfs.Log.Errorf("Unable to process "+
×
559
                                        "transaction %v: %v", update.tx.Hash(),
×
560
                                        err)
×
561
                        }
×
562

563
                case err := <-n.rescanErr:
×
564
                        chainntnfs.Log.Errorf("Error during rescan: %v", err)
×
565

UNCOV
566
                case <-n.quit:
×
UNCOV
567
                        return
×
568

569
                }
570
        }
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 (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
UNCOV
577
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation, error) {
×
UNCOV
578

×
UNCOV
579
        // Starting from the height hint, we'll walk forwards in the chain to
×
UNCOV
580
        // see if this transaction/output script has already been confirmed.
×
UNCOV
581
        for scanHeight := endHeight; scanHeight >= startHeight && scanHeight > 0; scanHeight-- {
×
UNCOV
582
                // Ensure we haven't been requested to shut down before
×
UNCOV
583
                // processing the next height.
×
UNCOV
584
                select {
×
585
                case <-n.quit:
×
586
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
UNCOV
587
                default:
×
588
                }
589

590
                // First, we'll fetch the block header for this height so we
591
                // can compute the current block hash.
UNCOV
592
                blockHash, err := n.p2pNode.GetBlockHash(int64(scanHeight))
×
UNCOV
593
                if err != nil {
×
594
                        return nil, fmt.Errorf("unable to get header for "+
×
595
                                "height=%v: %w", scanHeight, err)
×
596
                }
×
597

598
                // With the hash computed, we can now fetch the basic filter for this
599
                // height. Since the range of required items is known we avoid
600
                // roundtrips by requesting a batched response and save bandwidth by
601
                // limiting the max number of items per batch. Since neutrino populates
602
                // its underline filters cache with the batch response, the next call
603
                // will execute a network query only once per batch and not on every
604
                // iteration.
UNCOV
605
                regFilter, err := n.p2pNode.GetCFilter(
×
UNCOV
606
                        *blockHash, wire.GCSFilterRegular,
×
UNCOV
607
                        neutrino.NumRetries(5),
×
UNCOV
608
                        neutrino.OptimisticReverseBatch(),
×
UNCOV
609
                        neutrino.MaxBatchSize(int64(scanHeight-startHeight+1)),
×
UNCOV
610
                )
×
UNCOV
611
                if err != nil {
×
612
                        return nil, fmt.Errorf("unable to retrieve regular "+
×
613
                                "filter for height=%v: %w", scanHeight, err)
×
614
                }
×
615

616
                // In the case that the filter exists, we'll attempt to see if
617
                // any element in it matches our target public key script.
UNCOV
618
                key := builder.DeriveKey(blockHash)
×
UNCOV
619
                match, err := regFilter.Match(key, confRequest.PkScript.Script())
×
UNCOV
620
                if err != nil {
×
621
                        return nil, fmt.Errorf("unable to query filter: %w",
×
622
                                err)
×
623
                }
×
624

625
                // If there's no match, then we can continue forward to the
626
                // next block.
UNCOV
627
                if !match {
×
UNCOV
628
                        continue
×
629
                }
630

631
                // In the case that we do have a match, we'll fetch the block
632
                // from the network so we can find the positional data required
633
                // to send the proper response.
UNCOV
634
                block, err := n.GetBlock(*blockHash)
×
UNCOV
635
                if err != nil {
×
636
                        return nil, fmt.Errorf("unable to get block from "+
×
637
                                "network: %w", err)
×
638
                }
×
639

640
                // For every transaction in the block, check which one matches
641
                // our request. If we find one that does, we can dispatch its
642
                // confirmation details.
UNCOV
643
                for i, tx := range block.Transactions() {
×
UNCOV
644
                        if !confRequest.MatchesTx(tx.MsgTx()) {
×
UNCOV
645
                                continue
×
646
                        }
647

UNCOV
648
                        return &chainntnfs.TxConfirmation{
×
UNCOV
649
                                Tx:          tx.MsgTx().Copy(),
×
UNCOV
650
                                BlockHash:   blockHash,
×
UNCOV
651
                                BlockHeight: scanHeight,
×
UNCOV
652
                                TxIndex:     uint32(i),
×
UNCOV
653
                                Block:       block.MsgBlock(),
×
UNCOV
654
                        }, nil
×
655
                }
656
        }
657

UNCOV
658
        return nil, nil
×
659
}
660

661
// handleBlockConnected applies a chain update for a new block. Any watched
662
// transactions included this block will processed to either send notifications
663
// now or after numConfirmations confs.
664
//
665
// NOTE: This method must be called with the bestBlockMtx lock held.
UNCOV
666
func (n *NeutrinoNotifier) handleBlockConnected(newBlock *filteredBlock) error {
×
UNCOV
667
        // We'll extend the txNotifier's height with the information of this
×
UNCOV
668
        // new block, which will handle all of the notification logic for us.
×
UNCOV
669
        //
×
UNCOV
670
        // We actually need the _full_ block here as well in order to be able
×
UNCOV
671
        // to send the full block back up to the client. The neutrino client
×
UNCOV
672
        // itself will only dispatch a block if one of the items we're looking
×
UNCOV
673
        // for matches, so ultimately passing it the full block will still only
×
UNCOV
674
        // result in the items we care about being dispatched.
×
UNCOV
675
        rawBlock, err := n.GetBlock(newBlock.hash)
×
UNCOV
676
        if err != nil {
×
677
                return fmt.Errorf("unable to get full block: %w", err)
×
678
        }
×
UNCOV
679
        err = n.txNotifier.ConnectTip(rawBlock, newBlock.height)
×
UNCOV
680
        if err != nil {
×
681
                return fmt.Errorf("unable to connect tip: %w", err)
×
682
        }
×
683

UNCOV
684
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", newBlock.height,
×
UNCOV
685
                newBlock.hash)
×
UNCOV
686

×
UNCOV
687
        // Now that we've guaranteed the new block extends the txNotifier's
×
UNCOV
688
        // current tip, we'll proceed to dispatch notifications to all of our
×
UNCOV
689
        // registered clients whom have had notifications fulfilled. Before
×
UNCOV
690
        // doing so, we'll make sure update our in memory state in order to
×
UNCOV
691
        // satisfy any client requests based upon the new block.
×
UNCOV
692
        n.bestBlock.Hash = &newBlock.hash
×
UNCOV
693
        n.bestBlock.Height = int32(newBlock.height)
×
UNCOV
694
        n.bestBlock.BlockHeader = newBlock.header
×
UNCOV
695

×
UNCOV
696
        err = n.txNotifier.NotifyHeight(newBlock.height)
×
UNCOV
697
        if err != nil {
×
698
                return fmt.Errorf("unable to notify height: %w", err)
×
699
        }
×
700

UNCOV
701
        n.notifyBlockEpochs(
×
UNCOV
702
                int32(newBlock.height), &newBlock.hash, newBlock.header,
×
UNCOV
703
        )
×
UNCOV
704

×
UNCOV
705
        return nil
×
706
}
707

708
// getFilteredBlock is a utility to retrieve the full filtered block from a block epoch.
UNCOV
709
func (n *NeutrinoNotifier) getFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) {
×
UNCOV
710
        rawBlock, err := n.GetBlock(*epoch.Hash)
×
UNCOV
711
        if err != nil {
×
712
                return nil, fmt.Errorf("unable to get block: %w", err)
×
713
        }
×
714

UNCOV
715
        txns := rawBlock.Transactions()
×
UNCOV
716

×
UNCOV
717
        block := &filteredBlock{
×
UNCOV
718
                hash:    *epoch.Hash,
×
UNCOV
719
                height:  uint32(epoch.Height),
×
UNCOV
720
                header:  &rawBlock.MsgBlock().Header,
×
UNCOV
721
                txns:    txns,
×
UNCOV
722
                connect: true,
×
UNCOV
723
        }
×
UNCOV
724
        return block, nil
×
725
}
726

727
// notifyBlockEpochs notifies all registered block epoch clients of the newly
728
// connected block to the main chain.
729
func (n *NeutrinoNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
UNCOV
730
        blockHeader *wire.BlockHeader) {
×
UNCOV
731

×
UNCOV
732
        for _, client := range n.blockEpochClients {
×
UNCOV
733
                n.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
×
UNCOV
734
        }
×
735
}
736

737
// notifyBlockEpochClient sends a registered block epoch client a notification
738
// about a specific block.
739
func (n *NeutrinoNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
UNCOV
740
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
×
UNCOV
741

×
UNCOV
742
        epoch := &chainntnfs.BlockEpoch{
×
UNCOV
743
                Height:      height,
×
UNCOV
744
                Hash:        sha,
×
UNCOV
745
                BlockHeader: blockHeader,
×
UNCOV
746
        }
×
UNCOV
747

×
UNCOV
748
        select {
×
UNCOV
749
        case epochClient.epochQueue.ChanIn() <- epoch:
×
750
        case <-epochClient.cancelChan:
×
751
        case <-n.quit:
×
752
        }
753
}
754

755
// RegisterSpendNtfn registers an intent to be notified once the target
756
// outpoint/output script has been spent by a transaction on-chain. When
757
// intending to be notified of the spend of an output script, a nil outpoint
758
// must be used. The heightHint should represent the earliest height in the
759
// chain of the transaction that spent the outpoint/output script.
760
//
761
// Once a spend of has been detected, the details of the spending event will be
762
// sent across the 'Spend' channel.
763
func (n *NeutrinoNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
UNCOV
764
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
×
UNCOV
765

×
UNCOV
766
        // Register the conf notification with the TxNotifier. A non-nil value
×
UNCOV
767
        // for `dispatch` will be returned if we are required to perform a
×
UNCOV
768
        // manual scan for the confirmation. Otherwise the notifier will begin
×
UNCOV
769
        // watching at tip for the transaction to confirm.
×
UNCOV
770
        ntfn, err := n.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
×
UNCOV
771
        if err != nil {
×
UNCOV
772
                return nil, err
×
UNCOV
773
        }
×
774

775
        // To determine whether this outpoint has been spent on-chain, we'll
776
        // update our filter to watch for the transaction at tip and we'll also
777
        // dispatch a historical rescan to determine if it has been spent in the
778
        // past.
779
        //
780
        // We'll update our filter first to ensure we can immediately detect the
781
        // spend at tip.
UNCOV
782
        if outpoint == nil {
×
UNCOV
783
                outpoint = &chainntnfs.ZeroOutPoint
×
UNCOV
784
        }
×
UNCOV
785
        inputToWatch := neutrino.InputWithScript{
×
UNCOV
786
                OutPoint: *outpoint,
×
UNCOV
787
                PkScript: pkScript,
×
UNCOV
788
        }
×
UNCOV
789
        updateOptions := []neutrino.UpdateOption{
×
UNCOV
790
                neutrino.AddInputs(inputToWatch),
×
UNCOV
791
                neutrino.DisableDisconnectedNtfns(true),
×
UNCOV
792
        }
×
UNCOV
793

×
UNCOV
794
        // We'll use the txNotifier's tip as the starting point of our filter
×
UNCOV
795
        // update. In the case of an output script spend request, we'll check if
×
UNCOV
796
        // we should perform a historical rescan and start from there, as we
×
UNCOV
797
        // cannot do so with GetUtxo since it matches outpoints.
×
UNCOV
798
        rewindHeight := ntfn.Height
×
UNCOV
799
        if ntfn.HistoricalDispatch != nil && *outpoint == chainntnfs.ZeroOutPoint {
×
UNCOV
800
                rewindHeight = ntfn.HistoricalDispatch.StartHeight
×
UNCOV
801
        }
×
UNCOV
802
        updateOptions = append(updateOptions, neutrino.Rewind(rewindHeight))
×
UNCOV
803

×
UNCOV
804
        errChan := make(chan error, 1)
×
UNCOV
805
        select {
×
806
        case n.notificationRegistry <- &rescanFilterUpdate{
807
                updateOptions: updateOptions,
808
                errChan:       errChan,
UNCOV
809
        }:
×
810
        case <-n.quit:
×
811
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
812
        }
813

UNCOV
814
        select {
×
UNCOV
815
        case err = <-errChan:
×
816
        case <-n.quit:
×
817
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
818
        }
UNCOV
819
        if err != nil {
×
820
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
821
        }
×
822

823
        // If the txNotifier didn't return any details to perform a historical
824
        // scan of the chain, or if we already performed one like in the case of
825
        // output script spend requests, then we can return early as there's
826
        // nothing left for us to do.
UNCOV
827
        if ntfn.HistoricalDispatch == nil || *outpoint == chainntnfs.ZeroOutPoint {
×
UNCOV
828
                return ntfn.Event, nil
×
UNCOV
829
        }
×
830

831
        // Grab the current best height as the height may have been updated
832
        // while we were draining the chainUpdates queue.
UNCOV
833
        n.bestBlockMtx.RLock()
×
UNCOV
834
        currentHeight := uint32(n.bestBlock.Height)
×
UNCOV
835
        n.bestBlockMtx.RUnlock()
×
UNCOV
836

×
UNCOV
837
        ntfn.HistoricalDispatch.EndHeight = currentHeight
×
UNCOV
838

×
UNCOV
839
        // With the filter updated, we'll dispatch our historical rescan to
×
UNCOV
840
        // ensure we detect the spend if it happened in the past.
×
UNCOV
841
        n.wg.Add(1)
×
UNCOV
842
        go func() {
×
UNCOV
843
                defer n.wg.Done()
×
UNCOV
844

×
UNCOV
845
                // We'll ensure that neutrino is caught up to the starting
×
UNCOV
846
                // height before we attempt to fetch the UTXO from the chain.
×
UNCOV
847
                // If we're behind, then we may miss a notification dispatch.
×
UNCOV
848
                for {
×
UNCOV
849
                        n.bestBlockMtx.RLock()
×
UNCOV
850
                        currentHeight := uint32(n.bestBlock.Height)
×
UNCOV
851
                        n.bestBlockMtx.RUnlock()
×
UNCOV
852

×
UNCOV
853
                        if currentHeight >= ntfn.HistoricalDispatch.StartHeight {
×
UNCOV
854
                                break
×
855
                        }
856

857
                        select {
×
858
                        case <-time.After(time.Millisecond * 200):
×
859
                        case <-n.quit:
×
860
                                return
×
861
                        }
862
                }
863

UNCOV
864
                spendReport, err := n.p2pNode.GetUtxo(
×
UNCOV
865
                        neutrino.WatchInputs(inputToWatch),
×
UNCOV
866
                        neutrino.StartBlock(&headerfs.BlockStamp{
×
UNCOV
867
                                Height: int32(ntfn.HistoricalDispatch.StartHeight),
×
UNCOV
868
                        }),
×
UNCOV
869
                        neutrino.EndBlock(&headerfs.BlockStamp{
×
UNCOV
870
                                Height: int32(ntfn.HistoricalDispatch.EndHeight),
×
UNCOV
871
                        }),
×
UNCOV
872
                        neutrino.ProgressHandler(func(processedHeight uint32) {
×
UNCOV
873
                                // We persist the rescan progress to achieve incremental
×
UNCOV
874
                                // behavior across restarts, otherwise long rescans may
×
UNCOV
875
                                // start from the beginning with every restart.
×
UNCOV
876
                                err := n.spendHintCache.CommitSpendHint(
×
UNCOV
877
                                        processedHeight,
×
UNCOV
878
                                        ntfn.HistoricalDispatch.SpendRequest)
×
UNCOV
879
                                if err != nil {
×
880
                                        chainntnfs.Log.Errorf("Failed to update rescan "+
×
881
                                                "progress: %v", err)
×
882
                                }
×
883
                        }),
884
                        neutrino.QuitChan(n.quit),
885
                )
UNCOV
886
                if err != nil && !strings.Contains(err.Error(), "not found") {
×
UNCOV
887
                        chainntnfs.Log.Errorf("Failed getting UTXO: %v", err)
×
UNCOV
888
                        return
×
UNCOV
889
                }
×
890

891
                // If a spend report was returned, and the transaction is present, then
892
                // this means that the output is already spent.
UNCOV
893
                var spendDetails *chainntnfs.SpendDetail
×
UNCOV
894
                if spendReport != nil && spendReport.SpendingTx != nil {
×
UNCOV
895
                        spendingTxHash := spendReport.SpendingTx.TxHash()
×
UNCOV
896
                        spendDetails = &chainntnfs.SpendDetail{
×
UNCOV
897
                                SpentOutPoint:     outpoint,
×
UNCOV
898
                                SpenderTxHash:     &spendingTxHash,
×
UNCOV
899
                                SpendingTx:        spendReport.SpendingTx,
×
UNCOV
900
                                SpenderInputIndex: spendReport.SpendingInputIndex,
×
UNCOV
901
                                SpendingHeight:    int32(spendReport.SpendingTxHeight),
×
UNCOV
902
                        }
×
UNCOV
903
                }
×
904

905
                // Finally, no matter whether the rescan found a spend in the past or
906
                // not, we'll mark our historical rescan as complete to ensure the
907
                // outpoint's spend hint gets updated upon connected/disconnected
908
                // blocks.
UNCOV
909
                err = n.txNotifier.UpdateSpendDetails(
×
UNCOV
910
                        ntfn.HistoricalDispatch.SpendRequest, spendDetails,
×
UNCOV
911
                )
×
UNCOV
912
                if err != nil {
×
913
                        chainntnfs.Log.Errorf("Failed to update spend details: %v", err)
×
914
                        return
×
915
                }
×
916
        }()
917

UNCOV
918
        return ntfn.Event, nil
×
919
}
920

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

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

945
        // To determine whether this transaction has confirmed on-chain, we'll
946
        // update our filter to watch for the transaction at tip and we'll also
947
        // dispatch a historical rescan to determine if it has confirmed in the
948
        // past.
949
        //
950
        // We'll update our filter first to ensure we can immediately detect the
951
        // confirmation at tip. To do so, we'll map the script into an address
952
        // type so we can instruct neutrino to match if the transaction
953
        // containing the script is found in a block.
UNCOV
954
        params := n.p2pNode.ChainParams()
×
UNCOV
955
        _, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, &params)
×
UNCOV
956
        if err != nil {
×
957
                return nil, fmt.Errorf("unable to extract script: %w", err)
×
958
        }
×
959

960
        // We'll send the filter update request to the notifier's main event
961
        // handler and wait for its response.
UNCOV
962
        errChan := make(chan error, 1)
×
UNCOV
963
        select {
×
964
        case n.notificationRegistry <- &rescanFilterUpdate{
965
                updateOptions: []neutrino.UpdateOption{
966
                        neutrino.AddAddrs(addrs...),
967
                        neutrino.Rewind(ntfn.Height),
968
                        neutrino.DisableDisconnectedNtfns(true),
969
                },
970
                errChan: errChan,
UNCOV
971
        }:
×
972
        case <-n.quit:
×
973
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
974
        }
975

UNCOV
976
        select {
×
UNCOV
977
        case err = <-errChan:
×
978
        case <-n.quit:
×
979
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
980
        }
UNCOV
981
        if err != nil {
×
982
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
983
        }
×
984

985
        // If a historical rescan was not requested by the txNotifier, then we
986
        // can return to the caller.
UNCOV
987
        if ntfn.HistoricalDispatch == nil {
×
UNCOV
988
                return ntfn.Event, nil
×
UNCOV
989
        }
×
990

991
        // Grab the current best height as the height may have been updated
992
        // while we were draining the chainUpdates queue.
UNCOV
993
        n.bestBlockMtx.RLock()
×
UNCOV
994
        currentHeight := uint32(n.bestBlock.Height)
×
UNCOV
995
        n.bestBlockMtx.RUnlock()
×
UNCOV
996

×
UNCOV
997
        ntfn.HistoricalDispatch.EndHeight = currentHeight
×
UNCOV
998

×
UNCOV
999
        // Finally, with the filter updated, we can dispatch the historical
×
UNCOV
1000
        // rescan to ensure we can detect if the event happened in the past.
×
UNCOV
1001
        select {
×
UNCOV
1002
        case n.notificationRegistry <- ntfn.HistoricalDispatch:
×
1003
        case <-n.quit:
×
1004
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1005
        }
1006

UNCOV
1007
        return ntfn.Event, nil
×
1008
}
1009

1010
// GetBlock is used to retrieve the block with the given hash. Since the block
1011
// cache used by neutrino will be the same as that used by LND (since it is
1012
// passed to neutrino on initialisation), the neutrino GetBlock method can be
1013
// called directly since it already uses the block cache. However, neutrino
1014
// does not lock the block cache mutex for the given block hash and so that is
1015
// done here.
1016
func (n *NeutrinoNotifier) GetBlock(hash chainhash.Hash) (
UNCOV
1017
        *btcutil.Block, error) {
×
UNCOV
1018

×
UNCOV
1019
        n.blockCache.HashMutex.Lock(lntypes.Hash(hash))
×
UNCOV
1020
        defer n.blockCache.HashMutex.Unlock(lntypes.Hash(hash))
×
UNCOV
1021

×
UNCOV
1022
        return n.p2pNode.GetBlock(hash)
×
UNCOV
1023
}
×
1024

1025
// blockEpochRegistration represents a client's intent to receive a
1026
// notification with each newly connected block.
1027
type blockEpochRegistration struct {
1028
        epochID uint64
1029

1030
        epochChan chan *chainntnfs.BlockEpoch
1031

1032
        epochQueue *queue.ConcurrentQueue
1033

1034
        cancelChan chan struct{}
1035

1036
        bestBlock *chainntnfs.BlockEpoch
1037

1038
        errorChan chan error
1039

1040
        wg sync.WaitGroup
1041
}
1042

1043
// epochCancel is a message sent to the NeutrinoNotifier when a client wishes
1044
// to cancel an outstanding epoch notification that has yet to be dispatched.
1045
type epochCancel struct {
1046
        epochID uint64
1047
}
1048

1049
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1050
// caller to receive notifications, of each new block connected to the main
1051
// chain. Clients have the option of passing in their best known block, which
1052
// the notifier uses to check if they are behind on blocks and catch them up. If
1053
// they do not provide one, then a notification will be dispatched immediately
1054
// for the current tip of the chain upon a successful registration.
1055
func (n *NeutrinoNotifier) RegisterBlockEpochNtfn(
UNCOV
1056
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
×
UNCOV
1057

×
UNCOV
1058
        reg := &blockEpochRegistration{
×
UNCOV
1059
                epochQueue: queue.NewConcurrentQueue(20),
×
UNCOV
1060
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
×
UNCOV
1061
                cancelChan: make(chan struct{}),
×
UNCOV
1062
                epochID:    atomic.AddUint64(&n.epochClientCounter, 1),
×
UNCOV
1063
                bestBlock:  bestBlock,
×
UNCOV
1064
                errorChan:  make(chan error, 1),
×
UNCOV
1065
        }
×
UNCOV
1066
        reg.epochQueue.Start()
×
UNCOV
1067

×
UNCOV
1068
        // Before we send the request to the main goroutine, we'll launch a new
×
UNCOV
1069
        // goroutine to proxy items added to our queue to the client itself.
×
UNCOV
1070
        // This ensures that all notifications are received *in order*.
×
UNCOV
1071
        reg.wg.Add(1)
×
UNCOV
1072
        go func() {
×
UNCOV
1073
                defer reg.wg.Done()
×
UNCOV
1074

×
UNCOV
1075
                for {
×
UNCOV
1076
                        select {
×
UNCOV
1077
                        case ntfn := <-reg.epochQueue.ChanOut():
×
UNCOV
1078
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
×
UNCOV
1079
                                select {
×
UNCOV
1080
                                case reg.epochChan <- blockNtfn:
×
1081

UNCOV
1082
                                case <-reg.cancelChan:
×
UNCOV
1083
                                        return
×
1084

UNCOV
1085
                                case <-n.quit:
×
UNCOV
1086
                                        return
×
1087
                                }
1088

UNCOV
1089
                        case <-reg.cancelChan:
×
UNCOV
1090
                                return
×
1091

UNCOV
1092
                        case <-n.quit:
×
UNCOV
1093
                                return
×
1094
                        }
1095
                }
1096
        }()
1097

UNCOV
1098
        select {
×
1099
        case <-n.quit:
×
1100
                // As we're exiting before the registration could be sent,
×
1101
                // we'll stop the queue now ourselves.
×
1102
                reg.epochQueue.Stop()
×
1103

×
1104
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1105
                        "attempting to register for block epoch notification.")
×
UNCOV
1106
        case n.notificationRegistry <- reg:
×
UNCOV
1107
                return &chainntnfs.BlockEpochEvent{
×
UNCOV
1108
                        Epochs: reg.epochChan,
×
UNCOV
1109
                        Cancel: func() {
×
UNCOV
1110
                                cancel := &epochCancel{
×
UNCOV
1111
                                        epochID: reg.epochID,
×
UNCOV
1112
                                }
×
UNCOV
1113

×
UNCOV
1114
                                // Submit epoch cancellation to notification dispatcher.
×
UNCOV
1115
                                select {
×
UNCOV
1116
                                case n.notificationCancels <- cancel:
×
UNCOV
1117
                                        // Cancellation is being handled, drain the epoch channel until it is
×
UNCOV
1118
                                        // closed before yielding to caller.
×
UNCOV
1119
                                        for {
×
UNCOV
1120
                                                select {
×
UNCOV
1121
                                                case _, ok := <-reg.epochChan:
×
UNCOV
1122
                                                        if !ok {
×
UNCOV
1123
                                                                return
×
UNCOV
1124
                                                        }
×
1125
                                                case <-n.quit:
×
1126
                                                        return
×
1127
                                                }
1128
                                        }
UNCOV
1129
                                case <-n.quit:
×
1130
                                }
1131
                        },
1132
                }, nil
1133
        }
1134
}
1135

1136
// NeutrinoChainConn is a wrapper around neutrino's chain backend in order
1137
// to satisfy the chainntnfs.ChainConn interface.
1138
type NeutrinoChainConn struct {
1139
        p2pNode *neutrino.ChainService
1140
}
1141

1142
// GetBlockHeader returns the block header for a hash.
UNCOV
1143
func (n *NeutrinoChainConn) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
×
UNCOV
1144
        return n.p2pNode.GetBlockHeader(blockHash)
×
UNCOV
1145
}
×
1146

1147
// GetBlockHeaderVerbose returns a verbose block header result for a hash. This
1148
// result only contains the height with a nil hash.
1149
func (n *NeutrinoChainConn) GetBlockHeaderVerbose(blockHash *chainhash.Hash) (
1150
        *btcjson.GetBlockHeaderVerboseResult, error) {
×
1151

×
1152
        height, err := n.p2pNode.GetBlockHeight(blockHash)
×
1153
        if err != nil {
×
1154
                return nil, err
×
1155
        }
×
1156
        // Since only the height is used from the result, leave the hash nil.
1157
        return &btcjson.GetBlockHeaderVerboseResult{Height: int32(height)}, nil
×
1158
}
1159

1160
// GetBlockHash returns the hash from a block height.
UNCOV
1161
func (n *NeutrinoChainConn) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) {
×
UNCOV
1162
        return n.p2pNode.GetBlockHash(blockHeight)
×
UNCOV
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