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

lightningnetwork / lnd / 10207481183

01 Aug 2024 11:52PM UTC coverage: 58.679% (+0.09%) from 58.591%
10207481183

push

github

web-flow
Merge pull request #8836 from hieblmi/payment-failure-reason-cancel

routing: add payment failure reason `FailureReasonCancel`

7 of 30 new or added lines in 5 files covered. (23.33%)

1662 existing lines in 21 files now uncovered.

125454 of 213798 relevant lines covered (58.68%)

28679.1 hits per line

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

84.57
/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,
96
        blockCache *blockcache.BlockCache) *NeutrinoNotifier {
5✔
97

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

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

5✔
104
                p2pNode:   node,
5✔
105
                chainConn: &NeutrinoChainConn{node},
5✔
106

5✔
107
                rescanErr: make(chan error),
5✔
108

5✔
109
                chainUpdates: make(chan *filteredBlock, 100),
5✔
110

5✔
111
                txUpdates: queue.NewConcurrentQueue(10),
5✔
112

5✔
113
                spendHintCache:   spendHintCache,
5✔
114
                confirmHintCache: confirmHintCache,
5✔
115

5✔
116
                blockCache: blockCache,
5✔
117

5✔
118
                quit: make(chan struct{}),
5✔
119
        }
5✔
120
}
5✔
121

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

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

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

4✔
142
        close(n.quit)
4✔
143
        n.wg.Wait()
4✔
144

4✔
145
        n.txUpdates.Stop()
4✔
146

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

19✔
153
                close(epochClient.epochChan)
19✔
154
        }
19✔
155

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

162
        return nil
4✔
163
}
164

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

170
func (n *NeutrinoNotifier) startNotifier() error {
2✔
171
        // Start our concurrent queues before starting the rescan, to ensure
2✔
172
        // onFilteredBlockConnected and onRelavantTx callbacks won't be
2✔
173
        // blocked.
2✔
174
        n.txUpdates.Start()
2✔
175

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

193
        n.bestBlock.Hash = &startingPoint.Hash
2✔
194
        n.bestBlock.Height = startingPoint.Height
2✔
195
        n.bestBlock.BlockHeader = startingHeader
2✔
196

2✔
197
        n.txNotifier = chainntnfs.NewTxNotifier(
2✔
198
                uint32(n.bestBlock.Height), chainntnfs.ReorgSafetyLimit,
2✔
199
                n.confirmHintCache, n.spendHintCache,
2✔
200
        )
2✔
201

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

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

2✔
230
        n.wg.Add(1)
2✔
231
        go n.notificationDispatcher()
2✔
232

2✔
233
        // Set the active flag now that we've completed the full
2✔
234
        // startup.
2✔
235
        atomic.StoreInt32(&n.active, 1)
2✔
236

2✔
237
        return nil
2✔
238
}
239

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

250
        // connected is true if this update is a new block and false if it is a
251
        // disconnected block.
252
        connect bool
253
}
254

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

263
// onFilteredBlockConnected is a callback which is executed each a new block is
264
// connected to the end of the main chain.
265
func (n *NeutrinoNotifier) onFilteredBlockConnected(height int32,
266
        header *wire.BlockHeader, txns []*btcutil.Tx) {
180✔
267

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

282
// onFilteredBlockDisconnected is a callback which is executed each time a new
283
// block has been disconnected from the end of the mainchain due to a re-org.
284
func (n *NeutrinoNotifier) onFilteredBlockDisconnected(height int32,
285
        header *wire.BlockHeader) {
4✔
286

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

299
// relevantTx represents a relevant transaction to the notifier that fulfills
300
// any outstanding spend requests.
301
type relevantTx struct {
302
        tx      *btcutil.Tx
303
        details *btcjson.BlockDetails
304
}
305

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

315
// connectFilteredBlock is called when we receive a filteredBlock from the
316
// backend. If the block is ahead of what we're expecting, we'll attempt to
317
// catch up and then process the block.
318
func (n *NeutrinoNotifier) connectFilteredBlock(update *filteredBlock) {
159✔
319
        n.bestBlockMtx.Lock()
159✔
320
        defer n.bestBlockMtx.Unlock()
159✔
321

159✔
322
        if update.height != uint32(n.bestBlock.Height+1) {
164✔
323
                chainntnfs.Log.Infof("Missed blocks, attempting to catch up")
5✔
324

5✔
325
                _, missedBlocks, err := chainntnfs.HandleMissedBlocks(
5✔
326
                        n.chainConn, n.txNotifier, n.bestBlock,
5✔
327
                        int32(update.height), false,
5✔
328
                )
5✔
329
                if err != nil {
9✔
330
                        chainntnfs.Log.Error(err)
4✔
331
                        return
4✔
332
                }
4✔
333

334
                for _, block := range missedBlocks {
11✔
335
                        filteredBlock, err := n.getFilteredBlock(block)
10✔
336
                        if err != nil {
10✔
337
                                chainntnfs.Log.Error(err)
×
338
                                return
×
339
                        }
×
340
                        err = n.handleBlockConnected(filteredBlock)
10✔
341
                        if err != nil {
10✔
UNCOV
342
                                chainntnfs.Log.Error(err)
×
UNCOV
343
                                return
×
UNCOV
344
                        }
×
345
                }
346
        }
347

348
        err := n.handleBlockConnected(update)
156✔
349
        if err != nil {
156✔
UNCOV
350
                chainntnfs.Log.Error(err)
×
UNCOV
351
        }
×
352
}
353

354
// disconnectFilteredBlock is called when our disconnected filtered block
355
// callback is fired. It attempts to rewind the chain to before the
356
// disconnection and updates our best block.
357
func (n *NeutrinoNotifier) disconnectFilteredBlock(update *filteredBlock) {
4✔
358
        n.bestBlockMtx.Lock()
4✔
359
        defer n.bestBlockMtx.Unlock()
4✔
360

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

375
        n.bestBlock = newBestBlock
4✔
376
}
377

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

400
// notificationDispatcher is the primary goroutine which handles client
401
// notification registrations, as well as notification dispatches.
402
func (n *NeutrinoNotifier) notificationDispatcher() {
4✔
403
        defer n.wg.Done()
4✔
404

4✔
405
        for {
307✔
406
                select {
303✔
407
                case cancelMsg := <-n.notificationCancels:
2✔
408
                        switch msg := cancelMsg.(type) {
2✔
409
                        case *epochCancel:
2✔
410
                                chainntnfs.Log.Infof("Cancelling epoch "+
2✔
411
                                        "notification, epoch_id=%v", msg.epochID)
2✔
412

2✔
413
                                // First, we'll lookup the original
2✔
414
                                // registration in order to stop the active
2✔
415
                                // queue goroutine.
2✔
416
                                reg := n.blockEpochClients[msg.epochID]
2✔
417
                                reg.epochQueue.Stop()
2✔
418

2✔
419
                                // Next, close the cancel channel for this
2✔
420
                                // specific client, and wait for the client to
2✔
421
                                // exit.
2✔
422
                                close(n.blockEpochClients[msg.epochID].cancelChan)
2✔
423
                                n.blockEpochClients[msg.epochID].wg.Wait()
2✔
424

2✔
425
                                // Once the client has exited, we can then
2✔
426
                                // safely close the channel used to send epoch
2✔
427
                                // notifications, in order to notify any
2✔
428
                                // listeners that the intent has been
2✔
429
                                // canceled.
2✔
430
                                close(n.blockEpochClients[msg.epochID].epochChan)
2✔
431
                                delete(n.blockEpochClients, msg.epochID)
2✔
432
                        }
433

434
                case registerMsg := <-n.notificationRegistry:
127✔
435
                        switch msg := registerMsg.(type) {
127✔
436
                        case *chainntnfs.HistoricalConfDispatch:
34✔
437
                                // We'll start a historical rescan chain of the
34✔
438
                                // chain asynchronously to prevent blocking
34✔
439
                                // potentially long rescans.
34✔
440
                                n.wg.Add(1)
34✔
441

34✔
442
                                //nolint:lll
34✔
443
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
68✔
444
                                        defer n.wg.Done()
34✔
445

34✔
446
                                        confDetails, err := n.historicalConfDetails(
34✔
447
                                                msg.ConfRequest,
34✔
448
                                                msg.StartHeight, msg.EndHeight,
34✔
449
                                        )
34✔
450
                                        if err != nil {
34✔
UNCOV
451
                                                chainntnfs.Log.Error(err)
×
UNCOV
452
                                                return
×
UNCOV
453
                                        }
×
454

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

470
                        case *blockEpochRegistration:
20✔
471
                                chainntnfs.Log.Infof("New block epoch subscription")
20✔
472

20✔
473
                                n.blockEpochClients[msg.epochID] = msg
20✔
474

20✔
475
                                // If the client did not provide their best
20✔
476
                                // known block, then we'll immediately dispatch
20✔
477
                                // a notification for the current tip.
20✔
478
                                if msg.bestBlock == nil {
35✔
479
                                        n.notifyBlockEpochClient(
15✔
480
                                                msg, n.bestBlock.Height,
15✔
481
                                                n.bestBlock.Hash,
15✔
482
                                                n.bestBlock.BlockHeader,
15✔
483
                                        )
15✔
484

15✔
485
                                        msg.errorChan <- nil
15✔
486
                                        continue
15✔
487
                                }
488

489
                                // Otherwise, we'll attempt to deliver the
490
                                // backlog of notifications from their best
491
                                // known block.
492
                                n.bestBlockMtx.Lock()
6✔
493
                                bestHeight := n.bestBlock.Height
6✔
494
                                n.bestBlockMtx.Unlock()
6✔
495

6✔
496
                                missedBlocks, err := chainntnfs.GetClientMissedBlocks(
6✔
497
                                        n.chainConn, msg.bestBlock, bestHeight,
6✔
498
                                        false,
6✔
499
                                )
6✔
500
                                if err != nil {
6✔
UNCOV
501
                                        msg.errorChan <- err
×
UNCOV
502
                                        continue
×
503
                                }
504

505
                                for _, block := range missedBlocks {
56✔
506
                                        n.notifyBlockEpochClient(
50✔
507
                                                msg, block.Height, block.Hash,
50✔
508
                                                block.BlockHeader,
50✔
509
                                        )
50✔
510
                                }
50✔
511

512
                                msg.errorChan <- nil
6✔
513

514
                        case *rescanFilterUpdate:
75✔
515
                                err := n.chainView.Update(msg.updateOptions...)
75✔
516
                                if err != nil {
75✔
UNCOV
517
                                        chainntnfs.Log.Errorf("Unable to "+
×
UNCOV
518
                                                "update rescan filter: %v", err)
×
UNCOV
519
                                }
×
520

521
                                // Drain the chainUpdates chan so the caller
522
                                // listening on errChan can be sure that
523
                                // updates after receiving the error will have
524
                                // the filter applied. This allows the caller
525
                                // to update their EndHeight if they're
526
                                // performing a historical scan.
527
                                n.drainChainUpdates()
75✔
528

75✔
529
                                // After draining, send the error to the
75✔
530
                                // caller.
75✔
531
                                msg.errChan <- err
75✔
532
                        }
533

534
                case item := <-n.chainUpdates:
163✔
535
                        update := item
163✔
536
                        if update.connect {
322✔
537
                                n.connectFilteredBlock(update)
159✔
538
                                continue
159✔
539
                        }
540

541
                        n.disconnectFilteredBlock(update)
4✔
542

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

559
                case err := <-n.rescanErr:
1✔
560
                        chainntnfs.Log.Errorf("Error during rescan: %v", err)
1✔
561

562
                case <-n.quit:
4✔
563
                        return
4✔
564

565
                }
566
        }
567
}
568

569
// historicalConfDetails looks up whether a confirmation request (txid/output
570
// script) has already been included in a block in the active chain and, if so,
571
// returns details about said block.
572
func (n *NeutrinoNotifier) historicalConfDetails(confRequest chainntnfs.ConfRequest,
573
        startHeight, endHeight uint32) (*chainntnfs.TxConfirmation, error) {
34✔
574

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

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

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

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

621
                // If there's no match, then we can continue forward to the
622
                // next block.
623
                if !match {
90✔
624
                        continue
42✔
625
                }
626

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

636
                // For every transaction in the block, check which one matches
637
                // our request. If we find one that does, we can dispatch its
638
                // confirmation details.
639
                for i, tx := range block.Transactions() {
22✔
640
                        if !confRequest.MatchesTx(tx.MsgTx()) {
26✔
641
                                continue
11✔
642
                        }
643

644
                        return &chainntnfs.TxConfirmation{
5✔
645
                                Tx:          tx.MsgTx().Copy(),
5✔
646
                                BlockHash:   blockHash,
5✔
647
                                BlockHeight: scanHeight,
5✔
648
                                TxIndex:     uint32(i),
5✔
649
                                Block:       block.MsgBlock(),
5✔
650
                        }, nil
5✔
651
                }
652
        }
653

654
        return nil, nil
30✔
655
}
656

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

680
        chainntnfs.Log.Infof("New block: height=%v, sha=%v", newBlock.height,
166✔
681
                newBlock.hash)
166✔
682

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

166✔
692
        n.notifyBlockEpochs(
166✔
693
                int32(newBlock.height), &newBlock.hash, newBlock.header,
166✔
694
        )
166✔
695
        return n.txNotifier.NotifyHeight(newBlock.height)
166✔
696
}
697

698
// getFilteredBlock is a utility to retrieve the full filtered block from a block epoch.
699
func (n *NeutrinoNotifier) getFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) {
10✔
700
        rawBlock, err := n.GetBlock(*epoch.Hash)
10✔
701
        if err != nil {
10✔
UNCOV
702
                return nil, fmt.Errorf("unable to get block: %w", err)
×
UNCOV
703
        }
×
704

705
        txns := rawBlock.Transactions()
10✔
706

10✔
707
        block := &filteredBlock{
10✔
708
                hash:    *epoch.Hash,
10✔
709
                height:  uint32(epoch.Height),
10✔
710
                header:  &rawBlock.MsgBlock().Header,
10✔
711
                txns:    txns,
10✔
712
                connect: true,
10✔
713
        }
10✔
714
        return block, nil
10✔
715
}
716

717
// notifyBlockEpochs notifies all registered block epoch clients of the newly
718
// connected block to the main chain.
719
func (n *NeutrinoNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
720
        blockHeader *wire.BlockHeader) {
166✔
721

166✔
722
        for _, client := range n.blockEpochClients {
378✔
723
                n.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
212✔
724
        }
212✔
725
}
726

727
// notifyBlockEpochClient sends a registered block epoch client a notification
728
// about a specific block.
729
func (n *NeutrinoNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
730
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
276✔
731

276✔
732
        epoch := &chainntnfs.BlockEpoch{
276✔
733
                Height:      height,
276✔
734
                Hash:        sha,
276✔
735
                BlockHeader: blockHeader,
276✔
736
        }
276✔
737

276✔
738
        select {
276✔
739
        case epochClient.epochQueue.ChanIn() <- epoch:
276✔
UNCOV
740
        case <-epochClient.cancelChan:
×
UNCOV
741
        case <-n.quit:
×
742
        }
743
}
744

745
// RegisterSpendNtfn registers an intent to be notified once the target
746
// outpoint/output script has been spent by a transaction on-chain. When
747
// intending to be notified of the spend of an output script, a nil outpoint
748
// must be used. The heightHint should represent the earliest height in the
749
// chain of the transaction that spent the outpoint/output script.
750
//
751
// Once a spend of has been detected, the details of the spending event will be
752
// sent across the 'Spend' channel.
753
func (n *NeutrinoNotifier) RegisterSpendNtfn(outpoint *wire.OutPoint,
754
        pkScript []byte, heightHint uint32) (*chainntnfs.SpendEvent, error) {
27✔
755

27✔
756
        // Register the conf notification with the TxNotifier. A non-nil value
27✔
757
        // for `dispatch` will be returned if we are required to perform a
27✔
758
        // manual scan for the confirmation. Otherwise the notifier will begin
27✔
759
        // watching at tip for the transaction to confirm.
27✔
760
        ntfn, err := n.txNotifier.RegisterSpend(outpoint, pkScript, heightHint)
27✔
761
        if err != nil {
28✔
762
                return nil, err
1✔
763
        }
1✔
764

765
        // To determine whether this outpoint has been spent on-chain, we'll
766
        // update our filter to watch for the transaction at tip and we'll also
767
        // dispatch a historical rescan to determine if it has been spent in the
768
        // past.
769
        //
770
        // We'll update our filter first to ensure we can immediately detect the
771
        // spend at tip.
772
        if outpoint == nil {
40✔
773
                outpoint = &chainntnfs.ZeroOutPoint
13✔
774
        }
13✔
775
        inputToWatch := neutrino.InputWithScript{
27✔
776
                OutPoint: *outpoint,
27✔
777
                PkScript: pkScript,
27✔
778
        }
27✔
779
        updateOptions := []neutrino.UpdateOption{
27✔
780
                neutrino.AddInputs(inputToWatch),
27✔
781
                neutrino.DisableDisconnectedNtfns(true),
27✔
782
        }
27✔
783

27✔
784
        // We'll use the txNotifier's tip as the starting point of our filter
27✔
785
        // update. In the case of an output script spend request, we'll check if
27✔
786
        // we should perform a historical rescan and start from there, as we
27✔
787
        // cannot do so with GetUtxo since it matches outpoints.
27✔
788
        rewindHeight := ntfn.Height
27✔
789
        if ntfn.HistoricalDispatch != nil && *outpoint == chainntnfs.ZeroOutPoint {
28✔
790
                rewindHeight = ntfn.HistoricalDispatch.StartHeight
1✔
791
        }
1✔
792
        updateOptions = append(updateOptions, neutrino.Rewind(rewindHeight))
27✔
793

27✔
794
        errChan := make(chan error, 1)
27✔
795
        select {
27✔
796
        case n.notificationRegistry <- &rescanFilterUpdate{
797
                updateOptions: updateOptions,
798
                errChan:       errChan,
799
        }:
27✔
UNCOV
800
        case <-n.quit:
×
801
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
802
        }
803

804
        select {
27✔
805
        case err = <-errChan:
27✔
806
        case <-n.quit:
×
UNCOV
807
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
808
        }
809
        if err != nil {
27✔
UNCOV
810
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
UNCOV
811
        }
×
812

813
        // If the txNotifier didn't return any details to perform a historical
814
        // scan of the chain, or if we already performed one like in the case of
815
        // output script spend requests, then we can return early as there's
816
        // nothing left for us to do.
817
        if ntfn.HistoricalDispatch == nil || *outpoint == chainntnfs.ZeroOutPoint {
53✔
818
                return ntfn.Event, nil
26✔
819
        }
26✔
820

821
        // Grab the current best height as the height may have been updated
822
        // while we were draining the chainUpdates queue.
823
        n.bestBlockMtx.RLock()
2✔
824
        currentHeight := uint32(n.bestBlock.Height)
2✔
825
        n.bestBlockMtx.RUnlock()
2✔
826

2✔
827
        ntfn.HistoricalDispatch.EndHeight = currentHeight
2✔
828

2✔
829
        // With the filter updated, we'll dispatch our historical rescan to
2✔
830
        // ensure we detect the spend if it happened in the past.
2✔
831
        n.wg.Add(1)
2✔
832
        go func() {
4✔
833
                defer n.wg.Done()
2✔
834

2✔
835
                // We'll ensure that neutrino is caught up to the starting
2✔
836
                // height before we attempt to fetch the UTXO from the chain.
2✔
837
                // If we're behind, then we may miss a notification dispatch.
2✔
838
                for {
4✔
839
                        n.bestBlockMtx.RLock()
2✔
840
                        currentHeight := uint32(n.bestBlock.Height)
2✔
841
                        n.bestBlockMtx.RUnlock()
2✔
842

2✔
843
                        if currentHeight >= ntfn.HistoricalDispatch.StartHeight {
4✔
844
                                break
2✔
845
                        }
846

UNCOV
847
                        select {
×
UNCOV
848
                        case <-time.After(time.Millisecond * 200):
×
UNCOV
849
                        case <-n.quit:
×
UNCOV
850
                                return
×
851
                        }
852
                }
853

854
                spendReport, err := n.p2pNode.GetUtxo(
2✔
855
                        neutrino.WatchInputs(inputToWatch),
2✔
856
                        neutrino.StartBlock(&headerfs.BlockStamp{
2✔
857
                                Height: int32(ntfn.HistoricalDispatch.StartHeight),
2✔
858
                        }),
2✔
859
                        neutrino.EndBlock(&headerfs.BlockStamp{
2✔
860
                                Height: int32(ntfn.HistoricalDispatch.EndHeight),
2✔
861
                        }),
2✔
862
                        neutrino.ProgressHandler(func(processedHeight uint32) {
4✔
863
                                // We persist the rescan progress to achieve incremental
2✔
864
                                // behavior across restarts, otherwise long rescans may
2✔
865
                                // start from the beginning with every restart.
2✔
866
                                err := n.spendHintCache.CommitSpendHint(
2✔
867
                                        processedHeight,
2✔
868
                                        ntfn.HistoricalDispatch.SpendRequest)
2✔
869
                                if err != nil {
2✔
UNCOV
870
                                        chainntnfs.Log.Errorf("Failed to update rescan "+
×
UNCOV
871
                                                "progress: %v", err)
×
UNCOV
872
                                }
×
873
                        }),
874
                        neutrino.QuitChan(n.quit),
875
                )
876
                if err != nil && !strings.Contains(err.Error(), "not found") {
3✔
877
                        chainntnfs.Log.Errorf("Failed getting UTXO: %v", err)
1✔
878
                        return
1✔
879
                }
1✔
880

881
                // If a spend report was returned, and the transaction is present, then
882
                // this means that the output is already spent.
883
                var spendDetails *chainntnfs.SpendDetail
2✔
884
                if spendReport != nil && spendReport.SpendingTx != nil {
4✔
885
                        spendingTxHash := spendReport.SpendingTx.TxHash()
2✔
886
                        spendDetails = &chainntnfs.SpendDetail{
2✔
887
                                SpentOutPoint:     outpoint,
2✔
888
                                SpenderTxHash:     &spendingTxHash,
2✔
889
                                SpendingTx:        spendReport.SpendingTx,
2✔
890
                                SpenderInputIndex: spendReport.SpendingInputIndex,
2✔
891
                                SpendingHeight:    int32(spendReport.SpendingTxHeight),
2✔
892
                        }
2✔
893
                }
2✔
894

895
                // Finally, no matter whether the rescan found a spend in the past or
896
                // not, we'll mark our historical rescan as complete to ensure the
897
                // outpoint's spend hint gets updated upon connected/disconnected
898
                // blocks.
899
                err = n.txNotifier.UpdateSpendDetails(
2✔
900
                        ntfn.HistoricalDispatch.SpendRequest, spendDetails,
2✔
901
                )
2✔
902
                if err != nil {
2✔
UNCOV
903
                        chainntnfs.Log.Errorf("Failed to update spend details: %v", err)
×
UNCOV
904
                        return
×
UNCOV
905
                }
×
906
        }()
907

908
        return ntfn.Event, nil
2✔
909
}
910

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

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

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

950
        // We'll send the filter update request to the notifier's main event
951
        // handler and wait for its response.
952
        errChan := make(chan error, 1)
49✔
953
        select {
49✔
954
        case n.notificationRegistry <- &rescanFilterUpdate{
955
                updateOptions: []neutrino.UpdateOption{
956
                        neutrino.AddAddrs(addrs...),
957
                        neutrino.Rewind(ntfn.Height),
958
                        neutrino.DisableDisconnectedNtfns(true),
959
                },
960
                errChan: errChan,
961
        }:
49✔
UNCOV
962
        case <-n.quit:
×
963
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
964
        }
965

966
        select {
49✔
967
        case err = <-errChan:
49✔
968
        case <-n.quit:
×
UNCOV
969
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
970
        }
971
        if err != nil {
49✔
UNCOV
972
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
UNCOV
973
        }
×
974

975
        // If a historical rescan was not requested by the txNotifier, then we
976
        // can return to the caller.
977
        if ntfn.HistoricalDispatch == nil {
65✔
978
                return ntfn.Event, nil
16✔
979
        }
16✔
980

981
        // Grab the current best height as the height may have been updated
982
        // while we were draining the chainUpdates queue.
983
        n.bestBlockMtx.RLock()
34✔
984
        currentHeight := uint32(n.bestBlock.Height)
34✔
985
        n.bestBlockMtx.RUnlock()
34✔
986

34✔
987
        ntfn.HistoricalDispatch.EndHeight = currentHeight
34✔
988

34✔
989
        // Finally, with the filter updated, we can dispatch the historical
34✔
990
        // rescan to ensure we can detect if the event happened in the past.
34✔
991
        select {
34✔
992
        case n.notificationRegistry <- ntfn.HistoricalDispatch:
34✔
UNCOV
993
        case <-n.quit:
×
UNCOV
994
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
995
        }
996

997
        return ntfn.Event, nil
34✔
998
}
999

1000
// GetBlock is used to retrieve the block with the given hash. Since the block
1001
// cache used by neutrino will be the same as that used by LND (since it is
1002
// passed to neutrino on initialisation), the neutrino GetBlock method can be
1003
// called directly since it already uses the block cache. However, neutrino
1004
// does not lock the block cache mutex for the given block hash and so that is
1005
// done here.
1006
func (n *NeutrinoNotifier) GetBlock(hash chainhash.Hash) (
1007
        *btcutil.Block, error) {
182✔
1008

182✔
1009
        n.blockCache.HashMutex.Lock(lntypes.Hash(hash))
182✔
1010
        defer n.blockCache.HashMutex.Unlock(lntypes.Hash(hash))
182✔
1011

182✔
1012
        return n.p2pNode.GetBlock(hash)
182✔
1013
}
182✔
1014

1015
// blockEpochRegistration represents a client's intent to receive a
1016
// notification with each newly connected block.
1017
type blockEpochRegistration struct {
1018
        epochID uint64
1019

1020
        epochChan chan *chainntnfs.BlockEpoch
1021

1022
        epochQueue *queue.ConcurrentQueue
1023

1024
        cancelChan chan struct{}
1025

1026
        bestBlock *chainntnfs.BlockEpoch
1027

1028
        errorChan chan error
1029

1030
        wg sync.WaitGroup
1031
}
1032

1033
// epochCancel is a message sent to the NeutrinoNotifier when a client wishes
1034
// to cancel an outstanding epoch notification that has yet to be dispatched.
1035
type epochCancel struct {
1036
        epochID uint64
1037
}
1038

1039
// RegisterBlockEpochNtfn returns a BlockEpochEvent which subscribes the
1040
// caller to receive notifications, of each new block connected to the main
1041
// chain. Clients have the option of passing in their best known block, which
1042
// the notifier uses to check if they are behind on blocks and catch them up. If
1043
// they do not provide one, then a notification will be dispatched immediately
1044
// for the current tip of the chain upon a successful registration.
1045
func (n *NeutrinoNotifier) RegisterBlockEpochNtfn(
1046
        bestBlock *chainntnfs.BlockEpoch) (*chainntnfs.BlockEpochEvent, error) {
20✔
1047

20✔
1048
        reg := &blockEpochRegistration{
20✔
1049
                epochQueue: queue.NewConcurrentQueue(20),
20✔
1050
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
20✔
1051
                cancelChan: make(chan struct{}),
20✔
1052
                epochID:    atomic.AddUint64(&n.epochClientCounter, 1),
20✔
1053
                bestBlock:  bestBlock,
20✔
1054
                errorChan:  make(chan error, 1),
20✔
1055
        }
20✔
1056
        reg.epochQueue.Start()
20✔
1057

20✔
1058
        // Before we send the request to the main goroutine, we'll launch a new
20✔
1059
        // goroutine to proxy items added to our queue to the client itself.
20✔
1060
        // This ensures that all notifications are received *in order*.
20✔
1061
        reg.wg.Add(1)
20✔
1062
        go func() {
40✔
1063
                defer reg.wg.Done()
20✔
1064

20✔
1065
                for {
269✔
1066
                        select {
249✔
1067
                        case ntfn := <-reg.epochQueue.ChanOut():
232✔
1068
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
232✔
1069
                                select {
232✔
1070
                                case reg.epochChan <- blockNtfn:
230✔
1071

1072
                                case <-reg.cancelChan:
1✔
1073
                                        return
1✔
1074

1075
                                case <-n.quit:
2✔
1076
                                        return
2✔
1077
                                }
1078

1079
                        case <-reg.cancelChan:
2✔
1080
                                return
2✔
1081

1082
                        case <-n.quit:
17✔
1083
                                return
17✔
1084
                        }
1085
                }
1086
        }()
1087

1088
        select {
20✔
1089
        case <-n.quit:
×
1090
                // As we're exiting before the registration could be sent,
×
UNCOV
1091
                // we'll stop the queue now ourselves.
×
UNCOV
1092
                reg.epochQueue.Stop()
×
UNCOV
1093

×
UNCOV
1094
                return nil, errors.New("chainntnfs: system interrupt while " +
×
UNCOV
1095
                        "attempting to register for block epoch notification.")
×
1096
        case n.notificationRegistry <- reg:
20✔
1097
                return &chainntnfs.BlockEpochEvent{
20✔
1098
                        Epochs: reg.epochChan,
20✔
1099
                        Cancel: func() {
22✔
1100
                                cancel := &epochCancel{
2✔
1101
                                        epochID: reg.epochID,
2✔
1102
                                }
2✔
1103

2✔
1104
                                // Submit epoch cancellation to notification dispatcher.
2✔
1105
                                select {
2✔
1106
                                case n.notificationCancels <- cancel:
2✔
1107
                                        // Cancellation is being handled, drain the epoch channel until it is
2✔
1108
                                        // closed before yielding to caller.
2✔
1109
                                        for {
5✔
1110
                                                select {
3✔
1111
                                                case _, ok := <-reg.epochChan:
3✔
1112
                                                        if !ok {
5✔
1113
                                                                return
2✔
1114
                                                        }
2✔
1115
                                                case <-n.quit:
1✔
1116
                                                        return
1✔
1117
                                                }
1118
                                        }
1119
                                case <-n.quit:
1✔
1120
                                }
1121
                        },
1122
                }, nil
1123
        }
1124
}
1125

1126
// NeutrinoChainConn is a wrapper around neutrino's chain backend in order
1127
// to satisfy the chainntnfs.ChainConn interface.
1128
type NeutrinoChainConn struct {
1129
        p2pNode *neutrino.ChainService
1130
}
1131

1132
// GetBlockHeader returns the block header for a hash.
1133
func (n *NeutrinoChainConn) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
64✔
1134
        return n.p2pNode.GetBlockHeader(blockHash)
64✔
1135
}
64✔
1136

1137
// GetBlockHeaderVerbose returns a verbose block header result for a hash. This
1138
// result only contains the height with a nil hash.
1139
func (n *NeutrinoChainConn) GetBlockHeaderVerbose(blockHash *chainhash.Hash) (
1140
        *btcjson.GetBlockHeaderVerboseResult, error) {
×
UNCOV
1141

×
1142
        height, err := n.p2pNode.GetBlockHeight(blockHash)
×
UNCOV
1143
        if err != nil {
×
UNCOV
1144
                return nil, err
×
UNCOV
1145
        }
×
1146
        // Since only the height is used from the result, leave the hash nil.
UNCOV
1147
        return &btcjson.GetBlockHeaderVerboseResult{Height: int32(height)}, nil
×
1148
}
1149

1150
// GetBlockHash returns the hash from a block height.
1151
func (n *NeutrinoChainConn) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) {
64✔
1152
        return n.p2pNode.GetBlockHash(blockHeight)
64✔
1153
}
64✔
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