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

lightningnetwork / lnd / 15924767183

27 Jun 2025 11:04AM UTC coverage: 67.597% (-0.009%) from 67.606%
15924767183

Pull #9878

github

web-flow
Merge f0b6b70e2 into 6290edf14
Pull Request #9878: chainntfns: add option to send all confirmations

115 of 139 new or added lines in 3 files covered. (82.73%)

102 existing lines in 19 files now uncovered.

135139 of 199919 relevant lines covered (67.6%)

21914.19 hits per line

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

88.08
/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 {
157✔
132
        return &confNtfnSet{
157✔
133
                ntfns:        make(map[uint64]*ConfNtfn),
157✔
134
                rescanStatus: rescanNotStarted,
157✔
135
        }
157✔
136
}
157✔
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 {
49✔
159
        return &spendNtfnSet{
49✔
160
                ntfns:        make(map[uint64]*SpendNtfn),
49✔
161
                rescanStatus: rescanNotStarted,
49✔
162
        }
49✔
163
}
49✔
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) {
235✔
183
        var r ConfRequest
235✔
184
        outputScript, err := txscript.ParsePkScript(pkScript)
235✔
185
        if err != nil {
235✔
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 {
376✔
193
                r.TxID = *txid
141✔
194
        }
141✔
195
        r.PkScript = outputScript
235✔
196

235✔
197
        return r, nil
235✔
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 {
219✔
213
        scriptMatches := func() bool {
363✔
214
                pkScript := r.PkScript.Script()
144✔
215
                for _, txOut := range tx.TxOut {
320✔
216
                        if bytes.Equal(txOut.PkScript, pkScript) {
231✔
217
                                return true
55✔
218
                        }
55✔
219
                }
220

221
                return false
89✔
222
        }
223

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

228
        return scriptMatches()
87✔
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) {
128✔
328
        var r SpendRequest
128✔
329
        outputScript, err := txscript.ParsePkScript(pkScript)
128✔
330
        if err != nil {
128✔
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 {
204✔
338
                r.OutPoint = *op
76✔
339
        }
76✔
340
        r.PkScript = outputScript
128✔
341

128✔
342
        // For Taproot spends we have the main problem that for the key spend
128✔
343
        // path we cannot derive the pkScript from only looking at the input's
128✔
344
        // witness. So we need to rely on the outpoint information alone.
128✔
345
        //
128✔
346
        // TODO(guggero): For script path spends we can derive the pkScript from
128✔
347
        // the witness, since we have the full control block and the spent
128✔
348
        // script available.
128✔
349
        if outputScript.Class() == txscript.WitnessV1TaprootTy {
131✔
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
128✔
361
}
362

363
// String returns the string representation of the SpendRequest.
364
func (r SpendRequest) String() string {
4✔
365
        if r.OutPoint != ZeroOutPoint {
8✔
366
                return fmt.Sprintf("outpoint=%v, script=%v", r.OutPoint,
4✔
367
                        r.PkScript)
4✔
368
        }
4✔
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) {
9✔
379
        if r.OutPoint != ZeroOutPoint {
14✔
380
                for i, txIn := range tx.TxIn {
10✔
381
                        if txIn.PreviousOutPoint == r.OutPoint {
6✔
382
                                return true, uint32(i), nil
1✔
383
                        }
1✔
384
                }
385

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

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

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

405
        return false, 0, nil
4✔
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 {
50✔
549

50✔
550
        return &TxNotifier{
50✔
551
                currentHeight:        startHeight,
50✔
552
                reorgSafetyLimit:     reorgSafetyLimit,
50✔
553
                confNotifications:    make(map[ConfRequest]*confNtfnSet),
50✔
554
                confsByInitialHeight: make(map[uint32]map[ConfRequest]struct{}),
50✔
555
                ntfnsByConfirmHeight: make(map[uint32]map[*ConfNtfn]struct{}),
50✔
556
                spendNotifications:   make(map[SpendRequest]*spendNtfnSet),
50✔
557
                spendsByHeight:       make(map[uint32]map[SpendRequest]struct{}),
50✔
558
                confirmHintCache:     confirmHintCache,
50✔
559
                spendHintCache:       spendHintCache,
50✔
560
                quit:                 make(chan struct{}),
50✔
561
        }
50✔
562
}
50✔
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) {
227✔
569

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

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

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

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

593
        confID := atomic.AddUint64(&n.confClientCounter, 1)
223✔
594
        return &ConfNtfn{
223✔
595
                ConfID:           confID,
223✔
596
                ConfRequest:      confRequest,
223✔
597
                NumConfirmations: numConfs,
223✔
598
                Event: NewConfirmationEvent(numConfs, func() {
229✔
599
                        n.CancelConf(confRequest, confID)
6✔
600
                }),
6✔
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) {
228✔
619

228✔
620
        select {
228✔
621
        case <-n.quit:
1✔
622
                return nil, ErrTxNotifierExiting
1✔
623
        default:
227✔
624
        }
625

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

631
        // We'll start by performing a series of validation checks.
632
        ntfn, err := n.newConfNtfn(txid, pkScript, numConfs, heightHint, opts)
227✔
633
        if err != nil {
231✔
634
                return nil, err
4✔
635
        }
4✔
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
223✔
642
        hint, err := n.confirmHintCache.QueryConfirmHint(ntfn.ConfRequest)
223✔
643
        if err == nil {
248✔
644
                if hint > startHeight {
47✔
645
                        Log.Debugf("Using height hint %d retrieved from cache "+
22✔
646
                                "for %v instead of %d for conf subscription",
22✔
647
                                hint, ntfn.ConfRequest, startHeight)
22✔
648
                        startHeight = hint
22✔
649
                }
22✔
650
        } else if err != ErrConfirmHintNotFound {
201✔
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, "+
223✔
656
                "num_confs=%v height_hint=%d", ntfn.ConfID, ntfn.ConfRequest,
223✔
657
                numConfs, startHeight)
223✔
658

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

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

223✔
671
        switch confSet.rescanStatus {
223✔
672

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

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

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

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

704
                return &ConfRegistration{
27✔
705
                        Event:              ntfn.Event,
27✔
706
                        HistoricalDispatch: nil,
27✔
707
                        Height:             n.currentHeight,
27✔
708
                }, nil
27✔
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:
45✔
714
                Log.Debugf("Waiting for pending rescan to finish before "+
45✔
715
                        "notifying %v at tip", ntfn.ConfRequest)
45✔
716

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

723
        // If no rescan has been dispatched, attempt to do so now.
724
        case rescanNotStarted:
157✔
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 {
163✔
732
                Log.Debugf("Height hint is above current height, not "+
6✔
733
                        "dispatching historical confirmation rescan for %v",
6✔
734
                        ntfn.ConfRequest)
6✔
735

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

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

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

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

153✔
764
        return &ConfRegistration{
153✔
765
                Event:              ntfn.Event,
153✔
766
                HistoricalDispatch: dispatch,
153✔
767
                Height:             n.currentHeight,
153✔
768
        }, nil
153✔
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) {
6✔
774
        select {
6✔
775
        case <-n.quit:
×
776
                return
×
777
        default:
6✔
778
        }
779

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

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

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

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

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

6✔
804
        // Remove the queued confirmation notification if the transaction has
6✔
805
        // already confirmed, but hasn't met its required number of
6✔
806
        // confirmations.
6✔
807
        if confSet.details != nil {
11✔
808
                confHeight := confSet.details.BlockHeight +
5✔
809
                        ntfn.NumConfirmations - 1
5✔
810
                delete(n.ntfnsByConfirmHeight[confHeight], ntfn)
5✔
811
        }
5✔
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 {
144✔
823

144✔
824
        select {
144✔
825
        case <-n.quit:
×
826
                return ErrTxNotifierExiting
×
827
        default:
144✔
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()
144✔
833
        defer n.Unlock()
144✔
834

144✔
835
        // First, we'll determine whether we have an active confirmation
144✔
836
        // notification for the given txid/script.
144✔
837
        confSet, ok := n.confNotifications[confRequest]
144✔
838
        if !ok {
144✔
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 {
149✔
848
                return nil
5✔
849
        }
5✔
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
140✔
856

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

118✔
865
                // We'll commit the current height as the confirm hint to
118✔
866
                // prevent another potentially long rescan if we restart before
118✔
867
                // a new block comes in.
118✔
868
                err := n.confirmHintCache.CommitConfirmHint(
118✔
869
                        n.currentHeight, confRequest,
118✔
870
                )
118✔
871
                if err != nil {
118✔
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
118✔
879
        }
880

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

2✔
885
                return nil
2✔
886
        }
2✔
887

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

23✔
890
        err := n.confirmHintCache.CommitConfirmHint(
23✔
891
                details.BlockHeight, confRequest,
23✔
892
        )
23✔
893
        if err != nil {
23✔
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
23✔
903
        for _, ntfn := range confSet.ntfns {
51✔
904
                // The default notification we assigned above includes the
28✔
905
                // block along with the rest of the details. However not all
28✔
906
                // clients want the block, so we make a copy here w/o the block
28✔
907
                // if needed so we can give clients only what they ask for.
28✔
908
                confDetails := *details
28✔
909
                if !ntfn.includeBlock {
48✔
910
                        confDetails.Block = nil
20✔
911
                }
20✔
912

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

919
        return nil
23✔
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 {
116✔
927

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

24✔
935
                return nil
24✔
936
        }
24✔
937

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

51✔
942
                return nil
51✔
943
        }
51✔
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
47✔
949
        if confHeight <= n.currentHeight {
85✔
950
                Log.Debugf("Dispatching %v confirmation notification for "+
38✔
951
                        "conf_id=%v, %v", ntfn.NumConfirmations, ntfn.ConfID,
38✔
952
                        ntfn.ConfRequest)
38✔
953

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

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

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

12✔
977
                // We'll send a confirmation update to the client only if
12✔
978
                // the client has opted in to receive updates on the number
12✔
979
                // of confirmations remaining for the transaction/output script.
12✔
980
                numConfsLeft := confHeight - n.currentHeight
12✔
981
                err := n.notifyConfsUpdate(ntfn, numConfsLeft, *details)
12✔
982
                if err != nil {
12✔
983
                        return err
×
984
                }
×
985

986
                // Update the number of confirmations left to the notification.
987
                ntfn.numConfsLeft = numConfsLeft
12✔
988
        }
989

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

1002
        return nil
47✔
1003
}
1004

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

130✔
1010
        // An accompanying output script must always be provided.
130✔
1011
        if len(pkScript) == 0 {
131✔
1012
                return nil, ErrNoScript
1✔
1013
        }
1✔
1014

1015
        // A height hint must be provided to prevent scanning from the genesis
1016
        // block.
1017
        if heightHint == 0 {
130✔
1018
                return nil, ErrNoHeightHint
1✔
1019
        }
1✔
1020

1021
        // Ensure the output script is of a supported type.
1022
        spendRequest, err := NewSpendRequest(outpoint, pkScript)
128✔
1023
        if err != nil {
131✔
1024
                return nil, err
3✔
1025
        }
3✔
1026

1027
        spendID := atomic.AddUint64(&n.spendClientCounter, 1)
128✔
1028
        return &SpendNtfn{
128✔
1029
                SpendID:      spendID,
128✔
1030
                SpendRequest: spendRequest,
128✔
1031
                Event: NewSpendEvent(func() {
139✔
1032
                        n.CancelSpend(spendRequest, spendID)
11✔
1033
                }),
11✔
1034
                HeightHint: heightHint,
1035
        }, nil
1036
}
1037

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

131✔
1049
        select {
131✔
1050
        case <-n.quit:
1✔
1051
                return nil, ErrTxNotifierExiting
1✔
1052
        default:
130✔
1053
        }
1054

1055
        // We'll start by performing a series of validation checks.
1056
        ntfn, err := n.newSpendNtfn(outpoint, pkScript, heightHint)
130✔
1057
        if err != nil {
135✔
1058
                return nil, err
5✔
1059
        }
5✔
1060

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

1077
        n.Lock()
128✔
1078
        defer n.Unlock()
128✔
1079

128✔
1080
        Log.Debugf("New spend subscription: spend_id=%d, %v, height_hint=%d",
128✔
1081
                ntfn.SpendID, ntfn.SpendRequest, startHeight)
128✔
1082

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

128✔
1094
        // We'll now let the caller know whether a historical rescan is needed
128✔
1095
        // depending on the current rescan status.
128✔
1096
        switch spendSet.rescanStatus {
128✔
1097

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

72✔
1106
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
72✔
1107
                if err != nil {
72✔
1108
                        return nil, err
×
1109
                }
×
1110

1111
                return &SpendRegistration{
72✔
1112
                        Event:              ntfn.Event,
72✔
1113
                        HistoricalDispatch: nil,
72✔
1114
                        Height:             n.currentHeight,
72✔
1115
                }, nil
72✔
1116

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

13✔
1123
                return &SpendRegistration{
13✔
1124
                        Event:              ntfn.Event,
13✔
1125
                        HistoricalDispatch: nil,
13✔
1126
                        Height:             n.currentHeight,
13✔
1127
                }, nil
13✔
1128

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

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

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

1154
        // We'll set the rescan status to pending to ensure subsequent
1155
        // notifications don't also attempt a historical dispatch.
1156
        spendSet.rescanStatus = rescanPending
25✔
1157

25✔
1158
        Log.Debugf("Dispatching historical spend rescan for %v, start=%d, "+
25✔
1159
                "end=%d", ntfn.SpendRequest, startHeight, n.currentHeight)
25✔
1160

25✔
1161
        return &SpendRegistration{
25✔
1162
                Event: ntfn.Event,
25✔
1163
                HistoricalDispatch: &HistoricalSpendDispatch{
25✔
1164
                        SpendRequest: ntfn.SpendRequest,
25✔
1165
                        StartHeight:  startHeight,
25✔
1166
                        EndHeight:    n.currentHeight,
25✔
1167
                },
25✔
1168
                Height: n.currentHeight,
25✔
1169
        }, nil
25✔
1170
}
1171

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

1181
        n.Lock()
12✔
1182
        defer n.Unlock()
12✔
1183

12✔
1184
        spendSet, ok := n.spendNotifications[spendRequest]
12✔
1185
        if !ok {
12✔
1186
                return
×
1187
        }
×
1188
        ntfn, ok := spendSet.ntfns[spendID]
12✔
1189
        if !ok {
12✔
1190
                return
×
1191
        }
×
1192

1193
        Log.Debugf("Canceling spend notification: spend_id=%d, %v", spendID,
12✔
1194
                spendRequest)
12✔
1195

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

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

44✔
1211
        select {
44✔
1212
        case <-n.quit:
×
1213
                return ErrTxNotifierExiting
×
1214
        default:
44✔
1215
        }
1216

1217
        // Ensure we hold the lock throughout handling the notification to
1218
        // prevent the notifier from advancing its height underneath us.
1219
        n.Lock()
44✔
1220
        defer n.Unlock()
44✔
1221

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

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

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

1246
        return nil
44✔
1247
}
1248

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

16✔
1259
        select {
16✔
1260
        case <-n.quit:
×
1261
                return ErrTxNotifierExiting
×
1262
        default:
16✔
1263
        }
1264

1265
        // Ensure we hold the lock throughout handling the notification to
1266
        // prevent the notifier from advancing its height underneath us.
1267
        n.Lock()
16✔
1268
        defer n.Unlock()
16✔
1269

16✔
1270
        return n.updateSpendDetails(spendRequest, details)
16✔
1271
}
1272

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

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

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

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

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

1319
                Log.Debugf("Updated spend hint to height=%v for unconfirmed "+
8✔
1320
                        "spend request %v", n.currentHeight, spendRequest)
8✔
1321
                return nil
8✔
1322
        }
1323

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

×
1334
                return ErrEmptyWitnessStack
×
1335
        }
×
1336

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

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

1359
        Log.Debugf("Updated spend hint to height=%v for confirmed spend "+
7✔
1360
                "request %v", details.SpendingHeight, spendRequest)
7✔
1361

7✔
1362
        spendSet.details = details
7✔
1363
        for _, ntfn := range spendSet.ntfns {
19✔
1364
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
12✔
1365
                if err != nil {
12✔
1366
                        return err
×
1367
                }
×
1368
        }
1369

1370
        return nil
7✔
1371
}
1372

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

1386
        Log.Debugf("Dispatching confirmed spend notification for %v at "+
128✔
1387
                "current height=%d: %v", ntfn.SpendRequest, n.currentHeight,
128✔
1388
                details)
128✔
1389

128✔
1390
        select {
128✔
1391
        case ntfn.Event.Spend <- details:
128✔
1392
                ntfn.dispatched = true
128✔
1393
        case <-n.quit:
×
1394
                return ErrTxNotifierExiting
×
1395
        }
1396

1397
        spendHeight := uint32(details.SpendingHeight)
128✔
1398

128✔
1399
        // We also add to spendsByHeight to notify on chain reorgs.
128✔
1400
        reorgSafeHeight := spendHeight + n.reorgSafetyLimit
128✔
1401
        if reorgSafeHeight > n.currentHeight {
256✔
1402
                txSet, exists := n.spendsByHeight[spendHeight]
128✔
1403
                if !exists {
135✔
1404
                        txSet = make(map[SpendRequest]struct{})
7✔
1405
                        n.spendsByHeight[spendHeight] = txSet
7✔
1406
                }
7✔
1407
                txSet[ntfn.SpendRequest] = struct{}{}
128✔
1408
        }
1409

1410
        return nil
128✔
1411
}
1412

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

1,589✔
1435
        select {
1,589✔
1436
        case <-n.quit:
×
1437
                return ErrTxNotifierExiting
×
1438
        default:
1,589✔
1439
        }
1440

1441
        n.Lock()
1,589✔
1442
        defer n.Unlock()
1,589✔
1443

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

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

1,586✔
1459
                for _, tx := range block.Transactions() {
3,848✔
1460
                        n.filterTx(
2,262✔
1461
                                block, tx, blockHeight,
2,262✔
1462
                                n.handleConfDetailsAtTip,
2,262✔
1463
                                n.handleSpendDetailsAtTip,
2,262✔
1464
                        )
2,262✔
1465
                }
2,262✔
1466
        }
1467

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

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

1488
                        delete(n.confNotifications, confRequest)
16✔
1489
                }
1490
                delete(n.confsByInitialHeight, matureBlockHeight)
1,477✔
1491

1,477✔
1492
                for spendRequest := range n.spendsByHeight[matureBlockHeight] {
1,479✔
1493
                        spendSet := n.spendNotifications[spendRequest]
2✔
1494
                        for _, ntfn := range spendSet.ntfns {
4✔
1495
                                select {
2✔
1496
                                case ntfn.Event.Done <- struct{}{}:
2✔
1497
                                case <-n.quit:
×
1498
                                        return ErrTxNotifierExiting
×
1499
                                }
1500
                        }
1501

1502
                        Log.Debugf("Deleting mature spend request %v at "+
2✔
1503
                                "height=%d", spendRequest, blockHeight)
2✔
1504
                        delete(n.spendNotifications, spendRequest)
2✔
1505
                }
1506
                delete(n.spendsByHeight, matureBlockHeight)
1,477✔
1507
        }
1508

1509
        return nil
1,589✔
1510
}
1511

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

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

88✔
1530
                        Log.Debugf("Found spend of %v: spend_tx=%v, "+
88✔
1531
                                "block_height=%d", spendRequest, txHash,
88✔
1532
                                blockHeight)
88✔
1533

88✔
1534
                        onSpend(spendRequest, &SpendDetail{
88✔
1535
                                SpentOutPoint:     &prevOut,
88✔
1536
                                SpenderTxHash:     txHash,
88✔
1537
                                SpendingTx:        tx.MsgTx(),
88✔
1538
                                SpenderInputIndex: inputIdx,
88✔
1539
                                SpendingHeight:    int32(blockHeight),
88✔
1540
                        })
88✔
1541
                }
88✔
1542

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

2,546✔
1559
                        // If we have any, we'll record their spend height so
2,546✔
1560
                        // that notifications get dispatched to the respective
2,546✔
1561
                        // clients.
2,546✔
1562
                        if _, ok := n.spendNotifications[spendRequest]; ok {
2,596✔
1563
                                notifyDetails(spendRequest, prevOut, uint32(i))
50✔
1564
                        }
50✔
1565

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

1575
                        // Restore the pkScript but try with a zero outpoint
1576
                        // instead (won't be possible for Taproot).
1577
                        spendRequest.PkScript = pkScript
2,546✔
1578
                        spendRequest.OutPoint = ZeroOutPoint
2,546✔
1579
                        if _, ok := n.spendNotifications[spendRequest]; ok {
2,584✔
1580
                                notifyDetails(spendRequest, prevOut, uint32(i))
38✔
1581
                        }
38✔
1582
                }
1583
        }
1584

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

142✔
1596
                        details := &TxConfirmation{
142✔
1597
                                Tx:          tx.MsgTx(),
142✔
1598
                                BlockHash:   block.Hash(),
142✔
1599
                                BlockHeight: blockHeight,
142✔
1600
                                TxIndex:     uint32(tx.Index()),
142✔
1601
                                Block:       block.MsgBlock(),
142✔
1602
                        }
142✔
1603

142✔
1604
                        onConf(confRequest, details)
142✔
1605
                }
142✔
1606

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

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

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

142✔
1641
        // TODO(wilmer): cancel pending historical rescans if any?
142✔
1642
        confSet := n.confNotifications[confRequest]
142✔
1643

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

1652
        confSet.rescanStatus = rescanComplete
139✔
1653
        confSet.details = details
139✔
1654

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

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

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

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

53✔
1693
        // TODO(wilmer): cancel pending historical rescans if any?
53✔
1694
        spendSet := n.spendNotifications[spendRequest]
53✔
1695
        spendSet.rescanStatus = rescanComplete
53✔
1696
        spendSet.details = details
53✔
1697

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

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

53✔
1720
        Log.Debugf("Spend request %v spent at tip=%d", spendRequest,
53✔
1721
                spendHeight)
53✔
1722
}
1723

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

1,489✔
1731
        // First, we'll dispatch an update to all of the notification clients
1,489✔
1732
        // for our watched requests with the number of confirmations left at
1,489✔
1733
        // this new height.
1,489✔
1734
        for _, confRequests := range n.confsByInitialHeight {
9,061✔
1735
                for confRequest := range confRequests {
20,935✔
1736
                        confSet := n.confNotifications[confRequest]
13,363✔
1737
                        for _, ntfn := range confSet.ntfns {
30,078✔
1738
                                txConfHeight := confSet.details.BlockHeight +
16,715✔
1739
                                        ntfn.NumConfirmations - 1
16,715✔
1740
                                numConfsLeft := txConfHeight - height
16,715✔
1741

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

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

1757
                                // Update the number of confirmations left to
1758
                                // the notification.
1759
                                ntfn.numConfsLeft = numConfsLeft
688✔
1760
                        }
1761
                }
1762
        }
1763

1764
        // Then, we'll dispatch notifications for all the requests that have
1765
        // become confirmed at this new block height.
1766
        for ntfn := range n.ntfnsByConfirmHeight[height] {
1,666✔
1767
                confSet := n.confNotifications[ntfn.ConfRequest]
177✔
1768

177✔
1769
                // The default notification we assigned above includes the
177✔
1770
                // block along with the rest of the details. However not all
177✔
1771
                // clients want the block, so we make a copy here w/o the block
177✔
1772
                // if needed so we can give clients only what they ask for.
177✔
1773
                confDetails := *confSet.details
177✔
1774
                if !ntfn.includeBlock {
314✔
1775
                        confDetails.Block = nil
137✔
1776
                }
137✔
1777

1778
                // If the `confDetails` has already been sent before, we'll
1779
                // skip it and continue processing the next one.
1780
                if ntfn.dispatched {
177✔
1781
                        Log.Debugf("Skipped dispatched conf details for "+
×
1782
                                "request %v conf_id=%v", ntfn.ConfRequest,
×
1783
                                ntfn.ConfID)
×
1784

×
1785
                        continue
×
1786
                }
1787

1788
                Log.Debugf("Dispatching %v confirmation notification for "+
177✔
1789
                        "conf_id=%v, %v", ntfn.NumConfirmations, ntfn.ConfID,
177✔
1790
                        ntfn.ConfRequest)
177✔
1791

177✔
1792
                select {
177✔
1793
                case ntfn.Event.Confirmed <- &confDetails:
177✔
1794
                        ntfn.dispatched = true
177✔
1795
                case <-n.quit:
×
1796
                        return ErrTxNotifierExiting
×
1797
                }
1798
        }
1799
        delete(n.ntfnsByConfirmHeight, height)
1,489✔
1800

1,489✔
1801
        // Finally, we'll dispatch spend notifications for all the requests that
1,489✔
1802
        // were spent at this new block height.
1,489✔
1803
        for spendRequest := range n.spendsByHeight[height] {
1,542✔
1804
                spendSet := n.spendNotifications[spendRequest]
53✔
1805
                for _, ntfn := range spendSet.ntfns {
151✔
1806
                        err := n.dispatchSpendDetails(ntfn, spendSet.details)
98✔
1807
                        if err != nil {
98✔
1808
                                return err
×
1809
                        }
×
1810
                }
1811
        }
1812

1813
        return nil
1,489✔
1814
}
1815

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

1829
        n.Lock()
95✔
1830
        defer n.Unlock()
95✔
1831

95✔
1832
        if blockHeight != n.currentHeight {
95✔
1833
                return fmt.Errorf("received blocks out of order: "+
×
1834
                        "current height=%d, disconnected height=%d",
×
1835
                        n.currentHeight, blockHeight)
×
1836
        }
×
1837
        n.currentHeight--
95✔
1838
        n.reorgDepth++
95✔
1839

95✔
1840
        // With the block disconnected, we'll update the confirm and spend hints
95✔
1841
        // for our notification requests to reflect the new height, except for
95✔
1842
        // those that have confirmed/spent at previous heights.
95✔
1843
        n.updateHints(blockHeight)
95✔
1844

95✔
1845
        // We'll go through all of our watched confirmation requests and attempt
95✔
1846
        // to drain their notification channels to ensure sending notifications
95✔
1847
        // to the clients is always non-blocking.
95✔
1848
        for initialHeight, txHashes := range n.confsByInitialHeight {
386✔
1849
                for txHash := range txHashes {
775✔
1850
                        // If the transaction/output script has been reorged out
484✔
1851
                        // of the chain, we'll make sure to remove the cached
484✔
1852
                        // confirmation details to prevent notifying clients
484✔
1853
                        // with old information.
484✔
1854
                        confSet := n.confNotifications[txHash]
484✔
1855
                        if initialHeight == blockHeight {
498✔
1856
                                confSet.details = nil
14✔
1857
                        }
14✔
1858

1859
                        for _, ntfn := range confSet.ntfns {
1,096✔
1860
                                // We'll attempt to drain an Confirmed from each
612✔
1861
                                // notification to ensure sends to the Confirmed
612✔
1862
                                // channel are always non-blocking.
612✔
1863
                                select {
612✔
1864
                                case <-ntfn.Event.Confirmed:
1✔
1865
                                case <-n.quit:
×
1866
                                        return ErrTxNotifierExiting
×
1867
                                default:
611✔
1868
                                }
1869

1870
                                // We also reset the num of confs update.
1871
                                ntfn.numConfsLeft = ntfn.NumConfirmations
612✔
1872

612✔
1873
                                // Then, we'll check if the current
612✔
1874
                                // transaction/output script was included in the
612✔
1875
                                // block currently being disconnected. If it
612✔
1876
                                // was, we'll need to dispatch a reorg
612✔
1877
                                // notification to the client.
612✔
1878
                                if initialHeight == blockHeight {
626✔
1879
                                        err := n.dispatchConfReorg(
14✔
1880
                                                ntfn, blockHeight,
14✔
1881
                                        )
14✔
1882
                                        if err != nil {
14✔
1883
                                                return err
×
1884
                                        }
×
1885
                                }
1886
                        }
1887
                }
1888
        }
1889

1890
        // We'll also go through our watched spend requests and attempt to drain
1891
        // their dispatched notifications to ensure dispatching notifications to
1892
        // clients later on is always non-blocking. We're only interested in
1893
        // requests whose spending transaction was included at the height being
1894
        // disconnected.
1895
        for op := range n.spendsByHeight[blockHeight] {
107✔
1896
                // Since the spending transaction is being reorged out of the
12✔
1897
                // chain, we'll need to clear out the spending details of the
12✔
1898
                // request.
12✔
1899
                spendSet := n.spendNotifications[op]
12✔
1900
                spendSet.details = nil
12✔
1901

12✔
1902
                // For all requests which have had a spend notification
12✔
1903
                // dispatched, we'll attempt to drain it and send a reorg
12✔
1904
                // notification instead.
12✔
1905
                for _, ntfn := range spendSet.ntfns {
24✔
1906
                        if err := n.dispatchSpendReorg(ntfn); err != nil {
12✔
1907
                                return err
×
1908
                        }
×
1909
                }
1910
        }
1911

1912
        // Finally, we can remove the requests that were confirmed and/or spent
1913
        // at the height being disconnected. We'll still continue to track them
1914
        // until they have been confirmed/spent and are no longer under the risk
1915
        // of being reorged out of the chain again.
1916
        delete(n.confsByInitialHeight, blockHeight)
95✔
1917
        delete(n.spendsByHeight, blockHeight)
95✔
1918

95✔
1919
        return nil
95✔
1920
}
1921

1922
// updateHints attempts to update the confirm and spend hints for all relevant
1923
// requests respectively. The height parameter is used to determine which
1924
// requests we should update based on whether a new block is being
1925
// connected/disconnected.
1926
//
1927
// NOTE: This must be called with the TxNotifier's lock held and after its
1928
// height has already been reflected by a block being connected/disconnected.
1929
func (n *TxNotifier) updateHints(height uint32) {
1,682✔
1930
        // TODO(wilmer): update under one database transaction.
1,682✔
1931
        //
1,682✔
1932
        // To update the height hint for all the required confirmation requests
1,682✔
1933
        // under one database transaction, we'll gather the set of unconfirmed
1,682✔
1934
        // requests along with the ones that confirmed at the height being
1,682✔
1935
        // connected/disconnected.
1,682✔
1936
        confRequests := n.unconfirmedRequests()
1,682✔
1937
        for confRequest := range n.confsByInitialHeight[height] {
1,833✔
1938
                confRequests = append(confRequests, confRequest)
151✔
1939
        }
151✔
1940
        err := n.confirmHintCache.CommitConfirmHint(
1,682✔
1941
                n.currentHeight, confRequests...,
1,682✔
1942
        )
1,682✔
1943
        if err != nil {
1,682✔
1944
                // The error is not fatal as this is an optimistic optimization,
×
1945
                // so we'll avoid returning an error.
×
1946
                Log.Debugf("Unable to update confirm hints to %d for "+
×
1947
                        "%v: %v", n.currentHeight, confRequests, err)
×
1948
        }
×
1949

1950
        // Similarly, to update the height hint for all the required spend
1951
        // requests under one database transaction, we'll gather the set of
1952
        // unspent requests along with the ones that were spent at the height
1953
        // being connected/disconnected.
1954
        spendRequests := n.unspentRequests()
1,682✔
1955
        for spendRequest := range n.spendsByHeight[height] {
1,747✔
1956
                spendRequests = append(spendRequests, spendRequest)
65✔
1957
        }
65✔
1958
        err = n.spendHintCache.CommitSpendHint(n.currentHeight, spendRequests...)
1,682✔
1959
        if err != nil {
1,682✔
1960
                // The error is not fatal as this is an optimistic optimization,
×
1961
                // so we'll avoid returning an error.
×
1962
                Log.Debugf("Unable to update spend hints to %d for "+
×
1963
                        "%v: %v", n.currentHeight, spendRequests, err)
×
1964
        }
×
1965
}
1966

1967
// unconfirmedRequests returns the set of confirmation requests that are
1968
// still seen as unconfirmed by the TxNotifier.
1969
//
1970
// NOTE: This method must be called with the TxNotifier's lock held.
1971
func (n *TxNotifier) unconfirmedRequests() []ConfRequest {
1,682✔
1972
        var unconfirmed []ConfRequest
1,682✔
1973
        for confRequest, confNtfnSet := range n.confNotifications {
16,335✔
1974
                // If the notification is already aware of its confirmation
14,653✔
1975
                // details, or it's in the process of learning them, we'll skip
14,653✔
1976
                // it as we can't yet determine if it's confirmed or not.
14,653✔
1977
                if confNtfnSet.rescanStatus != rescanComplete ||
14,653✔
1978
                        confNtfnSet.details != nil {
28,615✔
1979
                        continue
13,962✔
1980
                }
1981

1982
                unconfirmed = append(unconfirmed, confRequest)
694✔
1983
        }
1984

1985
        return unconfirmed
1,682✔
1986
}
1987

1988
// unspentRequests returns the set of spend requests that are still seen as
1989
// unspent by the TxNotifier.
1990
//
1991
// NOTE: This method must be called with the TxNotifier's lock held.
1992
func (n *TxNotifier) unspentRequests() []SpendRequest {
1,682✔
1993
        var unspent []SpendRequest
1,682✔
1994
        for spendRequest, spendNtfnSet := range n.spendNotifications {
3,269✔
1995
                // If the notification is already aware of its spend details, or
1,587✔
1996
                // it's in the process of learning them, we'll skip it as we
1,587✔
1997
                // can't yet determine if it's unspent or not.
1,587✔
1998
                if spendNtfnSet.rescanStatus != rescanComplete ||
1,587✔
1999
                        spendNtfnSet.details != nil {
3,132✔
2000
                        continue
1,545✔
2001
                }
2002

2003
                unspent = append(unspent, spendRequest)
45✔
2004
        }
2005

2006
        return unspent
1,682✔
2007
}
2008

2009
// dispatchConfReorg dispatches a reorg notification to the client if the
2010
// confirmation notification was already delivered.
2011
//
2012
// NOTE: This must be called with the TxNotifier's lock held.
2013
func (n *TxNotifier) dispatchConfReorg(ntfn *ConfNtfn,
2014
        heightDisconnected uint32) error {
14✔
2015

14✔
2016
        // If the request's confirmation notification has yet to be dispatched,
14✔
2017
        // we'll need to clear its entry within the ntfnsByConfirmHeight index
14✔
2018
        // to prevent from notifying the client once the notifier reaches the
14✔
2019
        // confirmation height.
14✔
2020
        if !ntfn.dispatched {
26✔
2021
                confHeight := heightDisconnected + ntfn.NumConfirmations - 1
12✔
2022
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
12✔
2023
                if exists {
24✔
2024
                        delete(ntfnSet, ntfn)
12✔
2025
                }
12✔
2026
                return nil
12✔
2027
        }
2028

2029
        // Otherwise, the entry within the ntfnsByConfirmHeight has already been
2030
        // deleted, so we'll attempt to drain the confirmation notification to
2031
        // ensure sends to the Confirmed channel are always non-blocking.
2032
        select {
4✔
2033
        case <-ntfn.Event.Confirmed:
×
2034
        case <-n.quit:
×
2035
                return ErrTxNotifierExiting
×
2036
        default:
4✔
2037
        }
2038

2039
        ntfn.dispatched = false
4✔
2040

4✔
2041
        // Send a negative confirmation notification to the client indicating
4✔
2042
        // how many blocks have been disconnected successively.
4✔
2043
        select {
4✔
2044
        case ntfn.Event.NegativeConf <- int32(n.reorgDepth):
4✔
2045
        case <-n.quit:
×
2046
                return ErrTxNotifierExiting
×
2047
        }
2048

2049
        return nil
4✔
2050
}
2051

2052
// dispatchSpendReorg dispatches a reorg notification to the client if a spend
2053
// notiification was already delivered.
2054
//
2055
// NOTE: This must be called with the TxNotifier's lock held.
2056
func (n *TxNotifier) dispatchSpendReorg(ntfn *SpendNtfn) error {
12✔
2057
        if !ntfn.dispatched {
12✔
2058
                return nil
×
2059
        }
×
2060

2061
        // Attempt to drain the spend notification to ensure sends to the Spend
2062
        // channel are always non-blocking.
2063
        select {
12✔
2064
        case <-ntfn.Event.Spend:
1✔
2065
        default:
11✔
2066
        }
2067

2068
        // Send a reorg notification to the client in order for them to
2069
        // correctly handle reorgs.
2070
        select {
12✔
2071
        case ntfn.Event.Reorg <- struct{}{}:
12✔
2072
        case <-n.quit:
×
2073
                return ErrTxNotifierExiting
×
2074
        }
2075

2076
        ntfn.dispatched = false
12✔
2077

12✔
2078
        return nil
12✔
2079
}
2080

2081
// TearDown is to be called when the owner of the TxNotifier is exiting. This
2082
// closes the event channels of all registered notifications that have not been
2083
// dispatched yet.
2084
func (n *TxNotifier) TearDown() {
25✔
2085
        close(n.quit)
25✔
2086

25✔
2087
        n.Lock()
25✔
2088
        defer n.Unlock()
25✔
2089

25✔
2090
        for _, confSet := range n.confNotifications {
153✔
2091
                for confID, ntfn := range confSet.ntfns {
312✔
2092
                        close(ntfn.Event.Confirmed)
184✔
2093
                        close(ntfn.Event.NegativeConf)
184✔
2094
                        close(ntfn.Event.Done)
184✔
2095
                        delete(confSet.ntfns, confID)
184✔
2096
                }
184✔
2097
        }
2098

2099
        for _, spendSet := range n.spendNotifications {
61✔
2100
                for spendID, ntfn := range spendSet.ntfns {
136✔
2101
                        close(ntfn.Event.Spend)
100✔
2102
                        close(ntfn.Event.Reorg)
100✔
2103
                        close(ntfn.Event.Done)
100✔
2104
                        delete(spendSet.ntfns, spendID)
100✔
2105
                }
100✔
2106
        }
2107
}
2108

2109
// notifyConfsUpdate sends a confirmation notification to the subscriber
2110
// through the Event.Confirmed channel, but only if the caller has opted to
2111
// receive updates for all confirmations and the transaction/output script
2112
// has not yet reached the target number of confirmations.
2113
//
2114
// NOTE: must be used with the TxNotifier's lock held.
2115
func (n *TxNotifier) notifyConfsUpdate(ntfn *ConfNtfn, num uint32,
2116
        details TxConfirmation) error {
697✔
2117

697✔
2118
        // Send the confirmation notification only if the caller has opted to
697✔
2119
        // receive updates for all confirmations and the transaction/output
697✔
2120
        // script has not yet reached the target number of confirmations.
697✔
2121
        if !ntfn.allConfirmations || num == 0 {
1,320✔
2122
                return nil
623✔
2123
        }
623✔
2124

2125
        // If the number left is no less than the recorded value, we can skip
2126
        // sending it as it means this same value has already been sent before.
2127
        if num >= ntfn.numConfsLeft {
74✔
NEW
2128
                Log.Debugf("Skipped dispatched confirmation (numConfsLeft=%v) "+
×
NEW
2129
                        "for request %v conf_id=%v", num, ntfn.ConfRequest,
×
UNCOV
2130
                        ntfn.ConfID)
×
UNCOV
2131

×
UNCOV
2132
                return nil
×
UNCOV
2133
        }
×
2134

2135
        // Update the number of confirmations left to the confirmation
2136
        // notification.
2137
        details.NumConfsLeft = num
74✔
2138

74✔
2139
        select {
74✔
2140
        case ntfn.Event.Confirmed <- &details:
74✔
2141
        case <-n.quit:
×
2142
                return ErrTxNotifierExiting
×
2143
        }
2144

2145
        return nil
74✔
2146
}
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