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

lightningnetwork / lnd / 15328865179

29 May 2025 04:43PM UTC coverage: 68.527% (+10.2%) from 58.327%
15328865179

Pull #9878

github

web-flow
Merge c27231d57 into bff2f2440
Pull Request #9878: chainntfns: add option to send all confirmations

87 of 118 new or added lines in 3 files covered. (73.73%)

18 existing lines in 3 files now uncovered.

134110 of 195704 relevant lines covered (68.53%)

21869.78 hits per line

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

88.53
/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 {
215✔
213
        scriptMatches := func() bool {
356✔
214
                pkScript := r.PkScript.Script()
141✔
215
                for _, txOut := range tx.TxOut {
312✔
216
                        if bytes.Equal(txOut.PkScript, pkScript) {
225✔
217
                                return true
54✔
218
                        }
54✔
219
                }
220

221
                return false
87✔
222
        }
223

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

228
        return scriptMatches()
85✔
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 {
247✔
644
                if hint > startHeight {
46✔
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 {
202✔
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:
26✔
676
                // If the confirmation details for this set of notifications has
26✔
677
                // already been found, we'll attempt to deliver them immediately
26✔
678
                // to this client.
26✔
679
                Log.Debugf("Attempting to dispatch confirmation for %v on "+
26✔
680
                        "registration since rescan has finished, conf_id=%v",
26✔
681
                        ntfn.ConfRequest, ntfn.ConfID)
26✔
682

26✔
683
                // The default notification we assigned above includes the
26✔
684
                // block along with the rest of the details. However not all
26✔
685
                // clients want the block, so we make a copy here w/o the block
26✔
686
                // if needed so we can give clients only what they ask for.
26✔
687
                confDetails := confSet.details
26✔
688
                if !ntfn.includeBlock && confDetails != nil {
40✔
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 {
114✔
698
                        err := n.dispatchConfDetails(subscriber, confDetails)
88✔
699
                        if err != nil {
88✔
700
                                return nil, err
×
701
                        }
×
702
                }
703

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

46✔
717
                return &ConfRegistration{
46✔
718
                        Event:              ntfn.Event,
46✔
719
                        HistoricalDispatch: nil,
46✔
720
                        Height:             n.currentHeight,
46✔
721
                }, nil
46✔
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 {
165✔
732
                Log.Debugf("Height hint is above current height, not "+
8✔
733
                        "dispatching historical confirmation rescan for %v",
8✔
734
                        ntfn.ConfRequest)
8✔
735

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

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

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

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

151✔
764
        return &ConfRegistration{
151✔
765
                Event:              ntfn.Event,
151✔
766
                HistoricalDispatch: dispatch,
151✔
767
                Height:             n.currentHeight,
151✔
768
        }, nil
151✔
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 {
142✔
823

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

142✔
835
        // First, we'll determine whether we have an active confirmation
142✔
836
        // notification for the given txid/script.
142✔
837
        confSet, ok := n.confNotifications[confRequest]
142✔
838
        if !ok {
142✔
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 {
147✔
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
138✔
856

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

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

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

21✔
935
                return nil
21✔
936
        }
21✔
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
                // We'll send a 0 value indicating that the transaction/output
38✔
955
                // script has already been confirmed.
38✔
956
                err := n.notifyConfsUpdate(ntfn, 0, *details)
38✔
957
                if err != nil {
38✔
958
                        return err
×
959
                }
×
960

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

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

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

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

1003
        return nil
47✔
1004
}
1005

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1247
        return nil
45✔
1248
}
1249

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

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

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

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

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

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

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

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

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

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

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

×
1335
                return ErrEmptyWitnessStack
×
1336
        }
×
1337

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

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

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

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

1371
        return nil
7✔
1372
}
1373

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

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

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

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

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

1411
        return nil
128✔
1412
}
1413

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

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

1442
        n.Lock()
1,588✔
1443
        defer n.Unlock()
1,588✔
1444

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

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

1,585✔
1460
                for _, tx := range block.Transactions() {
3,845✔
1461
                        n.filterTx(
2,260✔
1462
                                block, tx, blockHeight,
2,260✔
1463
                                n.handleConfDetailsAtTip,
2,260✔
1464
                                n.handleSpendDetailsAtTip,
2,260✔
1465
                        )
2,260✔
1466
                }
2,260✔
1467
        }
1468

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

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

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

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

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

1510
        return nil
1,588✔
1511
}
1512

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1782
                        continue
×
1783
                }
1784

1785
                Log.Debugf("Dispatching %v confirmation notification for "+
177✔
1786
                        "conf_id=%v, %v", ntfn.NumConfirmations, ntfn.ConfID,
177✔
1787
                        ntfn.ConfRequest)
177✔
1788

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

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

1810
        return nil
1,488✔
1811
}
1812

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

1826
        n.Lock()
95✔
1827
        defer n.Unlock()
95✔
1828

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

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

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

1856
                        for _, ntfn := range confSet.ntfns {
1,096✔
1857
                                // We also reset the num of confs update.
612✔
1858
                                ntfn.numConfsLeft = ntfn.NumConfirmations
612✔
1859

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

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

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

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

95✔
1906
        return nil
95✔
1907
}
1908

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

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

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

1969
                unconfirmed = append(unconfirmed, confRequest)
699✔
1970
        }
1971

1972
        return unconfirmed
1,681✔
1973
}
1974

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

1990
                unspent = append(unspent, spendRequest)
44✔
1991
        }
1992

1993
        return unspent
1,681✔
1994
}
1995

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

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

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

2026
        ntfn.dispatched = false
4✔
2027

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

2036
        return nil
4✔
2037
}
2038

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

2048
        // Attempt to drain the spend notification to ensure sends to the Spend
2049
        // channel are always non-blocking.
2050
        select {
12✔
2051
        case <-ntfn.Event.Spend:
1✔
2052
        default:
11✔
2053
        }
2054

2055
        // Send a reorg notification to the client in order for them to
2056
        // correctly handle reorgs.
2057
        select {
12✔
2058
        case ntfn.Event.Reorg <- struct{}{}:
12✔
2059
        case <-n.quit:
×
2060
                return ErrTxNotifierExiting
×
2061
        }
2062

2063
        ntfn.dispatched = false
12✔
2064

12✔
2065
        return nil
12✔
2066
}
2067

2068
// TearDown is to be called when the owner of the TxNotifier is exiting. This
2069
// closes the event channels of all registered notifications that have not been
2070
// dispatched yet.
2071
func (n *TxNotifier) TearDown() {
25✔
2072
        close(n.quit)
25✔
2073

25✔
2074
        n.Lock()
25✔
2075
        defer n.Unlock()
25✔
2076

25✔
2077
        for _, confSet := range n.confNotifications {
153✔
2078
                for confID, ntfn := range confSet.ntfns {
312✔
2079
                        close(ntfn.Event.Confirmed)
184✔
2080
                        close(ntfn.Event.NegativeConf)
184✔
2081
                        close(ntfn.Event.Done)
184✔
2082
                        delete(confSet.ntfns, confID)
184✔
2083
                }
184✔
2084
        }
2085

2086
        for _, spendSet := range n.spendNotifications {
61✔
2087
                for spendID, ntfn := range spendSet.ntfns {
136✔
2088
                        close(ntfn.Event.Spend)
100✔
2089
                        close(ntfn.Event.Reorg)
100✔
2090
                        close(ntfn.Event.Done)
100✔
2091
                        delete(spendSet.ntfns, spendID)
100✔
2092
                }
100✔
2093
        }
2094
}
2095

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

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

3✔
2112
                return nil
3✔
2113
        }
3✔
2114

2115
        // Update the number of confirmations left to the notification.
2116
        ntfn.numConfsLeft = num
732✔
2117
        details.NumConfsLeft = num
732✔
2118

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

2130
        return nil
732✔
2131
}
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