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

lightningnetwork / lnd / 15740541296

18 Jun 2025 06:19PM UTC coverage: 58.206% (-10.0%) from 68.248%
15740541296

Pull #9878

github

web-flow
Merge 4f0d27afa into 31c74f20f
Pull Request #9878: chainntfns: add option to send all confirmations

15 of 23 new or added lines in 2 files covered. (65.22%)

28313 existing lines in 453 files now uncovered.

97868 of 168142 relevant lines covered (58.21%)

1.81 hits per line

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

81.83
/chainntnfs/txnotifier.go
1
package chainntnfs
2

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

10
        "github.com/btcsuite/btcd/btcutil"
11
        "github.com/btcsuite/btcd/chaincfg/chainhash"
12
        "github.com/btcsuite/btcd/txscript"
13
        "github.com/btcsuite/btcd/wire"
14
)
15

16
const (
17
        // ReorgSafetyLimit is the chain depth beyond which it is assumed a
18
        // block will not be reorganized out of the chain. This is used to
19
        // determine when to prune old confirmation requests so that reorgs are
20
        // handled correctly. The average number of blocks in a day is a
21
        // reasonable value to use.
22
        ReorgSafetyLimit = 144
23

24
        // MaxNumConfs is the maximum number of confirmations that can be
25
        // requested on a transaction.
26
        MaxNumConfs = ReorgSafetyLimit
27
)
28

29
var (
30
        // ZeroHash is the value that should be used as the txid when
31
        // registering for the confirmation of a script on-chain. This allows
32
        // the notifier to match _and_ dispatch upon the inclusion of the script
33
        // on-chain, rather than the txid.
34
        ZeroHash chainhash.Hash
35

36
        // ZeroOutPoint is the value that should be used as the outpoint when
37
        // registering for the spend of a script on-chain. This allows the
38
        // notifier to match _and_ dispatch upon detecting the spend of the
39
        // script on-chain, rather than the outpoint.
40
        ZeroOutPoint wire.OutPoint
41

42
        // zeroV1KeyPush is a pkScript that pushes an all-zero 32-byte Taproot
43
        // SegWit v1 key to the stack.
44
        zeroV1KeyPush = [34]byte{
45
                txscript.OP_1, txscript.OP_DATA_32, // 32 byte of zeroes here
46
        }
47

48
        // ZeroTaprootPkScript is the parsed txscript.PkScript of an empty
49
        // Taproot SegWit v1 key being pushed to the stack. This allows the
50
        // notifier to match _and_ dispatch upon detecting the spend of the
51
        // outpoint on-chain, rather than the pkScript (which cannot be derived
52
        // from the witness alone in the SegWit v1 case).
53
        ZeroTaprootPkScript, _ = txscript.ParsePkScript(zeroV1KeyPush[:])
54
)
55

56
var (
57
        // ErrTxNotifierExiting is an error returned when attempting to interact
58
        // with the TxNotifier but it been shut down.
59
        ErrTxNotifierExiting = errors.New("TxNotifier is exiting")
60

61
        // ErrNoScript is an error returned when a confirmation/spend
62
        // registration is attempted without providing an accompanying output
63
        // script.
64
        ErrNoScript = errors.New("an output script must be provided")
65

66
        // ErrNoHeightHint is an error returned when a confirmation/spend
67
        // registration is attempted without providing an accompanying height
68
        // hint.
69
        ErrNoHeightHint = errors.New("a height hint greater than 0 must be " +
70
                "provided")
71

72
        // ErrNumConfsOutOfRange is an error returned when a confirmation/spend
73
        // registration is attempted and the number of confirmations provided is
74
        // out of range.
75
        ErrNumConfsOutOfRange = fmt.Errorf("number of confirmations must be "+
76
                "between %d and %d", 1, MaxNumConfs)
77

78
        // ErrEmptyWitnessStack is returned when a spending transaction has an
79
        // empty witness stack. More details in,
80
        // - https://github.com/bitcoin/bitcoin/issues/28730
81
        ErrEmptyWitnessStack = errors.New("witness stack is empty")
82
)
83

84
// rescanState indicates the progression of a registration before the notifier
85
// can begin dispatching confirmations at tip.
86
type rescanState byte
87

88
const (
89
        // rescanNotStarted is the initial state, denoting that a historical
90
        // dispatch may be required.
91
        rescanNotStarted rescanState = iota
92

93
        // rescanPending indicates that a dispatch has already been made, and we
94
        // are waiting for its completion. No other rescans should be dispatched
95
        // while in this state.
96
        rescanPending
97

98
        // rescanComplete signals either that a rescan was dispatched and has
99
        // completed, or that we began watching at tip immediately. In either
100
        // case, the notifier can only dispatch notifications from tip when in
101
        // this state.
102
        rescanComplete
103
)
104

105
// confNtfnSet holds all known, registered confirmation notifications for a
106
// txid/output script. If duplicates notifications are requested, only one
107
// historical dispatch will be spawned to ensure redundant scans are not
108
// permitted. A single conf detail will be constructed and dispatched to all
109
// interested
110
// clients.
111
type confNtfnSet struct {
112
        // ntfns keeps tracks of all the active client notification requests for
113
        // a transaction/output script
114
        ntfns map[uint64]*ConfNtfn
115

116
        // rescanStatus represents the current rescan state for the
117
        // transaction/output script.
118
        rescanStatus rescanState
119

120
        // details serves as a cache of the confirmation details of a
121
        // transaction that we'll use to determine if a transaction/output
122
        // script has already confirmed at the time of registration.
123
        // details is also used to make sure that in case of an address reuse
124
        // (funds sent to a previously confirmed script) no additional
125
        // notification is registered which would lead to an inconsistent state.
126
        details *TxConfirmation
127
}
128

129
// newConfNtfnSet constructs a fresh confNtfnSet for a group of clients
130
// interested in a notification for a particular txid.
131
func newConfNtfnSet() *confNtfnSet {
3✔
132
        return &confNtfnSet{
3✔
133
                ntfns:        make(map[uint64]*ConfNtfn),
3✔
134
                rescanStatus: rescanNotStarted,
3✔
135
        }
3✔
136
}
3✔
137

138
// spendNtfnSet holds all known, registered spend notifications for a spend
139
// request (outpoint/output script). If duplicate notifications are requested,
140
// only one historical dispatch will be spawned to ensure redundant scans are
141
// not permitted.
142
type spendNtfnSet struct {
143
        // ntfns keeps tracks of all the active client notification requests for
144
        // an outpoint/output script.
145
        ntfns map[uint64]*SpendNtfn
146

147
        // rescanStatus represents the current rescan state for the spend
148
        // request (outpoint/output script).
149
        rescanStatus rescanState
150

151
        // details serves as a cache of the spend details for an outpoint/output
152
        // script that we'll use to determine if it has already been spent at
153
        // the time of registration.
154
        details *SpendDetail
155
}
156

157
// newSpendNtfnSet constructs a new spend notification set.
158
func newSpendNtfnSet() *spendNtfnSet {
3✔
159
        return &spendNtfnSet{
3✔
160
                ntfns:        make(map[uint64]*SpendNtfn),
3✔
161
                rescanStatus: rescanNotStarted,
3✔
162
        }
3✔
163
}
3✔
164

165
// ConfRequest encapsulates a request for a confirmation notification of either
166
// a txid or output script.
167
type ConfRequest struct {
168
        // TxID is the hash of the transaction for which confirmation
169
        // notifications are requested. If set to a zero hash, then a
170
        // confirmation notification will be dispatched upon inclusion of the
171
        // _script_, rather than the txid.
172
        TxID chainhash.Hash
173

174
        // PkScript is the public key script of an outpoint created in this
175
        // transaction.
176
        PkScript txscript.PkScript
177
}
178

179
// NewConfRequest creates a request for a confirmation notification of either a
180
// txid or output script. A nil txid or an allocated ZeroHash can be used to
181
// dispatch the confirmation notification on the script.
182
func NewConfRequest(txid *chainhash.Hash, pkScript []byte) (ConfRequest, error) {
3✔
183
        var r ConfRequest
3✔
184
        outputScript, err := txscript.ParsePkScript(pkScript)
3✔
185
        if err != nil {
3✔
186
                return r, err
×
187
        }
×
188

189
        // We'll only set a txid for which we'll dispatch a confirmation
190
        // notification on this request if one was provided. Otherwise, we'll
191
        // default to dispatching on the confirmation of the script instead.
192
        if txid != nil {
6✔
193
                r.TxID = *txid
3✔
194
        }
3✔
195
        r.PkScript = outputScript
3✔
196

3✔
197
        return r, nil
3✔
198
}
199

200
// String returns the string representation of the ConfRequest.
201
func (r ConfRequest) String() string {
3✔
202
        if r.TxID != ZeroHash {
6✔
203
                return fmt.Sprintf("txid=%v", r.TxID)
3✔
204
        }
3✔
205
        return fmt.Sprintf("script=%v", r.PkScript)
×
206
}
207

208
// MatchesTx determines whether the given transaction satisfies the confirmation
209
// request. If the confirmation request is for a script, then we'll check all of
210
// the outputs of the transaction to determine if it matches. Otherwise, we'll
211
// match on the txid.
212
func (r ConfRequest) MatchesTx(tx *wire.MsgTx) bool {
3✔
213
        scriptMatches := func() bool {
6✔
214
                pkScript := r.PkScript.Script()
3✔
215
                for _, txOut := range tx.TxOut {
6✔
216
                        if bytes.Equal(txOut.PkScript, pkScript) {
6✔
217
                                return true
3✔
218
                        }
3✔
219
                }
220

UNCOV
221
                return false
×
222
        }
223

224
        if r.TxID != ZeroHash {
6✔
225
                return r.TxID == tx.TxHash() && scriptMatches()
3✔
226
        }
3✔
227

UNCOV
228
        return scriptMatches()
×
229
}
230

231
// ConfNtfn represents a notifier client's request to receive a notification
232
// once the target transaction/output script gets sufficient confirmations. The
233
// client is asynchronously notified via the ConfirmationEvent channels.
234
type ConfNtfn struct {
235
        // ConfID uniquely identifies the confirmation notification request for
236
        // the specified transaction/output script.
237
        ConfID uint64
238

239
        // ConfRequest represents either the txid or script we should detect
240
        // inclusion of within the chain.
241
        ConfRequest
242

243
        // NumConfirmations is the number of confirmations after which the
244
        // notification is to be sent.
245
        NumConfirmations uint32
246

247
        // Event contains references to the channels that the notifications are
248
        // to be sent over.
249
        Event *ConfirmationEvent
250

251
        // HeightHint is the minimum height in the chain that we expect to find
252
        // this txid.
253
        HeightHint uint32
254

255
        // dispatched is false if the confirmed notification has not been sent
256
        // yet.
257
        dispatched bool
258

259
        // includeBlock is true if the dispatched notification should also have
260
        // the block included with it.
261
        includeBlock bool
262

263
        // allConfirmations is true if the client wants to receive a
264
        // notification for every confirmation of this transaction/output script
265
        // rather than just the final one. If true, the client will receive a
266
        // notification for each confirmation, starting from the first.
267
        allConfirmations bool
268

269
        // numConfsLeft is the number of confirmations left to be sent to the
270
        // subscriber.
271
        numConfsLeft uint32
272
}
273

274
// HistoricalConfDispatch parametrizes a manual rescan for a particular
275
// transaction/output script. The parameters include the start and end block
276
// heights specifying the range of blocks to scan.
277
type HistoricalConfDispatch struct {
278
        // ConfRequest represents either the txid or script we should detect
279
        // inclusion of within the chain.
280
        ConfRequest
281

282
        // StartHeight specifies the block height at which to begin the
283
        // historical rescan.
284
        StartHeight uint32
285

286
        // EndHeight specifies the last block height (inclusive) that the
287
        // historical scan should consider.
288
        EndHeight uint32
289
}
290

291
// ConfRegistration encompasses all of the information required for callers to
292
// retrieve details about a confirmation event.
293
type ConfRegistration struct {
294
        // Event contains references to the channels that the notifications are
295
        // to be sent over.
296
        Event *ConfirmationEvent
297

298
        // HistoricalDispatch, if non-nil, signals to the client who registered
299
        // the notification that they are responsible for attempting to manually
300
        // rescan blocks for the txid/output script between the start and end
301
        // heights.
302
        HistoricalDispatch *HistoricalConfDispatch
303

304
        // Height is the height of the TxNotifier at the time the confirmation
305
        // notification was registered. This can be used so that backends can
306
        // request to be notified of confirmations from this point forwards.
307
        Height uint32
308
}
309

310
// SpendRequest encapsulates a request for a spend notification of either an
311
// outpoint or output script.
312
type SpendRequest struct {
313
        // OutPoint is the outpoint for which a client has requested a spend
314
        // notification for. If set to a zero outpoint, then a spend
315
        // notification will be dispatched upon detecting the spend of the
316
        // _script_, rather than the outpoint.
317
        OutPoint wire.OutPoint
318

319
        // PkScript is the script of the outpoint. If a zero outpoint is set,
320
        // then this can be an arbitrary script.
321
        PkScript txscript.PkScript
322
}
323

324
// NewSpendRequest creates a request for a spend notification of either an
325
// outpoint or output script. A nil outpoint or an allocated ZeroOutPoint can be
326
// used to dispatch the confirmation notification on the script.
327
func NewSpendRequest(op *wire.OutPoint, pkScript []byte) (SpendRequest, error) {
3✔
328
        var r SpendRequest
3✔
329
        outputScript, err := txscript.ParsePkScript(pkScript)
3✔
330
        if err != nil {
3✔
331
                return r, err
×
332
        }
×
333

334
        // We'll only set an outpoint for which we'll dispatch a spend
335
        // notification on this request if one was provided. Otherwise, we'll
336
        // default to dispatching on the spend of the script instead.
337
        if op != nil {
6✔
338
                r.OutPoint = *op
3✔
339
        }
3✔
340
        r.PkScript = outputScript
3✔
341

3✔
342
        // For Taproot spends we have the main problem that for the key spend
3✔
343
        // path we cannot derive the pkScript from only looking at the input's
3✔
344
        // witness. So we need to rely on the outpoint information alone.
3✔
345
        //
3✔
346
        // TODO(guggero): For script path spends we can derive the pkScript from
3✔
347
        // the witness, since we have the full control block and the spent
3✔
348
        // script available.
3✔
349
        if outputScript.Class() == txscript.WitnessV1TaprootTy {
6✔
350
                if op == nil {
6✔
351
                        return r, fmt.Errorf("cannot register witness v1 " +
3✔
352
                                "spend request without outpoint")
3✔
353
                }
3✔
354

355
                // We have an outpoint, so we can set the pkScript to an all
356
                // zero Taproot key that we'll compare this spend request to.
357
                r.PkScript = ZeroTaprootPkScript
3✔
358
        }
359

360
        return r, nil
3✔
361
}
362

363
// String returns the string representation of the SpendRequest.
364
func (r SpendRequest) String() string {
3✔
365
        if r.OutPoint != ZeroOutPoint {
6✔
366
                return fmt.Sprintf("outpoint=%v, script=%v", r.OutPoint,
3✔
367
                        r.PkScript)
3✔
368
        }
3✔
369
        return fmt.Sprintf("outpoint=<zero>, script=%v", r.PkScript)
×
370
}
371

372
// MatchesTx determines whether the given transaction satisfies the spend
373
// request. If the spend request is for an outpoint, then we'll check all of
374
// the outputs being spent by the inputs of the transaction to determine if it
375
// matches. Otherwise, we'll need to match on the output script being spent, so
376
// we'll recompute it for each input of the transaction to determine if it
377
// matches.
378
func (r SpendRequest) MatchesTx(tx *wire.MsgTx) (bool, uint32, error) {
1✔
379
        if r.OutPoint != ZeroOutPoint {
2✔
380
                for i, txIn := range tx.TxIn {
2✔
381
                        if txIn.PreviousOutPoint == r.OutPoint {
2✔
382
                                return true, uint32(i), nil
1✔
383
                        }
1✔
384
                }
385

386
                return false, 0, nil
1✔
387
        }
388

UNCOV
389
        for i, txIn := range tx.TxIn {
×
UNCOV
390
                pkScript, err := txscript.ComputePkScript(
×
UNCOV
391
                        txIn.SignatureScript, txIn.Witness,
×
UNCOV
392
                )
×
UNCOV
393
                if err == txscript.ErrUnsupportedScriptType {
×
394
                        continue
×
395
                }
UNCOV
396
                if err != nil {
×
397
                        return false, 0, err
×
398
                }
×
399

UNCOV
400
                if bytes.Equal(pkScript.Script(), r.PkScript.Script()) {
×
401
                        return true, uint32(i), nil
×
402
                }
×
403
        }
404

UNCOV
405
        return false, 0, nil
×
406
}
407

408
// SpendNtfn represents a client's request to receive a notification once an
409
// outpoint/output script has been spent on-chain. The client is asynchronously
410
// notified via the SpendEvent channels.
411
type SpendNtfn struct {
412
        // SpendID uniquely identies the spend notification request for the
413
        // specified outpoint/output script.
414
        SpendID uint64
415

416
        // SpendRequest represents either the outpoint or script we should
417
        // detect the spend of.
418
        SpendRequest
419

420
        // Event contains references to the channels that the notifications are
421
        // to be sent over.
422
        Event *SpendEvent
423

424
        // HeightHint is the earliest height in the chain that we expect to find
425
        // the spending transaction of the specified outpoint/output script.
426
        // This value will be overridden by the spend hint cache if it contains
427
        // an entry for it.
428
        HeightHint uint32
429

430
        // dispatched signals whether a spend notification has been dispatched
431
        // to the client.
432
        dispatched bool
433
}
434

435
// HistoricalSpendDispatch parametrizes a manual rescan to determine the
436
// spending details (if any) of an outpoint/output script. The parameters
437
// include the start and end block heights specifying the range of blocks to
438
// scan.
439
type HistoricalSpendDispatch struct {
440
        // SpendRequest represents either the outpoint or script we should
441
        // detect the spend of.
442
        SpendRequest
443

444
        // StartHeight specified the block height at which to begin the
445
        // historical rescan.
446
        StartHeight uint32
447

448
        // EndHeight specifies the last block height (inclusive) that the
449
        // historical rescan should consider.
450
        EndHeight uint32
451
}
452

453
// SpendRegistration encompasses all of the information required for callers to
454
// retrieve details about a spend event.
455
type SpendRegistration struct {
456
        // Event contains references to the channels that the notifications are
457
        // to be sent over.
458
        Event *SpendEvent
459

460
        // HistoricalDispatch, if non-nil, signals to the client who registered
461
        // the notification that they are responsible for attempting to manually
462
        // rescan blocks for the txid/output script between the start and end
463
        // heights.
464
        HistoricalDispatch *HistoricalSpendDispatch
465

466
        // Height is the height of the TxNotifier at the time the spend
467
        // notification was registered. This can be used so that backends can
468
        // request to be notified of spends from this point forwards.
469
        Height uint32
470
}
471

472
// TxNotifier is a struct responsible for delivering transaction notifications
473
// to subscribers. These notifications can be of two different types:
474
// transaction/output script confirmations and/or outpoint/output script spends.
475
// The TxNotifier will watch the blockchain as new blocks come in, in order to
476
// satisfy its client requests.
477
type TxNotifier struct {
478
        confClientCounter  uint64 // To be used atomically.
479
        spendClientCounter uint64 // To be used atomically.
480

481
        // currentHeight is the height of the tracked blockchain. It is used to
482
        // determine the number of confirmations a tx has and ensure blocks are
483
        // connected and disconnected in order.
484
        currentHeight uint32
485

486
        // reorgSafetyLimit is the chain depth beyond which it is assumed a
487
        // block will not be reorganized out of the chain. This is used to
488
        // determine when to prune old notification requests so that reorgs are
489
        // handled correctly. The coinbase maturity period is a reasonable value
490
        // to use.
491
        reorgSafetyLimit uint32
492

493
        // reorgDepth is the depth of a chain organization that this system is
494
        // being informed of. This is incremented as long as a sequence of
495
        // blocks are disconnected without being interrupted by a new block.
496
        reorgDepth uint32
497

498
        // confNotifications is an index of confirmation notification requests
499
        // by transaction hash/output script.
500
        confNotifications map[ConfRequest]*confNtfnSet
501

502
        // confsByInitialHeight is an index of watched transactions/output
503
        // scripts by the height that they are included at in the chain. This
504
        // is tracked so that incorrect notifications are not sent if a
505
        // transaction/output script is reorged out of the chain and so that
506
        // negative confirmations can be recognized.
507
        confsByInitialHeight map[uint32]map[ConfRequest]struct{}
508

509
        // ntfnsByConfirmHeight is an index of notification requests by the
510
        // height at which the transaction/output script will have sufficient
511
        // confirmations.
512
        ntfnsByConfirmHeight map[uint32]map[*ConfNtfn]struct{}
513

514
        // spendNotifications is an index of all active notification requests
515
        // per outpoint/output script.
516
        spendNotifications map[SpendRequest]*spendNtfnSet
517

518
        // spendsByHeight is an index that keeps tracks of the spending height
519
        // of outpoints/output scripts we are currently tracking notifications
520
        // for. This is used in order to recover from spending transactions
521
        // being reorged out of the chain.
522
        spendsByHeight map[uint32]map[SpendRequest]struct{}
523

524
        // confirmHintCache is a cache used to maintain the latest height hints
525
        // for transactions/output scripts. Each height hint represents the
526
        // earliest height at which they scripts could have been confirmed
527
        // within the chain.
528
        confirmHintCache ConfirmHintCache
529

530
        // spendHintCache is a cache used to maintain the latest height hints
531
        // for outpoints/output scripts. Each height hint represents the
532
        // earliest height at which they could have been spent within the chain.
533
        spendHintCache SpendHintCache
534

535
        // quit is closed in order to signal that the notifier is gracefully
536
        // exiting.
537
        quit chan struct{}
538

539
        sync.Mutex
540
}
541

542
// NewTxNotifier creates a TxNotifier. The current height of the blockchain is
543
// accepted as a parameter. The different hint caches (confirm and spend) are
544
// used as an optimization in order to retrieve a better starting point when
545
// dispatching a rescan for a historical event in the chain.
546
func NewTxNotifier(startHeight uint32, reorgSafetyLimit uint32,
547
        confirmHintCache ConfirmHintCache,
548
        spendHintCache SpendHintCache) *TxNotifier {
3✔
549

3✔
550
        return &TxNotifier{
3✔
551
                currentHeight:        startHeight,
3✔
552
                reorgSafetyLimit:     reorgSafetyLimit,
3✔
553
                confNotifications:    make(map[ConfRequest]*confNtfnSet),
3✔
554
                confsByInitialHeight: make(map[uint32]map[ConfRequest]struct{}),
3✔
555
                ntfnsByConfirmHeight: make(map[uint32]map[*ConfNtfn]struct{}),
3✔
556
                spendNotifications:   make(map[SpendRequest]*spendNtfnSet),
3✔
557
                spendsByHeight:       make(map[uint32]map[SpendRequest]struct{}),
3✔
558
                confirmHintCache:     confirmHintCache,
3✔
559
                spendHintCache:       spendHintCache,
3✔
560
                quit:                 make(chan struct{}),
3✔
561
        }
3✔
562
}
3✔
563

564
// newConfNtfn validates all of the parameters required to successfully create
565
// and register a confirmation notification.
566
func (n *TxNotifier) newConfNtfn(txid *chainhash.Hash,
567
        pkScript []byte, numConfs, heightHint uint32,
568
        opts *notifierOptions) (*ConfNtfn, error) {
3✔
569

3✔
570
        // An accompanying output script must always be provided.
3✔
571
        if len(pkScript) == 0 {
3✔
UNCOV
572
                return nil, ErrNoScript
×
UNCOV
573
        }
×
574

575
        // Enforce that we will not dispatch confirmations beyond the reorg
576
        // safety limit.
577
        if numConfs == 0 || numConfs > n.reorgSafetyLimit {
3✔
UNCOV
578
                return nil, ErrNumConfsOutOfRange
×
UNCOV
579
        }
×
580

581
        // A height hint must be provided to prevent scanning from the genesis
582
        // block.
583
        if heightHint == 0 {
3✔
UNCOV
584
                return nil, ErrNoHeightHint
×
UNCOV
585
        }
×
586

587
        // Ensure the output script is of a supported type.
588
        confRequest, err := NewConfRequest(txid, pkScript)
3✔
589
        if err != nil {
3✔
590
                return nil, err
×
591
        }
×
592

593
        confID := atomic.AddUint64(&n.confClientCounter, 1)
3✔
594
        return &ConfNtfn{
3✔
595
                ConfID:           confID,
3✔
596
                ConfRequest:      confRequest,
3✔
597
                NumConfirmations: numConfs,
3✔
598
                Event: NewConfirmationEvent(numConfs, func() {
6✔
599
                        n.CancelConf(confRequest, confID)
3✔
600
                }),
3✔
601
                HeightHint:       heightHint,
602
                includeBlock:     opts.includeBlock,
603
                allConfirmations: opts.allConfirmations,
604
                numConfsLeft:     numConfs,
605
        }, nil
606
}
607

608
// RegisterConf handles a new confirmation notification request. The client will
609
// be notified when the transaction/output script gets a sufficient number of
610
// confirmations in the blockchain.
611
//
612
// NOTE: If the transaction/output script has already been included in a block
613
// on the chain, the confirmation details must be provided with the
614
// UpdateConfDetails method, otherwise we will wait for the transaction/output
615
// script to confirm even though it already has.
616
func (n *TxNotifier) RegisterConf(txid *chainhash.Hash, pkScript []byte,
617
        numConfs, heightHint uint32,
618
        optFuncs ...NotifierOption) (*ConfRegistration, error) {
3✔
619

3✔
620
        select {
3✔
UNCOV
621
        case <-n.quit:
×
UNCOV
622
                return nil, ErrTxNotifierExiting
×
623
        default:
3✔
624
        }
625

626
        opts := defaultNotifierOptions()
3✔
627
        for _, optFunc := range optFuncs {
6✔
628
                optFunc(opts)
3✔
629
        }
3✔
630

631
        // We'll start by performing a series of validation checks.
632
        ntfn, err := n.newConfNtfn(txid, pkScript, numConfs, heightHint, opts)
3✔
633
        if err != nil {
3✔
UNCOV
634
                return nil, err
×
UNCOV
635
        }
×
636

637
        // Before proceeding to register the notification, we'll query our
638
        // height hint cache to determine whether a better one exists.
639
        //
640
        // TODO(conner): verify that all submitted height hints are identical.
641
        startHeight := ntfn.HeightHint
3✔
642
        hint, err := n.confirmHintCache.QueryConfirmHint(ntfn.ConfRequest)
3✔
643
        if err == nil {
6✔
644
                if hint > startHeight {
6✔
645
                        Log.Debugf("Using height hint %d retrieved from cache "+
3✔
646
                                "for %v instead of %d for conf subscription",
3✔
647
                                hint, ntfn.ConfRequest, startHeight)
3✔
648
                        startHeight = hint
3✔
649
                }
3✔
650
        } else if err != ErrConfirmHintNotFound {
3✔
651
                Log.Errorf("Unable to query confirm hint for %v: %v",
×
652
                        ntfn.ConfRequest, err)
×
653
        }
×
654

655
        Log.Infof("New confirmation subscription: conf_id=%d, %v, "+
3✔
656
                "num_confs=%v height_hint=%d", ntfn.ConfID, ntfn.ConfRequest,
3✔
657
                numConfs, startHeight)
3✔
658

3✔
659
        n.Lock()
3✔
660
        defer n.Unlock()
3✔
661

3✔
662
        confSet, ok := n.confNotifications[ntfn.ConfRequest]
3✔
663
        if !ok {
6✔
664
                // If this is the first registration for this request, construct
3✔
665
                // a confSet to coalesce all notifications for the same request.
3✔
666
                confSet = newConfNtfnSet()
3✔
667
                n.confNotifications[ntfn.ConfRequest] = confSet
3✔
668
        }
3✔
669
        confSet.ntfns[ntfn.ConfID] = ntfn
3✔
670

3✔
671
        switch confSet.rescanStatus {
3✔
672

673
        // A prior rescan has already completed and we are actively watching at
674
        // tip for this request.
675
        case rescanComplete:
3✔
676
                // If the confirmation details for this set of notifications has
3✔
677
                // already been found, we'll attempt to deliver them immediately
3✔
678
                // to this client.
3✔
679
                Log.Debugf("Attempting to dispatch confirmation for %v on "+
3✔
680
                        "registration since rescan has finished, conf_id=%v",
3✔
681
                        ntfn.ConfRequest, ntfn.ConfID)
3✔
682

3✔
683
                // The default notification we assigned above includes the
3✔
684
                // block along with the rest of the details. However not all
3✔
685
                // clients want the block, so we make a copy here w/o the block
3✔
686
                // if needed so we can give clients only what they ask for.
3✔
687
                confDetails := confSet.details
3✔
688
                if !ntfn.includeBlock && confDetails != nil {
6✔
689
                        confDetailsCopy := *confDetails
3✔
690
                        confDetailsCopy.Block = nil
3✔
691

3✔
692
                        confDetails = &confDetailsCopy
3✔
693
                }
3✔
694

695
                // Deliver the details to the whole conf set where this ntfn
696
                // lives in.
697
                for _, subscriber := range confSet.ntfns {
6✔
698
                        err := n.dispatchConfDetails(subscriber, confDetails)
3✔
699
                        if err != nil {
3✔
700
                                return nil, err
×
701
                        }
×
702
                }
703

704
                return &ConfRegistration{
3✔
705
                        Event:              ntfn.Event,
3✔
706
                        HistoricalDispatch: nil,
3✔
707
                        Height:             n.currentHeight,
3✔
708
                }, nil
3✔
709

710
        // A rescan is already in progress, return here to prevent dispatching
711
        // another. When the rescan returns, this notification's details will be
712
        // updated as well.
713
        case rescanPending:
3✔
714
                Log.Debugf("Waiting for pending rescan to finish before "+
3✔
715
                        "notifying %v at tip", ntfn.ConfRequest)
3✔
716

3✔
717
                return &ConfRegistration{
3✔
718
                        Event:              ntfn.Event,
3✔
719
                        HistoricalDispatch: nil,
3✔
720
                        Height:             n.currentHeight,
3✔
721
                }, nil
3✔
722

723
        // If no rescan has been dispatched, attempt to do so now.
724
        case rescanNotStarted:
3✔
725
        }
726

727
        // If the provided or cached height hint indicates that the
728
        // transaction with the given txid/output script is to be confirmed at a
729
        // height greater than the notifier's current height, we'll refrain from
730
        // spawning a historical dispatch.
731
        if startHeight > n.currentHeight {
5✔
732
                Log.Debugf("Height hint is above current height, not "+
2✔
733
                        "dispatching historical confirmation rescan for %v",
2✔
734
                        ntfn.ConfRequest)
2✔
735

2✔
736
                // Set the rescan status to complete, which will allow the
2✔
737
                // notifier to start delivering messages for this set
2✔
738
                // immediately.
2✔
739
                confSet.rescanStatus = rescanComplete
2✔
740
                return &ConfRegistration{
2✔
741
                        Event:              ntfn.Event,
2✔
742
                        HistoricalDispatch: nil,
2✔
743
                        Height:             n.currentHeight,
2✔
744
                }, nil
2✔
745
        }
2✔
746

747
        Log.Debugf("Dispatching historical confirmation rescan for %v",
3✔
748
                ntfn.ConfRequest)
3✔
749

3✔
750
        // Construct the parameters for historical dispatch, scanning the range
3✔
751
        // of blocks between our best known height hint and the notifier's
3✔
752
        // current height. The notifier will begin also watching for
3✔
753
        // confirmations at tip starting with the next block.
3✔
754
        dispatch := &HistoricalConfDispatch{
3✔
755
                ConfRequest: ntfn.ConfRequest,
3✔
756
                StartHeight: startHeight,
3✔
757
                EndHeight:   n.currentHeight,
3✔
758
        }
3✔
759

3✔
760
        // Set this confSet's status to pending, ensuring subsequent
3✔
761
        // registrations don't also attempt a dispatch.
3✔
762
        confSet.rescanStatus = rescanPending
3✔
763

3✔
764
        return &ConfRegistration{
3✔
765
                Event:              ntfn.Event,
3✔
766
                HistoricalDispatch: dispatch,
3✔
767
                Height:             n.currentHeight,
3✔
768
        }, nil
3✔
769
}
770

771
// CancelConf cancels an existing request for a spend notification of an
772
// outpoint/output script. The request is identified by its spend ID.
773
func (n *TxNotifier) CancelConf(confRequest ConfRequest, confID uint64) {
3✔
774
        select {
3✔
775
        case <-n.quit:
×
776
                return
×
777
        default:
3✔
778
        }
779

780
        n.Lock()
3✔
781
        defer n.Unlock()
3✔
782

3✔
783
        confSet, ok := n.confNotifications[confRequest]
3✔
784
        if !ok {
3✔
785
                return
×
786
        }
×
787
        ntfn, ok := confSet.ntfns[confID]
3✔
788
        if !ok {
3✔
789
                return
×
790
        }
×
791

792
        Log.Debugf("Canceling confirmation notification: conf_id=%d, %v",
3✔
793
                confID, confRequest)
3✔
794

3✔
795
        // We'll close all the notification channels to let the client know
3✔
796
        // their cancel request has been fulfilled.
3✔
797
        close(ntfn.Event.Confirmed)
3✔
798
        close(ntfn.Event.NegativeConf)
3✔
799

3✔
800
        // Finally, we'll clean up any lingering references to this
3✔
801
        // notification.
3✔
802
        delete(confSet.ntfns, confID)
3✔
803

3✔
804
        // Remove the queued confirmation notification if the transaction has
3✔
805
        // already confirmed, but hasn't met its required number of
3✔
806
        // confirmations.
3✔
807
        if confSet.details != nil {
6✔
808
                confHeight := confSet.details.BlockHeight +
3✔
809
                        ntfn.NumConfirmations - 1
3✔
810
                delete(n.ntfnsByConfirmHeight[confHeight], ntfn)
3✔
811
        }
3✔
812
}
813

814
// UpdateConfDetails attempts to update the confirmation details for an active
815
// notification within the notifier. This should only be used in the case of a
816
// transaction/output script that has confirmed before the notifier's current
817
// height.
818
//
819
// NOTE: The notification should be registered first to ensure notifications are
820
// dispatched correctly.
821
func (n *TxNotifier) UpdateConfDetails(confRequest ConfRequest,
822
        details *TxConfirmation) error {
3✔
823

3✔
824
        select {
3✔
825
        case <-n.quit:
×
826
                return ErrTxNotifierExiting
×
827
        default:
3✔
828
        }
829

830
        // Ensure we hold the lock throughout handling the notification to
831
        // prevent the notifier from advancing its height underneath us.
832
        n.Lock()
3✔
833
        defer n.Unlock()
3✔
834

3✔
835
        // First, we'll determine whether we have an active confirmation
3✔
836
        // notification for the given txid/script.
3✔
837
        confSet, ok := n.confNotifications[confRequest]
3✔
838
        if !ok {
3✔
839
                return fmt.Errorf("confirmation notification for %v not found",
×
840
                        confRequest)
×
841
        }
×
842

843
        // If the confirmation details were already found at tip, all existing
844
        // notifications will have been dispatched or queued for dispatch. We
845
        // can exit early to avoid sending too many notifications on the
846
        // buffered channels.
847
        if confSet.details != nil {
4✔
848
                return nil
1✔
849
        }
1✔
850

851
        // The historical dispatch has been completed for this confSet. We'll
852
        // update the rescan status and cache any details that were found. If
853
        // the details are nil, that implies we did not find them and will
854
        // continue to watch for them at tip.
855
        confSet.rescanStatus = rescanComplete
3✔
856

3✔
857
        // The notifier has yet to reach the height at which the
3✔
858
        // transaction/output script was included in a block, so we should defer
3✔
859
        // until handling it then within ConnectTip.
3✔
860
        if details == nil {
6✔
861
                Log.Debugf("Confirmation details for %v not found during "+
3✔
862
                        "historical dispatch, waiting to dispatch at tip",
3✔
863
                        confRequest)
3✔
864

3✔
865
                // We'll commit the current height as the confirm hint to
3✔
866
                // prevent another potentially long rescan if we restart before
3✔
867
                // a new block comes in.
3✔
868
                err := n.confirmHintCache.CommitConfirmHint(
3✔
869
                        n.currentHeight, confRequest,
3✔
870
                )
3✔
871
                if err != nil {
3✔
872
                        // The error is not fatal as this is an optimistic
×
873
                        // optimization, so we'll avoid returning an error.
×
874
                        Log.Debugf("Unable to update confirm hint to %d for "+
×
875
                                "%v: %v", n.currentHeight, confRequest, err)
×
876
                }
×
877

878
                return nil
3✔
879
        }
880

881
        if details.BlockHeight > n.currentHeight {
3✔
UNCOV
882
                Log.Debugf("Confirmation details for %v found above current "+
×
UNCOV
883
                        "height, waiting to dispatch at tip", confRequest)
×
UNCOV
884

×
UNCOV
885
                return nil
×
UNCOV
886
        }
×
887

888
        Log.Debugf("Updating confirmation details for %v", confRequest)
3✔
889

3✔
890
        err := n.confirmHintCache.CommitConfirmHint(
3✔
891
                details.BlockHeight, confRequest,
3✔
892
        )
3✔
893
        if err != nil {
3✔
894
                // The error is not fatal, so we should not return an error to
×
895
                // the caller.
×
896
                Log.Errorf("Unable to update confirm hint to %d for %v: %v",
×
897
                        details.BlockHeight, confRequest, err)
×
898
        }
×
899

900
        // Cache the details found in the rescan and attempt to dispatch any
901
        // notifications that have not yet been delivered.
902
        confSet.details = details
3✔
903
        for _, ntfn := range confSet.ntfns {
6✔
904
                // The default notification we assigned above includes the
3✔
905
                // block along with the rest of the details. However not all
3✔
906
                // clients want the block, so we make a copy here w/o the block
3✔
907
                // if needed so we can give clients only what they ask for.
3✔
908
                confDetails := *details
3✔
909
                if !ntfn.includeBlock {
6✔
910
                        confDetails.Block = nil
3✔
911
                }
3✔
912

913
                err = n.dispatchConfDetails(ntfn, &confDetails)
3✔
914
                if err != nil {
3✔
915
                        return err
×
916
                }
×
917
        }
918

919
        return nil
3✔
920
}
921

922
// dispatchConfDetails attempts to cache and dispatch details to a particular
923
// client if the transaction/output script has sufficiently confirmed. If the
924
// provided details are nil, this method will be a no-op.
925
func (n *TxNotifier) dispatchConfDetails(
926
        ntfn *ConfNtfn, details *TxConfirmation) error {
3✔
927

3✔
928
        // If there are no conf details to dispatch or if the notification has
3✔
929
        // already been dispatched, then we can skip dispatching to this
3✔
930
        // client.
3✔
931
        if details == nil {
6✔
932
                Log.Debugf("Skipped dispatching nil conf details for request "+
3✔
933
                        "%v, conf_id=%v", ntfn.ConfRequest, ntfn.ConfID)
3✔
934

3✔
935
                return nil
3✔
936
        }
3✔
937

938
        if ntfn.dispatched {
6✔
939
                Log.Debugf("Skipped dispatched conf details for request %v "+
3✔
940
                        "conf_id=%v", ntfn.ConfRequest, ntfn.ConfID)
3✔
941

3✔
942
                return nil
3✔
943
        }
3✔
944

945
        // Now, we'll examine whether the transaction/output script of this
946
        // request has reached its required number of confirmations. If it has,
947
        // we'll dispatch a confirmation notification to the caller.
948
        confHeight := details.BlockHeight + ntfn.NumConfirmations - 1
3✔
949
        if confHeight <= n.currentHeight {
6✔
950
                Log.Debugf("Dispatching %v confirmation notification for "+
3✔
951
                        "conf_id=%v, %v", ntfn.NumConfirmations, ntfn.ConfID,
3✔
952
                        ntfn.ConfRequest)
3✔
953

3✔
954
                // Update the number of confirmations left to the notification.
3✔
955
                ntfn.numConfsLeft = 0
3✔
956

3✔
957
                select {
3✔
958
                case ntfn.Event.Confirmed <- details:
3✔
959
                        ntfn.dispatched = true
3✔
960
                case <-n.quit:
×
961
                        return ErrTxNotifierExiting
×
962
                }
963
        } else {
3✔
964
                Log.Debugf("Queueing %v confirmation notification for %v at "+
3✔
965
                        "tip", ntfn.NumConfirmations, ntfn.ConfRequest)
3✔
966

3✔
967
                // Otherwise, we'll keep track of the notification
3✔
968
                // request by the height at which we should dispatch the
3✔
969
                // confirmation notification.
3✔
970
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
3✔
971
                if !exists {
6✔
972
                        ntfnSet = make(map[*ConfNtfn]struct{})
3✔
973
                        n.ntfnsByConfirmHeight[confHeight] = ntfnSet
3✔
974
                }
3✔
975
                ntfnSet[ntfn] = struct{}{}
3✔
976

3✔
977
                // We'll also send an update to the client of how many
3✔
978
                // confirmations are left for the transaction/output script to
3✔
979
                // be confirmed.
3✔
980
                numConfsLeft := confHeight - n.currentHeight
3✔
981
                err := n.notifyConfsUpdate(ntfn, numConfsLeft, *details)
3✔
982
                if err != nil {
3✔
983
                        return err
×
984
                }
×
985
        }
986

987
        // As a final check, we'll also watch the transaction/output script if
988
        // it's still possible for it to get reorged out of the chain.
989
        reorgSafeHeight := details.BlockHeight + n.reorgSafetyLimit
3✔
990
        if reorgSafeHeight > n.currentHeight {
6✔
991
                txSet, exists := n.confsByInitialHeight[details.BlockHeight]
3✔
992
                if !exists {
6✔
993
                        txSet = make(map[ConfRequest]struct{})
3✔
994
                        n.confsByInitialHeight[details.BlockHeight] = txSet
3✔
995
                }
3✔
996
                txSet[ntfn.ConfRequest] = struct{}{}
3✔
997
        }
998

999
        return nil
3✔
1000
}
1001

1002
// newSpendNtfn validates all of the parameters required to successfully create
1003
// and register a spend notification.
1004
func (n *TxNotifier) newSpendNtfn(outpoint *wire.OutPoint,
1005
        pkScript []byte, heightHint uint32) (*SpendNtfn, error) {
3✔
1006

3✔
1007
        // An accompanying output script must always be provided.
3✔
1008
        if len(pkScript) == 0 {
3✔
UNCOV
1009
                return nil, ErrNoScript
×
UNCOV
1010
        }
×
1011

1012
        // A height hint must be provided to prevent scanning from the genesis
1013
        // block.
1014
        if heightHint == 0 {
3✔
UNCOV
1015
                return nil, ErrNoHeightHint
×
UNCOV
1016
        }
×
1017

1018
        // Ensure the output script is of a supported type.
1019
        spendRequest, err := NewSpendRequest(outpoint, pkScript)
3✔
1020
        if err != nil {
6✔
1021
                return nil, err
3✔
1022
        }
3✔
1023

1024
        spendID := atomic.AddUint64(&n.spendClientCounter, 1)
3✔
1025
        return &SpendNtfn{
3✔
1026
                SpendID:      spendID,
3✔
1027
                SpendRequest: spendRequest,
3✔
1028
                Event: NewSpendEvent(func() {
6✔
1029
                        n.CancelSpend(spendRequest, spendID)
3✔
1030
                }),
3✔
1031
                HeightHint: heightHint,
1032
        }, nil
1033
}
1034

1035
// RegisterSpend handles a new spend notification request. The client will be
1036
// notified once the outpoint/output script is detected as spent within the
1037
// chain.
1038
//
1039
// NOTE: If the outpoint/output script has already been spent within the chain
1040
// before the notifier's current tip, the spend details must be provided with
1041
// the UpdateSpendDetails method, otherwise we will wait for the outpoint/output
1042
// script to be spent at tip, even though it already has.
1043
func (n *TxNotifier) RegisterSpend(outpoint *wire.OutPoint, pkScript []byte,
1044
        heightHint uint32) (*SpendRegistration, error) {
3✔
1045

3✔
1046
        select {
3✔
UNCOV
1047
        case <-n.quit:
×
UNCOV
1048
                return nil, ErrTxNotifierExiting
×
1049
        default:
3✔
1050
        }
1051

1052
        // We'll start by performing a series of validation checks.
1053
        ntfn, err := n.newSpendNtfn(outpoint, pkScript, heightHint)
3✔
1054
        if err != nil {
6✔
1055
                return nil, err
3✔
1056
        }
3✔
1057

1058
        // Before proceeding to register the notification, we'll query our spend
1059
        // hint cache to determine whether a better one exists.
1060
        startHeight := ntfn.HeightHint
3✔
1061
        hint, err := n.spendHintCache.QuerySpendHint(ntfn.SpendRequest)
3✔
1062
        if err == nil {
6✔
1063
                if hint > startHeight {
6✔
1064
                        Log.Debugf("Using height hint %d retrieved from cache "+
3✔
1065
                                "for %v instead of %d for spend subscription",
3✔
1066
                                hint, ntfn.SpendRequest, startHeight)
3✔
1067
                        startHeight = hint
3✔
1068
                }
3✔
1069
        } else if err != ErrSpendHintNotFound {
3✔
1070
                Log.Errorf("Unable to query spend hint for %v: %v",
×
1071
                        ntfn.SpendRequest, err)
×
1072
        }
×
1073

1074
        n.Lock()
3✔
1075
        defer n.Unlock()
3✔
1076

3✔
1077
        Log.Debugf("New spend subscription: spend_id=%d, %v, height_hint=%d",
3✔
1078
                ntfn.SpendID, ntfn.SpendRequest, startHeight)
3✔
1079

3✔
1080
        // Keep track of the notification request so that we can properly
3✔
1081
        // dispatch a spend notification later on.
3✔
1082
        spendSet, ok := n.spendNotifications[ntfn.SpendRequest]
3✔
1083
        if !ok {
6✔
1084
                // If this is the first registration for the request, we'll
3✔
1085
                // construct a spendNtfnSet to coalesce all notifications.
3✔
1086
                spendSet = newSpendNtfnSet()
3✔
1087
                n.spendNotifications[ntfn.SpendRequest] = spendSet
3✔
1088
        }
3✔
1089
        spendSet.ntfns[ntfn.SpendID] = ntfn
3✔
1090

3✔
1091
        // We'll now let the caller know whether a historical rescan is needed
3✔
1092
        // depending on the current rescan status.
3✔
1093
        switch spendSet.rescanStatus {
3✔
1094

1095
        // If the spending details for this request have already been determined
1096
        // and cached, then we can use them to immediately dispatch the spend
1097
        // notification to the client.
1098
        case rescanComplete:
3✔
1099
                Log.Debugf("Attempting to dispatch spend for %v on "+
3✔
1100
                        "registration since rescan has finished",
3✔
1101
                        ntfn.SpendRequest)
3✔
1102

3✔
1103
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1104
                if err != nil {
3✔
1105
                        return nil, err
×
1106
                }
×
1107

1108
                return &SpendRegistration{
3✔
1109
                        Event:              ntfn.Event,
3✔
1110
                        HistoricalDispatch: nil,
3✔
1111
                        Height:             n.currentHeight,
3✔
1112
                }, nil
3✔
1113

1114
        // If there is an active rescan to determine whether the request has
1115
        // been spent, then we won't trigger another one.
1116
        case rescanPending:
3✔
1117
                Log.Debugf("Waiting for pending rescan to finish before "+
3✔
1118
                        "notifying %v at tip", ntfn.SpendRequest)
3✔
1119

3✔
1120
                return &SpendRegistration{
3✔
1121
                        Event:              ntfn.Event,
3✔
1122
                        HistoricalDispatch: nil,
3✔
1123
                        Height:             n.currentHeight,
3✔
1124
                }, nil
3✔
1125

1126
        // Otherwise, we'll fall through and let the caller know that a rescan
1127
        // should be dispatched to determine whether the request has already
1128
        // been spent.
1129
        case rescanNotStarted:
3✔
1130
        }
1131

1132
        // However, if the spend hint, either provided by the caller or
1133
        // retrieved from the cache, is found to be at a later height than the
1134
        // TxNotifier is aware of, then we'll refrain from dispatching a
1135
        // historical rescan and wait for the spend to come in at tip.
1136
        if startHeight > n.currentHeight {
3✔
UNCOV
1137
                Log.Debugf("Spend hint of %d for %v is above current height %d",
×
UNCOV
1138
                        startHeight, ntfn.SpendRequest, n.currentHeight)
×
UNCOV
1139

×
UNCOV
1140
                // We'll also set the rescan status as complete to ensure that
×
UNCOV
1141
                // spend hints for this request get updated upon
×
UNCOV
1142
                // connected/disconnected blocks.
×
UNCOV
1143
                spendSet.rescanStatus = rescanComplete
×
UNCOV
1144
                return &SpendRegistration{
×
UNCOV
1145
                        Event:              ntfn.Event,
×
UNCOV
1146
                        HistoricalDispatch: nil,
×
UNCOV
1147
                        Height:             n.currentHeight,
×
UNCOV
1148
                }, nil
×
UNCOV
1149
        }
×
1150

1151
        // We'll set the rescan status to pending to ensure subsequent
1152
        // notifications don't also attempt a historical dispatch.
1153
        spendSet.rescanStatus = rescanPending
3✔
1154

3✔
1155
        Log.Debugf("Dispatching historical spend rescan for %v, start=%d, "+
3✔
1156
                "end=%d", ntfn.SpendRequest, startHeight, n.currentHeight)
3✔
1157

3✔
1158
        return &SpendRegistration{
3✔
1159
                Event: ntfn.Event,
3✔
1160
                HistoricalDispatch: &HistoricalSpendDispatch{
3✔
1161
                        SpendRequest: ntfn.SpendRequest,
3✔
1162
                        StartHeight:  startHeight,
3✔
1163
                        EndHeight:    n.currentHeight,
3✔
1164
                },
3✔
1165
                Height: n.currentHeight,
3✔
1166
        }, nil
3✔
1167
}
1168

1169
// CancelSpend cancels an existing request for a spend notification of an
1170
// outpoint/output script. The request is identified by its spend ID.
1171
func (n *TxNotifier) CancelSpend(spendRequest SpendRequest, spendID uint64) {
3✔
1172
        select {
3✔
1173
        case <-n.quit:
3✔
1174
                return
3✔
1175
        default:
3✔
1176
        }
1177

1178
        n.Lock()
3✔
1179
        defer n.Unlock()
3✔
1180

3✔
1181
        spendSet, ok := n.spendNotifications[spendRequest]
3✔
1182
        if !ok {
3✔
1183
                return
×
1184
        }
×
1185
        ntfn, ok := spendSet.ntfns[spendID]
3✔
1186
        if !ok {
3✔
1187
                return
×
1188
        }
×
1189

1190
        Log.Debugf("Canceling spend notification: spend_id=%d, %v", spendID,
3✔
1191
                spendRequest)
3✔
1192

3✔
1193
        // We'll close all the notification channels to let the client know
3✔
1194
        // their cancel request has been fulfilled.
3✔
1195
        close(ntfn.Event.Spend)
3✔
1196
        close(ntfn.Event.Reorg)
3✔
1197
        close(ntfn.Event.Done)
3✔
1198
        delete(spendSet.ntfns, spendID)
3✔
1199
}
1200

1201
// ProcessRelevantSpendTx processes a transaction provided externally. This will
1202
// check whether the transaction is relevant to the notifier if it spends any
1203
// outpoints/output scripts for which we currently have registered notifications
1204
// for. If it is relevant, spend notifications will be dispatched to the caller.
1205
func (n *TxNotifier) ProcessRelevantSpendTx(tx *btcutil.Tx,
1206
        blockHeight uint32) error {
3✔
1207

3✔
1208
        select {
3✔
1209
        case <-n.quit:
×
1210
                return ErrTxNotifierExiting
×
1211
        default:
3✔
1212
        }
1213

1214
        // Ensure we hold the lock throughout handling the notification to
1215
        // prevent the notifier from advancing its height underneath us.
1216
        n.Lock()
3✔
1217
        defer n.Unlock()
3✔
1218

3✔
1219
        // We'll use a channel to coalesce all the spend requests that this
3✔
1220
        // transaction fulfills.
3✔
1221
        type spend struct {
3✔
1222
                request *SpendRequest
3✔
1223
                details *SpendDetail
3✔
1224
        }
3✔
1225

3✔
1226
        // We'll set up the onSpend filter callback to gather all the fulfilled
3✔
1227
        // spends requests within this transaction.
3✔
1228
        var spends []spend
3✔
1229
        onSpend := func(request SpendRequest, details *SpendDetail) {
6✔
1230
                spends = append(spends, spend{&request, details})
3✔
1231
        }
3✔
1232
        n.filterTx(nil, tx, blockHeight, nil, onSpend)
3✔
1233

3✔
1234
        // After the transaction has been filtered, we can finally dispatch
3✔
1235
        // notifications for each request.
3✔
1236
        for _, spend := range spends {
6✔
1237
                err := n.updateSpendDetails(*spend.request, spend.details)
3✔
1238
                if err != nil {
3✔
1239
                        return err
×
1240
                }
×
1241
        }
1242

1243
        return nil
3✔
1244
}
1245

1246
// UpdateSpendDetails attempts to update the spend details for all active spend
1247
// notification requests for an outpoint/output script. This method should be
1248
// used once a historical scan of the chain has finished. If the historical scan
1249
// did not find a spending transaction for it, the spend details may be nil.
1250
//
1251
// NOTE: A notification request for the outpoint/output script must be
1252
// registered first to ensure notifications are delivered.
1253
func (n *TxNotifier) UpdateSpendDetails(spendRequest SpendRequest,
1254
        details *SpendDetail) error {
3✔
1255

3✔
1256
        select {
3✔
1257
        case <-n.quit:
×
1258
                return ErrTxNotifierExiting
×
1259
        default:
3✔
1260
        }
1261

1262
        // Ensure we hold the lock throughout handling the notification to
1263
        // prevent the notifier from advancing its height underneath us.
1264
        n.Lock()
3✔
1265
        defer n.Unlock()
3✔
1266

3✔
1267
        return n.updateSpendDetails(spendRequest, details)
3✔
1268
}
1269

1270
// updateSpendDetails attempts to update the spend details for all active spend
1271
// notification requests for an outpoint/output script. This method should be
1272
// used once a historical scan of the chain has finished. If the historical scan
1273
// did not find a spending transaction for it, the spend details may be nil.
1274
//
1275
// NOTE: This method must be called with the TxNotifier's lock held.
1276
func (n *TxNotifier) updateSpendDetails(spendRequest SpendRequest,
1277
        details *SpendDetail) error {
3✔
1278

3✔
1279
        // Mark the ongoing historical rescan for this request as finished. This
3✔
1280
        // will allow us to update the spend hints for it at tip.
3✔
1281
        spendSet, ok := n.spendNotifications[spendRequest]
3✔
1282
        if !ok {
3✔
UNCOV
1283
                return fmt.Errorf("spend notification for %v not found",
×
UNCOV
1284
                        spendRequest)
×
UNCOV
1285
        }
×
1286

1287
        // If the spend details have already been found either at tip, then the
1288
        // notifications should have already been dispatched, so we can exit
1289
        // early to prevent sending duplicate notifications.
1290
        if spendSet.details != nil {
5✔
1291
                return nil
2✔
1292
        }
2✔
1293

1294
        // Since the historical rescan has completed for this request, we'll
1295
        // mark its rescan status as complete in order to ensure that the
1296
        // TxNotifier can properly update its spend hints upon
1297
        // connected/disconnected blocks.
1298
        spendSet.rescanStatus = rescanComplete
3✔
1299

3✔
1300
        // If the historical rescan was not able to find a spending transaction
3✔
1301
        // for this request, then we can track the spend at tip.
3✔
1302
        if details == nil {
6✔
1303
                // We'll commit the current height as the spend hint to prevent
3✔
1304
                // another potentially long rescan if we restart before a new
3✔
1305
                // block comes in.
3✔
1306
                err := n.spendHintCache.CommitSpendHint(
3✔
1307
                        n.currentHeight, spendRequest,
3✔
1308
                )
3✔
1309
                if err != nil {
3✔
1310
                        // The error is not fatal as this is an optimistic
×
1311
                        // optimization, so we'll avoid returning an error.
×
1312
                        Log.Debugf("Unable to update spend hint to %d for %v: %v",
×
1313
                                n.currentHeight, spendRequest, err)
×
1314
                }
×
1315

1316
                Log.Debugf("Updated spend hint to height=%v for unconfirmed "+
3✔
1317
                        "spend request %v", n.currentHeight, spendRequest)
3✔
1318
                return nil
3✔
1319
        }
1320

1321
        // Return an error if the witness data is not present in the spending
1322
        // transaction.
1323
        //
1324
        // NOTE: if the witness stack is empty, we will do a critical log which
1325
        // shuts down the node.
1326
        if !details.HasSpenderWitness() {
3✔
1327
                Log.Criticalf("Found spending tx for outpoint=%v, but the "+
×
1328
                        "transaction %v does not have witness",
×
1329
                        spendRequest.OutPoint, details.SpendingTx.TxHash())
×
1330

×
1331
                return ErrEmptyWitnessStack
×
1332
        }
×
1333

1334
        // If the historical rescan found the spending transaction for this
1335
        // request, but it's at a later height than the notifier (this can
1336
        // happen due to latency with the backend during a reorg), then we'll
1337
        // defer handling the notification until the notifier has caught up to
1338
        // such height.
1339
        if uint32(details.SpendingHeight) > n.currentHeight {
6✔
1340
                return nil
3✔
1341
        }
3✔
1342

1343
        // Now that we've determined the request has been spent, we'll commit
1344
        // its spending height as its hint in the cache and dispatch
1345
        // notifications to all of its respective clients.
1346
        err := n.spendHintCache.CommitSpendHint(
3✔
1347
                uint32(details.SpendingHeight), spendRequest,
3✔
1348
        )
3✔
1349
        if err != nil {
3✔
1350
                // The error is not fatal as this is an optimistic optimization,
×
1351
                // so we'll avoid returning an error.
×
1352
                Log.Debugf("Unable to update spend hint to %d for %v: %v",
×
1353
                        details.SpendingHeight, spendRequest, err)
×
1354
        }
×
1355

1356
        Log.Debugf("Updated spend hint to height=%v for confirmed spend "+
3✔
1357
                "request %v", details.SpendingHeight, spendRequest)
3✔
1358

3✔
1359
        spendSet.details = details
3✔
1360
        for _, ntfn := range spendSet.ntfns {
6✔
1361
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1362
                if err != nil {
3✔
1363
                        return err
×
1364
                }
×
1365
        }
1366

1367
        return nil
3✔
1368
}
1369

1370
// dispatchSpendDetails dispatches a spend notification to the client.
1371
//
1372
// NOTE: This must be called with the TxNotifier's lock held.
1373
func (n *TxNotifier) dispatchSpendDetails(ntfn *SpendNtfn, details *SpendDetail) error {
3✔
1374
        // If there are no spend details to dispatch or if the notification has
3✔
1375
        // already been dispatched, then we can skip dispatching to this client.
3✔
1376
        if details == nil || ntfn.dispatched {
6✔
1377
                Log.Debugf("Skipping dispatch of spend details(%v) for "+
3✔
1378
                        "request %v, dispatched=%v", details, ntfn.SpendRequest,
3✔
1379
                        ntfn.dispatched)
3✔
1380
                return nil
3✔
1381
        }
3✔
1382

1383
        Log.Debugf("Dispatching confirmed spend notification for %v at "+
3✔
1384
                "current height=%d: %v", ntfn.SpendRequest, n.currentHeight,
3✔
1385
                details)
3✔
1386

3✔
1387
        select {
3✔
1388
        case ntfn.Event.Spend <- details:
3✔
1389
                ntfn.dispatched = true
3✔
1390
        case <-n.quit:
×
1391
                return ErrTxNotifierExiting
×
1392
        }
1393

1394
        spendHeight := uint32(details.SpendingHeight)
3✔
1395

3✔
1396
        // We also add to spendsByHeight to notify on chain reorgs.
3✔
1397
        reorgSafeHeight := spendHeight + n.reorgSafetyLimit
3✔
1398
        if reorgSafeHeight > n.currentHeight {
6✔
1399
                txSet, exists := n.spendsByHeight[spendHeight]
3✔
1400
                if !exists {
6✔
1401
                        txSet = make(map[SpendRequest]struct{})
3✔
1402
                        n.spendsByHeight[spendHeight] = txSet
3✔
1403
                }
3✔
1404
                txSet[ntfn.SpendRequest] = struct{}{}
3✔
1405
        }
1406

1407
        return nil
3✔
1408
}
1409

1410
// ConnectTip handles a new block extending the current chain. It will go
1411
// through every transaction and determine if it is relevant to any of its
1412
// clients. A transaction can be relevant in either of the following two ways:
1413
//
1414
//  1. One of the inputs in the transaction spends an outpoint/output script
1415
//     for which we currently have an active spend registration for.
1416
//
1417
//  2. The transaction has a txid or output script for which we currently have
1418
//     an active confirmation registration for.
1419
//
1420
// In the event that the transaction is relevant, a confirmation/spend
1421
// notification will be queued for dispatch to the relevant clients.
1422
// Confirmation notifications will only be dispatched for transactions/output
1423
// scripts that have met the required number of confirmations required by the
1424
// client.
1425
//
1426
// NOTE: In order to actually dispatch the relevant transaction notifications to
1427
// clients, NotifyHeight must be called with the same block height in order to
1428
// maintain correctness.
1429
func (n *TxNotifier) ConnectTip(block *btcutil.Block,
1430
        blockHeight uint32) error {
3✔
1431

3✔
1432
        select {
3✔
1433
        case <-n.quit:
×
1434
                return ErrTxNotifierExiting
×
1435
        default:
3✔
1436
        }
1437

1438
        n.Lock()
3✔
1439
        defer n.Unlock()
3✔
1440

3✔
1441
        if blockHeight != n.currentHeight+1 {
3✔
1442
                return fmt.Errorf("received blocks out of order: "+
×
1443
                        "current height=%d, new height=%d",
×
1444
                        n.currentHeight, blockHeight)
×
1445
        }
×
1446
        n.currentHeight++
3✔
1447
        n.reorgDepth = 0
3✔
1448

3✔
1449
        // First, we'll iterate over all the transactions found in this block to
3✔
1450
        // determine if it includes any relevant transactions to the TxNotifier.
3✔
1451
        if block != nil {
6✔
1452
                Log.Debugf("Filtering %d txns for %d spend requests at "+
3✔
1453
                        "height %d", len(block.Transactions()),
3✔
1454
                        len(n.spendNotifications), blockHeight)
3✔
1455

3✔
1456
                for _, tx := range block.Transactions() {
6✔
1457
                        n.filterTx(
3✔
1458
                                block, tx, blockHeight,
3✔
1459
                                n.handleConfDetailsAtTip,
3✔
1460
                                n.handleSpendDetailsAtTip,
3✔
1461
                        )
3✔
1462
                }
3✔
1463
        }
1464

1465
        // Now that we've determined which requests were confirmed and spent
1466
        // within the new block, we can update their entries in their respective
1467
        // caches, along with all of our unconfirmed and unspent requests.
1468
        n.updateHints(blockHeight)
3✔
1469

3✔
1470
        // Finally, we'll clear the entries from our set of notifications for
3✔
1471
        // requests that are no longer under the risk of being reorged out of
3✔
1472
        // the chain.
3✔
1473
        if blockHeight >= n.reorgSafetyLimit {
6✔
1474
                matureBlockHeight := blockHeight - n.reorgSafetyLimit
3✔
1475
                for confRequest := range n.confsByInitialHeight[matureBlockHeight] {
3✔
UNCOV
1476
                        confSet := n.confNotifications[confRequest]
×
UNCOV
1477
                        for _, ntfn := range confSet.ntfns {
×
UNCOV
1478
                                select {
×
UNCOV
1479
                                case ntfn.Event.Done <- struct{}{}:
×
1480
                                case <-n.quit:
×
1481
                                        return ErrTxNotifierExiting
×
1482
                                }
1483
                        }
1484

UNCOV
1485
                        delete(n.confNotifications, confRequest)
×
1486
                }
1487
                delete(n.confsByInitialHeight, matureBlockHeight)
3✔
1488

3✔
1489
                for spendRequest := range n.spendsByHeight[matureBlockHeight] {
3✔
UNCOV
1490
                        spendSet := n.spendNotifications[spendRequest]
×
UNCOV
1491
                        for _, ntfn := range spendSet.ntfns {
×
UNCOV
1492
                                select {
×
UNCOV
1493
                                case ntfn.Event.Done <- struct{}{}:
×
1494
                                case <-n.quit:
×
1495
                                        return ErrTxNotifierExiting
×
1496
                                }
1497
                        }
1498

UNCOV
1499
                        Log.Debugf("Deleting mature spend request %v at "+
×
UNCOV
1500
                                "height=%d", spendRequest, blockHeight)
×
UNCOV
1501
                        delete(n.spendNotifications, spendRequest)
×
1502
                }
1503
                delete(n.spendsByHeight, matureBlockHeight)
3✔
1504
        }
1505

1506
        return nil
3✔
1507
}
1508

1509
// filterTx determines whether the transaction spends or confirms any
1510
// outstanding pending requests. The onConf and onSpend callbacks can be used to
1511
// retrieve all the requests fulfilled by this transaction as they occur.
1512
func (n *TxNotifier) filterTx(block *btcutil.Block, tx *btcutil.Tx,
1513
        blockHeight uint32, onConf func(ConfRequest, *TxConfirmation),
1514
        onSpend func(SpendRequest, *SpendDetail)) {
3✔
1515

3✔
1516
        // In order to determine if this transaction is relevant to the
3✔
1517
        // notifier, we'll check its inputs for any outstanding spend
3✔
1518
        // requests.
3✔
1519
        txHash := tx.Hash()
3✔
1520
        if onSpend != nil {
6✔
1521
                // notifyDetails is a helper closure that will construct the
3✔
1522
                // spend details of a request and hand them off to the onSpend
3✔
1523
                // callback.
3✔
1524
                notifyDetails := func(spendRequest SpendRequest,
3✔
1525
                        prevOut wire.OutPoint, inputIdx uint32) {
6✔
1526

3✔
1527
                        Log.Debugf("Found spend of %v: spend_tx=%v, "+
3✔
1528
                                "block_height=%d", spendRequest, txHash,
3✔
1529
                                blockHeight)
3✔
1530

3✔
1531
                        onSpend(spendRequest, &SpendDetail{
3✔
1532
                                SpentOutPoint:     &prevOut,
3✔
1533
                                SpenderTxHash:     txHash,
3✔
1534
                                SpendingTx:        tx.MsgTx(),
3✔
1535
                                SpenderInputIndex: inputIdx,
3✔
1536
                                SpendingHeight:    int32(blockHeight),
3✔
1537
                        })
3✔
1538
                }
3✔
1539

1540
                for i, txIn := range tx.MsgTx().TxIn {
6✔
1541
                        // We'll re-derive the script of the output being spent
3✔
1542
                        // to determine if the inputs spends any registered
3✔
1543
                        // requests.
3✔
1544
                        prevOut := txIn.PreviousOutPoint
3✔
1545
                        pkScript, err := txscript.ComputePkScript(
3✔
1546
                                txIn.SignatureScript, txIn.Witness,
3✔
1547
                        )
3✔
1548
                        if err != nil {
3✔
1549
                                continue
×
1550
                        }
1551
                        spendRequest := SpendRequest{
3✔
1552
                                OutPoint: prevOut,
3✔
1553
                                PkScript: pkScript,
3✔
1554
                        }
3✔
1555

3✔
1556
                        // If we have any, we'll record their spend height so
3✔
1557
                        // that notifications get dispatched to the respective
3✔
1558
                        // clients.
3✔
1559
                        if _, ok := n.spendNotifications[spendRequest]; ok {
6✔
1560
                                notifyDetails(spendRequest, prevOut, uint32(i))
3✔
1561
                        }
3✔
1562

1563
                        // Now try with an empty taproot key pkScript, since we
1564
                        // cannot derive the spent pkScript directly from the
1565
                        // witness. But we have the outpoint, which should be
1566
                        // enough.
1567
                        spendRequest.PkScript = ZeroTaprootPkScript
3✔
1568
                        if _, ok := n.spendNotifications[spendRequest]; ok {
6✔
1569
                                notifyDetails(spendRequest, prevOut, uint32(i))
3✔
1570
                        }
3✔
1571

1572
                        // Restore the pkScript but try with a zero outpoint
1573
                        // instead (won't be possible for Taproot).
1574
                        spendRequest.PkScript = pkScript
3✔
1575
                        spendRequest.OutPoint = ZeroOutPoint
3✔
1576
                        if _, ok := n.spendNotifications[spendRequest]; ok {
3✔
UNCOV
1577
                                notifyDetails(spendRequest, prevOut, uint32(i))
×
UNCOV
1578
                        }
×
1579
                }
1580
        }
1581

1582
        // We'll also check its outputs to determine if there are any
1583
        // outstanding confirmation requests.
1584
        if onConf != nil {
6✔
1585
                // notifyDetails is a helper closure that will construct the
3✔
1586
                // confirmation details of a request and hand them off to the
3✔
1587
                // onConf callback.
3✔
1588
                notifyDetails := func(confRequest ConfRequest) {
6✔
1589
                        Log.Debugf("Found initial confirmation of %v: "+
3✔
1590
                                "height=%d, hash=%v", confRequest,
3✔
1591
                                blockHeight, block.Hash())
3✔
1592

3✔
1593
                        details := &TxConfirmation{
3✔
1594
                                Tx:          tx.MsgTx(),
3✔
1595
                                BlockHash:   block.Hash(),
3✔
1596
                                BlockHeight: blockHeight,
3✔
1597
                                TxIndex:     uint32(tx.Index()),
3✔
1598
                                Block:       block.MsgBlock(),
3✔
1599
                        }
3✔
1600

3✔
1601
                        onConf(confRequest, details)
3✔
1602
                }
3✔
1603

1604
                for _, txOut := range tx.MsgTx().TxOut {
6✔
1605
                        // We'll parse the script of the output to determine if
3✔
1606
                        // we have any registered requests for it or the
3✔
1607
                        // transaction itself.
3✔
1608
                        pkScript, err := txscript.ParsePkScript(txOut.PkScript)
3✔
1609
                        if err != nil {
6✔
1610
                                continue
3✔
1611
                        }
1612
                        confRequest := ConfRequest{
3✔
1613
                                TxID:     *txHash,
3✔
1614
                                PkScript: pkScript,
3✔
1615
                        }
3✔
1616

3✔
1617
                        // If we have any, we'll record their confirmed height
3✔
1618
                        // so that notifications get dispatched when they
3✔
1619
                        // reaches the clients' desired number of confirmations.
3✔
1620
                        if _, ok := n.confNotifications[confRequest]; ok {
6✔
1621
                                notifyDetails(confRequest)
3✔
1622
                        }
3✔
1623
                        confRequest.TxID = ZeroHash
3✔
1624
                        if _, ok := n.confNotifications[confRequest]; ok {
3✔
UNCOV
1625
                                notifyDetails(confRequest)
×
UNCOV
1626
                        }
×
1627
                }
1628
        }
1629
}
1630

1631
// handleConfDetailsAtTip tracks the confirmation height of the txid/output
1632
// script in order to properly dispatch a confirmation notification after
1633
// meeting each request's desired number of confirmations for all current and
1634
// future registered clients.
1635
func (n *TxNotifier) handleConfDetailsAtTip(confRequest ConfRequest,
1636
        details *TxConfirmation) {
3✔
1637

3✔
1638
        // TODO(wilmer): cancel pending historical rescans if any?
3✔
1639
        confSet := n.confNotifications[confRequest]
3✔
1640

3✔
1641
        // If we already have details for this request, we don't want to add it
3✔
1642
        // again since we have already dispatched notifications for it.
3✔
1643
        if confSet.details != nil {
5✔
1644
                Log.Warnf("Ignoring address reuse for %s at height %d.",
2✔
1645
                        confRequest, details.BlockHeight)
2✔
1646
                return
2✔
1647
        }
2✔
1648

1649
        confSet.rescanStatus = rescanComplete
3✔
1650
        confSet.details = details
3✔
1651

3✔
1652
        for _, ntfn := range confSet.ntfns {
6✔
1653
                // In the event that this notification was aware that the
3✔
1654
                // transaction/output script was reorged out of the chain, we'll
3✔
1655
                // consume the reorg notification if it hasn't been done yet
3✔
1656
                // already.
3✔
1657
                select {
3✔
1658
                case <-ntfn.Event.NegativeConf:
2✔
1659
                default:
3✔
1660
                }
1661

1662
                // We'll note this client's required number of confirmations so
1663
                // that we can notify them when expected.
1664
                confHeight := details.BlockHeight + ntfn.NumConfirmations - 1
3✔
1665
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
3✔
1666
                if !exists {
6✔
1667
                        ntfnSet = make(map[*ConfNtfn]struct{})
3✔
1668
                        n.ntfnsByConfirmHeight[confHeight] = ntfnSet
3✔
1669
                }
3✔
1670
                ntfnSet[ntfn] = struct{}{}
3✔
1671
        }
1672

1673
        // We'll also note the initial confirmation height in order to correctly
1674
        // handle dispatching notifications when the transaction/output script
1675
        // gets reorged out of the chain.
1676
        txSet, exists := n.confsByInitialHeight[details.BlockHeight]
3✔
1677
        if !exists {
6✔
1678
                txSet = make(map[ConfRequest]struct{})
3✔
1679
                n.confsByInitialHeight[details.BlockHeight] = txSet
3✔
1680
        }
3✔
1681
        txSet[confRequest] = struct{}{}
3✔
1682
}
1683

1684
// handleSpendDetailsAtTip tracks the spend height of the outpoint/output script
1685
// in order to properly dispatch a spend notification for all current and future
1686
// registered clients.
1687
func (n *TxNotifier) handleSpendDetailsAtTip(spendRequest SpendRequest,
1688
        details *SpendDetail) {
3✔
1689

3✔
1690
        // TODO(wilmer): cancel pending historical rescans if any?
3✔
1691
        spendSet := n.spendNotifications[spendRequest]
3✔
1692
        spendSet.rescanStatus = rescanComplete
3✔
1693
        spendSet.details = details
3✔
1694

3✔
1695
        for _, ntfn := range spendSet.ntfns {
6✔
1696
                // In the event that this notification was aware that the
3✔
1697
                // spending transaction of its outpoint/output script was
3✔
1698
                // reorged out of the chain, we'll consume the reorg
3✔
1699
                // notification if it hasn't been done yet already.
3✔
1700
                select {
3✔
1701
                case <-ntfn.Event.Reorg:
×
1702
                default:
3✔
1703
                }
1704
        }
1705

1706
        // We'll note the spending height of the request in order to correctly
1707
        // handle dispatching notifications when the spending transactions gets
1708
        // reorged out of the chain.
1709
        spendHeight := uint32(details.SpendingHeight)
3✔
1710
        opSet, exists := n.spendsByHeight[spendHeight]
3✔
1711
        if !exists {
6✔
1712
                opSet = make(map[SpendRequest]struct{})
3✔
1713
                n.spendsByHeight[spendHeight] = opSet
3✔
1714
        }
3✔
1715
        opSet[spendRequest] = struct{}{}
3✔
1716

3✔
1717
        Log.Debugf("Spend request %v spent at tip=%d", spendRequest,
3✔
1718
                spendHeight)
3✔
1719
}
1720

1721
// NotifyHeight dispatches confirmation and spend notifications to the clients
1722
// who registered for a notification which has been fulfilled at the passed
1723
// height.
1724
func (n *TxNotifier) NotifyHeight(height uint32) error {
3✔
1725
        n.Lock()
3✔
1726
        defer n.Unlock()
3✔
1727

3✔
1728
        // First, we'll dispatch an update to all of the notification clients
3✔
1729
        // for our watched requests with the number of confirmations left at
3✔
1730
        // this new height.
3✔
1731
        for _, confRequests := range n.confsByInitialHeight {
6✔
1732
                for confRequest := range confRequests {
6✔
1733
                        confSet := n.confNotifications[confRequest]
3✔
1734
                        for _, ntfn := range confSet.ntfns {
6✔
1735
                                txConfHeight := confSet.details.BlockHeight +
3✔
1736
                                        ntfn.NumConfirmations - 1
3✔
1737
                                numConfsLeft := txConfHeight - height
3✔
1738

3✔
1739
                                // Since we don't clear notifications until
3✔
1740
                                // transactions/output scripts are no longer
3✔
1741
                                // under the risk of being reorganized out of
3✔
1742
                                // the chain, we'll skip sending updates for
3✔
1743
                                // those that have already been confirmed.
3✔
1744
                                if int32(numConfsLeft) < 0 {
6✔
1745
                                        continue
3✔
1746
                                }
1747

1748
                                err := n.notifyConfsUpdate(ntfn, numConfsLeft,
3✔
1749
                                        *confSet.details)
3✔
1750
                                if err != nil {
3✔
1751
                                        return err
×
1752
                                }
×
1753
                        }
1754
                }
1755
        }
1756

1757
        // Then, we'll dispatch notifications for all the requests that have
1758
        // become confirmed at this new block height.
1759
        for ntfn := range n.ntfnsByConfirmHeight[height] {
6✔
1760
                confSet := n.confNotifications[ntfn.ConfRequest]
3✔
1761

3✔
1762
                // The default notification we assigned above includes the
3✔
1763
                // block along with the rest of the details. However not all
3✔
1764
                // clients want the block, so we make a copy here w/o the block
3✔
1765
                // if needed so we can give clients only what they ask for.
3✔
1766
                confDetails := *confSet.details
3✔
1767
                if !ntfn.includeBlock {
6✔
1768
                        confDetails.Block = nil
3✔
1769
                }
3✔
1770

1771
                // If the `confDetails` has already been sent before, we'll
1772
                // skip it and continue processing the next one.
1773
                if ntfn.dispatched {
4✔
1774
                        Log.Debugf("Skipped dispatched conf details for "+
1✔
1775
                                "request %v conf_id=%v", ntfn.ConfRequest,
1✔
1776
                                ntfn.ConfID)
1✔
1777

1✔
1778
                        continue
1✔
1779
                }
1780

1781
                Log.Debugf("Dispatching %v confirmation notification for "+
3✔
1782
                        "conf_id=%v, %v", ntfn.NumConfirmations, ntfn.ConfID,
3✔
1783
                        ntfn.ConfRequest)
3✔
1784

3✔
1785
                select {
3✔
1786
                case ntfn.Event.Confirmed <- &confDetails:
3✔
1787
                        ntfn.dispatched = true
3✔
1788
                case <-n.quit:
×
1789
                        return ErrTxNotifierExiting
×
1790
                }
1791
        }
1792
        delete(n.ntfnsByConfirmHeight, height)
3✔
1793

3✔
1794
        // Finally, we'll dispatch spend notifications for all the requests that
3✔
1795
        // were spent at this new block height.
3✔
1796
        for spendRequest := range n.spendsByHeight[height] {
6✔
1797
                spendSet := n.spendNotifications[spendRequest]
3✔
1798
                for _, ntfn := range spendSet.ntfns {
6✔
1799
                        err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1800
                        if err != nil {
3✔
1801
                                return err
×
1802
                        }
×
1803
                }
1804
        }
1805

1806
        return nil
3✔
1807
}
1808

1809
// DisconnectTip handles the tip of the current chain being disconnected during
1810
// a chain reorganization. If any watched requests were included in this block,
1811
// internal structures are updated to ensure confirmation/spend notifications
1812
// are consumed (if not already), and reorg notifications are dispatched
1813
// instead. Confirmation/spend notifications will be dispatched again upon block
1814
// inclusion.
1815
func (n *TxNotifier) DisconnectTip(blockHeight uint32) error {
2✔
1816
        select {
2✔
1817
        case <-n.quit:
×
1818
                return ErrTxNotifierExiting
×
1819
        default:
2✔
1820
        }
1821

1822
        n.Lock()
2✔
1823
        defer n.Unlock()
2✔
1824

2✔
1825
        if blockHeight != n.currentHeight {
2✔
1826
                return fmt.Errorf("received blocks out of order: "+
×
1827
                        "current height=%d, disconnected height=%d",
×
1828
                        n.currentHeight, blockHeight)
×
1829
        }
×
1830
        n.currentHeight--
2✔
1831
        n.reorgDepth++
2✔
1832

2✔
1833
        // With the block disconnected, we'll update the confirm and spend hints
2✔
1834
        // for our notification requests to reflect the new height, except for
2✔
1835
        // those that have confirmed/spent at previous heights.
2✔
1836
        n.updateHints(blockHeight)
2✔
1837

2✔
1838
        // We'll go through all of our watched confirmation requests and attempt
2✔
1839
        // to drain their notification channels to ensure sending notifications
2✔
1840
        // to the clients is always non-blocking.
2✔
1841
        for initialHeight, txHashes := range n.confsByInitialHeight {
4✔
1842
                for txHash := range txHashes {
4✔
1843
                        // If the transaction/output script has been reorged out
2✔
1844
                        // of the chain, we'll make sure to remove the cached
2✔
1845
                        // confirmation details to prevent notifying clients
2✔
1846
                        // with old information.
2✔
1847
                        confSet := n.confNotifications[txHash]
2✔
1848
                        if initialHeight == blockHeight {
4✔
1849
                                confSet.details = nil
2✔
1850
                        }
2✔
1851

1852
                        for _, ntfn := range confSet.ntfns {
4✔
1853
                                // We also reset the num of confs update.
2✔
1854
                                ntfn.numConfsLeft = ntfn.NumConfirmations
2✔
1855

2✔
1856
                                // Then, we'll check if the current
2✔
1857
                                // transaction/output script was included in the
2✔
1858
                                // block currently being disconnected. If it
2✔
1859
                                // was, we'll need to dispatch a reorg
2✔
1860
                                // notification to the client.
2✔
1861
                                if initialHeight == blockHeight {
4✔
1862
                                        err := n.dispatchConfReorg(
2✔
1863
                                                ntfn, blockHeight,
2✔
1864
                                        )
2✔
1865
                                        if err != nil {
2✔
1866
                                                return err
×
1867
                                        }
×
1868
                                }
1869
                        }
1870
                }
1871
        }
1872

1873
        // We'll also go through our watched spend requests and attempt to drain
1874
        // their dispatched notifications to ensure dispatching notifications to
1875
        // clients later on is always non-blocking. We're only interested in
1876
        // requests whose spending transaction was included at the height being
1877
        // disconnected.
1878
        for op := range n.spendsByHeight[blockHeight] {
2✔
UNCOV
1879
                // Since the spending transaction is being reorged out of the
×
UNCOV
1880
                // chain, we'll need to clear out the spending details of the
×
UNCOV
1881
                // request.
×
UNCOV
1882
                spendSet := n.spendNotifications[op]
×
UNCOV
1883
                spendSet.details = nil
×
UNCOV
1884

×
UNCOV
1885
                // For all requests which have had a spend notification
×
UNCOV
1886
                // dispatched, we'll attempt to drain it and send a reorg
×
UNCOV
1887
                // notification instead.
×
UNCOV
1888
                for _, ntfn := range spendSet.ntfns {
×
UNCOV
1889
                        if err := n.dispatchSpendReorg(ntfn); err != nil {
×
1890
                                return err
×
1891
                        }
×
1892
                }
1893
        }
1894

1895
        // Finally, we can remove the requests that were confirmed and/or spent
1896
        // at the height being disconnected. We'll still continue to track them
1897
        // until they have been confirmed/spent and are no longer under the risk
1898
        // of being reorged out of the chain again.
1899
        delete(n.confsByInitialHeight, blockHeight)
2✔
1900
        delete(n.spendsByHeight, blockHeight)
2✔
1901

2✔
1902
        return nil
2✔
1903
}
1904

1905
// updateHints attempts to update the confirm and spend hints for all relevant
1906
// requests respectively. The height parameter is used to determine which
1907
// requests we should update based on whether a new block is being
1908
// connected/disconnected.
1909
//
1910
// NOTE: This must be called with the TxNotifier's lock held and after its
1911
// height has already been reflected by a block being connected/disconnected.
1912
func (n *TxNotifier) updateHints(height uint32) {
3✔
1913
        // TODO(wilmer): update under one database transaction.
3✔
1914
        //
3✔
1915
        // To update the height hint for all the required confirmation requests
3✔
1916
        // under one database transaction, we'll gather the set of unconfirmed
3✔
1917
        // requests along with the ones that confirmed at the height being
3✔
1918
        // connected/disconnected.
3✔
1919
        confRequests := n.unconfirmedRequests()
3✔
1920
        for confRequest := range n.confsByInitialHeight[height] {
6✔
1921
                confRequests = append(confRequests, confRequest)
3✔
1922
        }
3✔
1923
        err := n.confirmHintCache.CommitConfirmHint(
3✔
1924
                n.currentHeight, confRequests...,
3✔
1925
        )
3✔
1926
        if err != nil {
3✔
1927
                // The error is not fatal as this is an optimistic optimization,
×
1928
                // so we'll avoid returning an error.
×
1929
                Log.Debugf("Unable to update confirm hints to %d for "+
×
1930
                        "%v: %v", n.currentHeight, confRequests, err)
×
1931
        }
×
1932

1933
        // Similarly, to update the height hint for all the required spend
1934
        // requests under one database transaction, we'll gather the set of
1935
        // unspent requests along with the ones that were spent at the height
1936
        // being connected/disconnected.
1937
        spendRequests := n.unspentRequests()
3✔
1938
        for spendRequest := range n.spendsByHeight[height] {
6✔
1939
                spendRequests = append(spendRequests, spendRequest)
3✔
1940
        }
3✔
1941
        err = n.spendHintCache.CommitSpendHint(n.currentHeight, spendRequests...)
3✔
1942
        if err != nil {
3✔
1943
                // The error is not fatal as this is an optimistic optimization,
×
1944
                // so we'll avoid returning an error.
×
1945
                Log.Debugf("Unable to update spend hints to %d for "+
×
1946
                        "%v: %v", n.currentHeight, spendRequests, err)
×
1947
        }
×
1948
}
1949

1950
// unconfirmedRequests returns the set of confirmation requests that are
1951
// still seen as unconfirmed by the TxNotifier.
1952
//
1953
// NOTE: This method must be called with the TxNotifier's lock held.
1954
func (n *TxNotifier) unconfirmedRequests() []ConfRequest {
3✔
1955
        var unconfirmed []ConfRequest
3✔
1956
        for confRequest, confNtfnSet := range n.confNotifications {
6✔
1957
                // If the notification is already aware of its confirmation
3✔
1958
                // details, or it's in the process of learning them, we'll skip
3✔
1959
                // it as we can't yet determine if it's confirmed or not.
3✔
1960
                if confNtfnSet.rescanStatus != rescanComplete ||
3✔
1961
                        confNtfnSet.details != nil {
6✔
1962
                        continue
3✔
1963
                }
1964

1965
                unconfirmed = append(unconfirmed, confRequest)
3✔
1966
        }
1967

1968
        return unconfirmed
3✔
1969
}
1970

1971
// unspentRequests returns the set of spend requests that are still seen as
1972
// unspent by the TxNotifier.
1973
//
1974
// NOTE: This method must be called with the TxNotifier's lock held.
1975
func (n *TxNotifier) unspentRequests() []SpendRequest {
3✔
1976
        var unspent []SpendRequest
3✔
1977
        for spendRequest, spendNtfnSet := range n.spendNotifications {
6✔
1978
                // If the notification is already aware of its spend details, or
3✔
1979
                // it's in the process of learning them, we'll skip it as we
3✔
1980
                // can't yet determine if it's unspent or not.
3✔
1981
                if spendNtfnSet.rescanStatus != rescanComplete ||
3✔
1982
                        spendNtfnSet.details != nil {
6✔
1983
                        continue
3✔
1984
                }
1985

1986
                unspent = append(unspent, spendRequest)
3✔
1987
        }
1988

1989
        return unspent
3✔
1990
}
1991

1992
// dispatchConfReorg dispatches a reorg notification to the client if the
1993
// confirmation notification was already delivered.
1994
//
1995
// NOTE: This must be called with the TxNotifier's lock held.
1996
func (n *TxNotifier) dispatchConfReorg(ntfn *ConfNtfn,
1997
        heightDisconnected uint32) error {
2✔
1998

2✔
1999
        // If the request's confirmation notification has yet to be dispatched,
2✔
2000
        // we'll need to clear its entry within the ntfnsByConfirmHeight index
2✔
2001
        // to prevent from notifying the client once the notifier reaches the
2✔
2002
        // confirmation height.
2✔
2003
        if !ntfn.dispatched {
4✔
2004
                confHeight := heightDisconnected + ntfn.NumConfirmations - 1
2✔
2005
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
2✔
2006
                if exists {
4✔
2007
                        delete(ntfnSet, ntfn)
2✔
2008
                }
2✔
2009
                return nil
2✔
2010
        }
2011

2012
        // Otherwise, the entry within the ntfnsByConfirmHeight has already been
2013
        // deleted, so we'll attempt to drain the confirmation notification to
2014
        // ensure sends to the Confirmed channel are always non-blocking.
2015
        select {
2✔
2016
        case <-ntfn.Event.Confirmed:
×
2017
        case <-n.quit:
×
2018
                return ErrTxNotifierExiting
×
2019
        default:
2✔
2020
        }
2021

2022
        ntfn.dispatched = false
2✔
2023

2✔
2024
        // Send a negative confirmation notification to the client indicating
2✔
2025
        // how many blocks have been disconnected successively.
2✔
2026
        select {
2✔
2027
        case ntfn.Event.NegativeConf <- int32(n.reorgDepth):
2✔
2028
        case <-n.quit:
×
2029
                return ErrTxNotifierExiting
×
2030
        }
2031

2032
        return nil
2✔
2033
}
2034

2035
// dispatchSpendReorg dispatches a reorg notification to the client if a spend
2036
// notiification was already delivered.
2037
//
2038
// NOTE: This must be called with the TxNotifier's lock held.
UNCOV
2039
func (n *TxNotifier) dispatchSpendReorg(ntfn *SpendNtfn) error {
×
UNCOV
2040
        if !ntfn.dispatched {
×
2041
                return nil
×
2042
        }
×
2043

2044
        // Attempt to drain the spend notification to ensure sends to the Spend
2045
        // channel are always non-blocking.
UNCOV
2046
        select {
×
UNCOV
2047
        case <-ntfn.Event.Spend:
×
UNCOV
2048
        default:
×
2049
        }
2050

2051
        // Send a reorg notification to the client in order for them to
2052
        // correctly handle reorgs.
UNCOV
2053
        select {
×
UNCOV
2054
        case ntfn.Event.Reorg <- struct{}{}:
×
2055
        case <-n.quit:
×
2056
                return ErrTxNotifierExiting
×
2057
        }
2058

UNCOV
2059
        ntfn.dispatched = false
×
UNCOV
2060

×
UNCOV
2061
        return nil
×
2062
}
2063

2064
// TearDown is to be called when the owner of the TxNotifier is exiting. This
2065
// closes the event channels of all registered notifications that have not been
2066
// dispatched yet.
2067
func (n *TxNotifier) TearDown() {
3✔
2068
        close(n.quit)
3✔
2069

3✔
2070
        n.Lock()
3✔
2071
        defer n.Unlock()
3✔
2072

3✔
2073
        for _, confSet := range n.confNotifications {
6✔
2074
                for confID, ntfn := range confSet.ntfns {
6✔
2075
                        close(ntfn.Event.Confirmed)
3✔
2076
                        close(ntfn.Event.NegativeConf)
3✔
2077
                        close(ntfn.Event.Done)
3✔
2078
                        delete(confSet.ntfns, confID)
3✔
2079
                }
3✔
2080
        }
2081

2082
        for _, spendSet := range n.spendNotifications {
6✔
2083
                for spendID, ntfn := range spendSet.ntfns {
6✔
2084
                        close(ntfn.Event.Spend)
3✔
2085
                        close(ntfn.Event.Reorg)
3✔
2086
                        close(ntfn.Event.Done)
3✔
2087
                        delete(spendSet.ntfns, spendID)
3✔
2088
                }
3✔
2089
        }
2090
}
2091

2092
// notifyConfsUpdate sends a confirmation notification to the subscriber
2093
// through the Event.Confirmed channel, but only if the caller has opted to
2094
// receive updates for all confirmations and the transaction/output script
2095
// has not yet reached the target number of confirmations.
2096
//
2097
// NOTE: must be used with the TxNotifier's lock held.
2098
func (n *TxNotifier) notifyConfsUpdate(ntfn *ConfNtfn, num uint32,
2099
        details TxConfirmation) error {
3✔
2100

3✔
2101
        // If the number left is no less than the recorded value, we can skip
3✔
2102
        // sending it as it means this same value has already been sent before.
3✔
2103
        if num >= ntfn.numConfsLeft {
6✔
2104
                Log.Debugf("Skipped dispatched confirmation (numConfsLeft=%v) "+
3✔
2105
                        "for request %v conf_id=%v", num, ntfn.ConfRequest,
3✔
2106
                        ntfn.ConfID)
3✔
2107

3✔
2108
                return nil
3✔
2109
        }
3✔
2110

2111
        // Update the number of confirmations left to the notification.
2112
        ntfn.numConfsLeft = num
3✔
2113
        details.NumConfsLeft = num
3✔
2114

3✔
2115
        // Send the confirmation notification only if the caller has opted to
3✔
2116
        // receive updates for all confirmations and the transaction/output
3✔
2117
        // script has not yet reached the target number of confirmations.
3✔
2118
        if ntfn.allConfirmations && num > 0 {
3✔
NEW
2119
                select {
×
NEW
2120
                case ntfn.Event.Confirmed <- &details:
×
NEW
2121
                case <-n.quit:
×
NEW
2122
                        return ErrTxNotifierExiting
×
2123
                }
2124
        }
2125

2126
        return nil
3✔
2127
}
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