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

lightningnetwork / lnd / 13586005509

28 Feb 2025 10:14AM UTC coverage: 68.629% (+9.9%) from 58.77%
13586005509

Pull #9521

github

web-flow
Merge 37d3a70a5 into 8532955b3
Pull Request #9521: unit: remove GOACC, use Go 1.20 native coverage functionality

129950 of 189351 relevant lines covered (68.63%)

23726.46 hits per line

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

83.82
/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✔
182
                n.txUpdates.Stop()
×
183
                return err
×
184
        }
×
185
        startingHeader, err := n.p2pNode.GetBlockHeader(
2✔
186
                &startingPoint.Hash,
2✔
187
        )
2✔
188
        if err != nil {
2✔
189
                n.txUpdates.Stop()
×
190
                return err
×
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) {
179✔
267

179✔
268
        // Append this new chain update to the end of the queue of new chain
179✔
269
        // updates.
179✔
270
        select {
179✔
271
        case n.chainUpdates <- &filteredBlock{
272
                hash:    header.BlockHash(),
273
                height:  uint32(height),
274
                txns:    txns,
275
                header:  header,
276
                connect: true,
277
        }:
179✔
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✔
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✔
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) {
158✔
319
        n.bestBlockMtx.Lock()
158✔
320
        defer n.bestBlockMtx.Unlock()
158✔
321

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

4✔
325
                _, missedBlocks, err := chainntnfs.HandleMissedBlocks(
4✔
326
                        n.chainConn, n.txNotifier, n.bestBlock,
4✔
327
                        int32(update.height), false,
4✔
328
                )
4✔
329
                if err != nil {
7✔
330
                        chainntnfs.Log.Error(err)
3✔
331
                        return
3✔
332
                }
3✔
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✔
342
                                chainntnfs.Log.Error(err)
×
343
                                return
×
344
                        }
×
345
                }
346
        }
347

348
        err := n.handleBlockConnected(update)
156✔
349
        if err != nil {
156✔
350
                chainntnfs.Log.Error(err)
×
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✔
362
                chainntnfs.Log.Infof("Missed disconnected blocks, attempting" +
×
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✔
369
                chainntnfs.Log.Errorf("Unable to rewind chain from height %d"+
×
370
                        "to height %d: %v", n.bestBlock.Height,
×
371
                        update.height-1, err,
×
372
                )
×
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 {
151✔
387
                select {
76✔
388
                case update := <-n.chainUpdates:
2✔
389
                        if update.connect {
4✔
390
                                n.connectFilteredBlock(update)
2✔
391
                                break
2✔
392
                        }
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 {
306✔
406
                select {
302✔
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:
128✔
435
                        switch msg := registerMsg.(type) {
128✔
436
                        case *chainntnfs.HistoricalConfDispatch:
35✔
437
                                // We'll start a historical rescan chain of the
35✔
438
                                // chain asynchronously to prevent blocking
35✔
439
                                // potentially long rescans.
35✔
440
                                n.wg.Add(1)
35✔
441

35✔
442
                                //nolint:ll
35✔
443
                                go func(msg *chainntnfs.HistoricalConfDispatch) {
70✔
444
                                        defer n.wg.Done()
35✔
445

35✔
446
                                        confDetails, err := n.historicalConfDetails(
35✔
447
                                                msg.ConfRequest,
35✔
448
                                                msg.StartHeight, msg.EndHeight,
35✔
449
                                        )
35✔
450
                                        if err != nil {
35✔
451
                                                chainntnfs.Log.Error(err)
×
452
                                                return
×
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(
35✔
463
                                                msg.ConfRequest, confDetails,
35✔
464
                                        )
35✔
465
                                        if err != nil {
35✔
466
                                                chainntnfs.Log.Error(err)
×
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✔
501
                                        msg.errorChan <- err
×
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✔
517
                                        chainntnfs.Log.Errorf("Unable to "+
×
518
                                                "update rescan filter: %v", err)
×
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:
161✔
535
                        update := item
161✔
536
                        if update.connect {
318✔
537
                                n.connectFilteredBlock(update)
157✔
538
                                continue
157✔
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(),
×
556
                                        err)
×
557
                        }
×
558

559
                case err := <-n.rescanErr:
×
560
                        chainntnfs.Log.Errorf("Error during rescan: %v", err)
×
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) {
35✔
574

35✔
575
        // Starting from the height hint, we'll walk forwards in the chain to
35✔
576
        // see if this transaction/output script has already been confirmed.
35✔
577
        for scanHeight := endHeight; scanHeight >= startHeight && scanHeight > 0; scanHeight-- {
84✔
578
                // Ensure we haven't been requested to shut down before
49✔
579
                // processing the next height.
49✔
580
                select {
49✔
581
                case <-n.quit:
×
582
                        return nil, chainntnfs.ErrChainNotifierShuttingDown
×
583
                default:
49✔
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))
49✔
589
                if err != nil {
49✔
590
                        return nil, fmt.Errorf("unable to get header for "+
×
591
                                "height=%v: %w", scanHeight, err)
×
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(
49✔
602
                        *blockHash, wire.GCSFilterRegular,
49✔
603
                        neutrino.NumRetries(5),
49✔
604
                        neutrino.OptimisticReverseBatch(),
49✔
605
                        neutrino.MaxBatchSize(int64(scanHeight-startHeight+1)),
49✔
606
                )
49✔
607
                if err != nil {
49✔
608
                        return nil, fmt.Errorf("unable to retrieve regular "+
×
609
                                "filter for height=%v: %w", scanHeight, err)
×
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)
49✔
615
                match, err := regFilter.Match(key, confRequest.PkScript.Script())
49✔
616
                if err != nil {
49✔
617
                        return nil, fmt.Errorf("unable to query filter: %w",
×
618
                                err)
×
619
                }
×
620

621
                // If there's no match, then we can continue forward to the
622
                // next block.
623
                if !match {
92✔
624
                        continue
43✔
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✔
632
                        return nil, fmt.Errorf("unable to get block from "+
×
633
                                "network: %w", err)
×
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() {
23✔
640
                        if !confRequest.MatchesTx(tx.MsgTx()) {
28✔
641
                                continue
12✔
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
31✔
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)
×
674
        }
×
675
        err = n.txNotifier.ConnectTip(rawBlock, newBlock.height)
166✔
676
        if err != nil {
166✔
677
                return fmt.Errorf("unable to connect tip: %w", err)
×
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
        err = n.txNotifier.NotifyHeight(newBlock.height)
166✔
693
        if err != nil {
166✔
694
                return fmt.Errorf("unable to notify height: %w", err)
×
695
        }
×
696

697
        n.notifyBlockEpochs(
166✔
698
                int32(newBlock.height), &newBlock.hash, newBlock.header,
166✔
699
        )
166✔
700

166✔
701
        return nil
166✔
702
}
703

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

711
        txns := rawBlock.Transactions()
10✔
712

10✔
713
        block := &filteredBlock{
10✔
714
                hash:    *epoch.Hash,
10✔
715
                height:  uint32(epoch.Height),
10✔
716
                header:  &rawBlock.MsgBlock().Header,
10✔
717
                txns:    txns,
10✔
718
                connect: true,
10✔
719
        }
10✔
720
        return block, nil
10✔
721
}
722

723
// notifyBlockEpochs notifies all registered block epoch clients of the newly
724
// connected block to the main chain.
725
func (n *NeutrinoNotifier) notifyBlockEpochs(newHeight int32, newSha *chainhash.Hash,
726
        blockHeader *wire.BlockHeader) {
166✔
727

166✔
728
        for _, client := range n.blockEpochClients {
378✔
729
                n.notifyBlockEpochClient(client, newHeight, newSha, blockHeader)
212✔
730
        }
212✔
731
}
732

733
// notifyBlockEpochClient sends a registered block epoch client a notification
734
// about a specific block.
735
func (n *NeutrinoNotifier) notifyBlockEpochClient(epochClient *blockEpochRegistration,
736
        height int32, sha *chainhash.Hash, blockHeader *wire.BlockHeader) {
276✔
737

276✔
738
        epoch := &chainntnfs.BlockEpoch{
276✔
739
                Height:      height,
276✔
740
                Hash:        sha,
276✔
741
                BlockHeader: blockHeader,
276✔
742
        }
276✔
743

276✔
744
        select {
276✔
745
        case epochClient.epochQueue.ChanIn() <- epoch:
276✔
746
        case <-epochClient.cancelChan:
×
747
        case <-n.quit:
×
748
        }
749
}
750

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

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

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

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

27✔
800
        errChan := make(chan error, 1)
27✔
801
        select {
27✔
802
        case n.notificationRegistry <- &rescanFilterUpdate{
803
                updateOptions: updateOptions,
804
                errChan:       errChan,
805
        }:
27✔
806
        case <-n.quit:
×
807
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
808
        }
809

810
        select {
27✔
811
        case err = <-errChan:
27✔
812
        case <-n.quit:
×
813
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
814
        }
815
        if err != nil {
27✔
816
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
817
        }
×
818

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

827
        // Grab the current best height as the height may have been updated
828
        // while we were draining the chainUpdates queue.
829
        n.bestBlockMtx.RLock()
2✔
830
        currentHeight := uint32(n.bestBlock.Height)
2✔
831
        n.bestBlockMtx.RUnlock()
2✔
832

2✔
833
        ntfn.HistoricalDispatch.EndHeight = currentHeight
2✔
834

2✔
835
        // With the filter updated, we'll dispatch our historical rescan to
2✔
836
        // ensure we detect the spend if it happened in the past.
2✔
837
        n.wg.Add(1)
2✔
838
        go func() {
4✔
839
                defer n.wg.Done()
2✔
840

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

2✔
849
                        if currentHeight >= ntfn.HistoricalDispatch.StartHeight {
4✔
850
                                break
2✔
851
                        }
852

853
                        select {
×
854
                        case <-time.After(time.Millisecond * 200):
×
855
                        case <-n.quit:
×
856
                                return
×
857
                        }
858
                }
859

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

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

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

914
        return ntfn.Event, nil
2✔
915
}
916

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

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

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

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

972
        select {
49✔
973
        case err = <-errChan:
49✔
974
        case <-n.quit:
×
975
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
976
        }
977
        if err != nil {
49✔
978
                return nil, fmt.Errorf("unable to update filter: %w", err)
×
979
        }
×
980

981
        // If a historical rescan was not requested by the txNotifier, then we
982
        // can return to the caller.
983
        if ntfn.HistoricalDispatch == nil {
64✔
984
                return ntfn.Event, nil
15✔
985
        }
15✔
986

987
        // Grab the current best height as the height may have been updated
988
        // while we were draining the chainUpdates queue.
989
        n.bestBlockMtx.RLock()
35✔
990
        currentHeight := uint32(n.bestBlock.Height)
35✔
991
        n.bestBlockMtx.RUnlock()
35✔
992

35✔
993
        ntfn.HistoricalDispatch.EndHeight = currentHeight
35✔
994

35✔
995
        // Finally, with the filter updated, we can dispatch the historical
35✔
996
        // rescan to ensure we can detect if the event happened in the past.
35✔
997
        select {
35✔
998
        case n.notificationRegistry <- ntfn.HistoricalDispatch:
35✔
999
        case <-n.quit:
×
1000
                return nil, chainntnfs.ErrChainNotifierShuttingDown
×
1001
        }
1002

1003
        return ntfn.Event, nil
35✔
1004
}
1005

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

182✔
1015
        n.blockCache.HashMutex.Lock(lntypes.Hash(hash))
182✔
1016
        defer n.blockCache.HashMutex.Unlock(lntypes.Hash(hash))
182✔
1017

182✔
1018
        return n.p2pNode.GetBlock(hash)
182✔
1019
}
182✔
1020

1021
// blockEpochRegistration represents a client's intent to receive a
1022
// notification with each newly connected block.
1023
type blockEpochRegistration struct {
1024
        epochID uint64
1025

1026
        epochChan chan *chainntnfs.BlockEpoch
1027

1028
        epochQueue *queue.ConcurrentQueue
1029

1030
        cancelChan chan struct{}
1031

1032
        bestBlock *chainntnfs.BlockEpoch
1033

1034
        errorChan chan error
1035

1036
        wg sync.WaitGroup
1037
}
1038

1039
// epochCancel is a message sent to the NeutrinoNotifier when a client wishes
1040
// to cancel an outstanding epoch notification that has yet to be dispatched.
1041
type epochCancel struct {
1042
        epochID uint64
1043
}
1044

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

20✔
1054
        reg := &blockEpochRegistration{
20✔
1055
                epochQueue: queue.NewConcurrentQueue(20),
20✔
1056
                epochChan:  make(chan *chainntnfs.BlockEpoch, 20),
20✔
1057
                cancelChan: make(chan struct{}),
20✔
1058
                epochID:    atomic.AddUint64(&n.epochClientCounter, 1),
20✔
1059
                bestBlock:  bestBlock,
20✔
1060
                errorChan:  make(chan error, 1),
20✔
1061
        }
20✔
1062
        reg.epochQueue.Start()
20✔
1063

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

20✔
1071
                for {
269✔
1072
                        select {
249✔
1073
                        case ntfn := <-reg.epochQueue.ChanOut():
232✔
1074
                                blockNtfn := ntfn.(*chainntnfs.BlockEpoch)
232✔
1075
                                select {
232✔
1076
                                case reg.epochChan <- blockNtfn:
230✔
1077

1078
                                case <-reg.cancelChan:
1✔
1079
                                        return
1✔
1080

1081
                                case <-n.quit:
2✔
1082
                                        return
2✔
1083
                                }
1084

1085
                        case <-reg.cancelChan:
2✔
1086
                                return
2✔
1087

1088
                        case <-n.quit:
17✔
1089
                                return
17✔
1090
                        }
1091
                }
1092
        }()
1093

1094
        select {
20✔
1095
        case <-n.quit:
×
1096
                // As we're exiting before the registration could be sent,
×
1097
                // we'll stop the queue now ourselves.
×
1098
                reg.epochQueue.Stop()
×
1099

×
1100
                return nil, errors.New("chainntnfs: system interrupt while " +
×
1101
                        "attempting to register for block epoch notification.")
×
1102
        case n.notificationRegistry <- reg:
20✔
1103
                return &chainntnfs.BlockEpochEvent{
20✔
1104
                        Epochs: reg.epochChan,
20✔
1105
                        Cancel: func() {
22✔
1106
                                cancel := &epochCancel{
2✔
1107
                                        epochID: reg.epochID,
2✔
1108
                                }
2✔
1109

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

1132
// NeutrinoChainConn is a wrapper around neutrino's chain backend in order
1133
// to satisfy the chainntnfs.ChainConn interface.
1134
type NeutrinoChainConn struct {
1135
        p2pNode *neutrino.ChainService
1136
}
1137

1138
// GetBlockHeader returns the block header for a hash.
1139
func (n *NeutrinoChainConn) GetBlockHeader(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
64✔
1140
        return n.p2pNode.GetBlockHeader(blockHash)
64✔
1141
}
64✔
1142

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

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

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