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

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

80.97
/chainntnfs/txnotifier.go
1
package chainntnfs
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

221
                return false
×
222
        }
223

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

228
        return scriptMatches()
×
229
}
230

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

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

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

247
        // Event contains references to the channels that the notifications are to
248
        // 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 yet.
256
        dispatched bool
257

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

263
// HistoricalConfDispatch parametrizes a manual rescan for a particular
264
// transaction/output script. The parameters include the start and end block
265
// heights specifying the range of blocks to scan.
266
type HistoricalConfDispatch struct {
267
        // ConfRequest represents either the txid or script we should detect
268
        // inclusion of within the chain.
269
        ConfRequest
270

271
        // StartHeight specifies the block height at which to begin the
272
        // historical rescan.
273
        StartHeight uint32
274

275
        // EndHeight specifies the last block height (inclusive) that the
276
        // historical scan should consider.
277
        EndHeight uint32
278
}
279

280
// ConfRegistration encompasses all of the information required for callers to
281
// retrieve details about a confirmation event.
282
type ConfRegistration struct {
283
        // Event contains references to the channels that the notifications are
284
        // to be sent over.
285
        Event *ConfirmationEvent
286

287
        // HistoricalDispatch, if non-nil, signals to the client who registered
288
        // the notification that they are responsible for attempting to manually
289
        // rescan blocks for the txid/output script between the start and end
290
        // heights.
291
        HistoricalDispatch *HistoricalConfDispatch
292

293
        // Height is the height of the TxNotifier at the time the confirmation
294
        // notification was registered. This can be used so that backends can
295
        // request to be notified of confirmations from this point forwards.
296
        Height uint32
297
}
298

299
// SpendRequest encapsulates a request for a spend notification of either an
300
// outpoint or output script.
301
type SpendRequest struct {
302
        // OutPoint is the outpoint for which a client has requested a spend
303
        // notification for. If set to a zero outpoint, then a spend
304
        // notification will be dispatched upon detecting the spend of the
305
        // _script_, rather than the outpoint.
306
        OutPoint wire.OutPoint
307

308
        // PkScript is the script of the outpoint. If a zero outpoint is set,
309
        // then this can be an arbitrary script.
310
        PkScript txscript.PkScript
311
}
312

313
// NewSpendRequest creates a request for a spend notification of either an
314
// outpoint or output script. A nil outpoint or an allocated ZeroOutPoint can be
315
// used to dispatch the confirmation notification on the script.
316
func NewSpendRequest(op *wire.OutPoint, pkScript []byte) (SpendRequest, error) {
3✔
317
        var r SpendRequest
3✔
318
        outputScript, err := txscript.ParsePkScript(pkScript)
3✔
319
        if err != nil {
3✔
320
                return r, err
×
321
        }
×
322

323
        // We'll only set an outpoint for which we'll dispatch a spend
324
        // notification on this request if one was provided. Otherwise, we'll
325
        // default to dispatching on the spend of the script instead.
326
        if op != nil {
6✔
327
                r.OutPoint = *op
3✔
328
        }
3✔
329
        r.PkScript = outputScript
3✔
330

3✔
331
        // For Taproot spends we have the main problem that for the key spend
3✔
332
        // path we cannot derive the pkScript from only looking at the input's
3✔
333
        // witness. So we need to rely on the outpoint information alone.
3✔
334
        //
3✔
335
        // TODO(guggero): For script path spends we can derive the pkScript from
3✔
336
        // the witness, since we have the full control block and the spent
3✔
337
        // script available.
3✔
338
        if outputScript.Class() == txscript.WitnessV1TaprootTy {
6✔
339
                if op == nil {
6✔
340
                        return r, fmt.Errorf("cannot register witness v1 " +
3✔
341
                                "spend request without outpoint")
3✔
342
                }
3✔
343

344
                // We have an outpoint, so we can set the pkScript to an all
345
                // zero Taproot key that we'll compare this spend request to.
346
                r.PkScript = ZeroTaprootPkScript
3✔
347
        }
348

349
        return r, nil
3✔
350
}
351

352
// String returns the string representation of the SpendRequest.
353
func (r SpendRequest) String() string {
3✔
354
        if r.OutPoint != ZeroOutPoint {
6✔
355
                return fmt.Sprintf("outpoint=%v, script=%v", r.OutPoint,
3✔
356
                        r.PkScript)
3✔
357
        }
3✔
358
        return fmt.Sprintf("outpoint=<zero>, script=%v", r.PkScript)
×
359
}
360

361
// MatchesTx determines whether the given transaction satisfies the spend
362
// request. If the spend request is for an outpoint, then we'll check all of
363
// the outputs being spent by the inputs of the transaction to determine if it
364
// matches. Otherwise, we'll need to match on the output script being spent, so
365
// we'll recompute it for each input of the transaction to determine if it
366
// matches.
367
func (r SpendRequest) MatchesTx(tx *wire.MsgTx) (bool, uint32, error) {
2✔
368
        if r.OutPoint != ZeroOutPoint {
4✔
369
                for i, txIn := range tx.TxIn {
4✔
370
                        if txIn.PreviousOutPoint == r.OutPoint {
4✔
371
                                return true, uint32(i), nil
2✔
372
                        }
2✔
373
                }
374

375
                return false, 0, nil
2✔
376
        }
377

378
        for i, txIn := range tx.TxIn {
×
379
                pkScript, err := txscript.ComputePkScript(
×
380
                        txIn.SignatureScript, txIn.Witness,
×
381
                )
×
382
                if err == txscript.ErrUnsupportedScriptType {
×
383
                        continue
×
384
                }
385
                if err != nil {
×
386
                        return false, 0, err
×
387
                }
×
388

389
                if bytes.Equal(pkScript.Script(), r.PkScript.Script()) {
×
390
                        return true, uint32(i), nil
×
391
                }
×
392
        }
393

394
        return false, 0, nil
×
395
}
396

397
// SpendNtfn represents a client's request to receive a notification once an
398
// outpoint/output script has been spent on-chain. The client is asynchronously
399
// notified via the SpendEvent channels.
400
type SpendNtfn struct {
401
        // SpendID uniquely identies the spend notification request for the
402
        // specified outpoint/output script.
403
        SpendID uint64
404

405
        // SpendRequest represents either the outpoint or script we should
406
        // detect the spend of.
407
        SpendRequest
408

409
        // Event contains references to the channels that the notifications are
410
        // to be sent over.
411
        Event *SpendEvent
412

413
        // HeightHint is the earliest height in the chain that we expect to find
414
        // the spending transaction of the specified outpoint/output script.
415
        // This value will be overridden by the spend hint cache if it contains
416
        // an entry for it.
417
        HeightHint uint32
418

419
        // dispatched signals whether a spend notification has been dispatched
420
        // to the client.
421
        dispatched bool
422
}
423

424
// HistoricalSpendDispatch parametrizes a manual rescan to determine the
425
// spending details (if any) of an outpoint/output script. The parameters
426
// include the start and end block heights specifying the range of blocks to
427
// scan.
428
type HistoricalSpendDispatch struct {
429
        // SpendRequest represents either the outpoint or script we should
430
        // detect the spend of.
431
        SpendRequest
432

433
        // StartHeight specified the block height at which to begin the
434
        // historical rescan.
435
        StartHeight uint32
436

437
        // EndHeight specifies the last block height (inclusive) that the
438
        // historical rescan should consider.
439
        EndHeight uint32
440
}
441

442
// SpendRegistration encompasses all of the information required for callers to
443
// retrieve details about a spend event.
444
type SpendRegistration struct {
445
        // Event contains references to the channels that the notifications are
446
        // to be sent over.
447
        Event *SpendEvent
448

449
        // HistoricalDispatch, if non-nil, signals to the client who registered
450
        // the notification that they are responsible for attempting to manually
451
        // rescan blocks for the txid/output script between the start and end
452
        // heights.
453
        HistoricalDispatch *HistoricalSpendDispatch
454

455
        // Height is the height of the TxNotifier at the time the spend
456
        // notification was registered. This can be used so that backends can
457
        // request to be notified of spends from this point forwards.
458
        Height uint32
459
}
460

461
// TxNotifier is a struct responsible for delivering transaction notifications
462
// to subscribers. These notifications can be of two different types:
463
// transaction/output script confirmations and/or outpoint/output script spends.
464
// The TxNotifier will watch the blockchain as new blocks come in, in order to
465
// satisfy its client requests.
466
type TxNotifier struct {
467
        confClientCounter  uint64 // To be used atomically.
468
        spendClientCounter uint64 // To be used atomically.
469

470
        // currentHeight is the height of the tracked blockchain. It is used to
471
        // determine the number of confirmations a tx has and ensure blocks are
472
        // connected and disconnected in order.
473
        currentHeight uint32
474

475
        // reorgSafetyLimit is the chain depth beyond which it is assumed a
476
        // block will not be reorganized out of the chain. This is used to
477
        // determine when to prune old notification requests so that reorgs are
478
        // handled correctly. The coinbase maturity period is a reasonable value
479
        // to use.
480
        reorgSafetyLimit uint32
481

482
        // reorgDepth is the depth of a chain organization that this system is
483
        // being informed of. This is incremented as long as a sequence of
484
        // blocks are disconnected without being interrupted by a new block.
485
        reorgDepth uint32
486

487
        // confNotifications is an index of confirmation notification requests
488
        // by transaction hash/output script.
489
        confNotifications map[ConfRequest]*confNtfnSet
490

491
        // confsByInitialHeight is an index of watched transactions/output
492
        // scripts by the height that they are included at in the chain. This
493
        // is tracked so that incorrect notifications are not sent if a
494
        // transaction/output script is reorged out of the chain and so that
495
        // negative confirmations can be recognized.
496
        confsByInitialHeight map[uint32]map[ConfRequest]struct{}
497

498
        // ntfnsByConfirmHeight is an index of notification requests by the
499
        // height at which the transaction/output script will have sufficient
500
        // confirmations.
501
        ntfnsByConfirmHeight map[uint32]map[*ConfNtfn]struct{}
502

503
        // spendNotifications is an index of all active notification requests
504
        // per outpoint/output script.
505
        spendNotifications map[SpendRequest]*spendNtfnSet
506

507
        // spendsByHeight is an index that keeps tracks of the spending height
508
        // of outpoints/output scripts we are currently tracking notifications
509
        // for. This is used in order to recover from spending transactions
510
        // being reorged out of the chain.
511
        spendsByHeight map[uint32]map[SpendRequest]struct{}
512

513
        // confirmHintCache is a cache used to maintain the latest height hints
514
        // for transactions/output scripts. Each height hint represents the
515
        // earliest height at which they scripts could have been confirmed
516
        // within the chain.
517
        confirmHintCache ConfirmHintCache
518

519
        // spendHintCache is a cache used to maintain the latest height hints
520
        // for outpoints/output scripts. Each height hint represents the
521
        // earliest height at which they could have been spent within the chain.
522
        spendHintCache SpendHintCache
523

524
        // quit is closed in order to signal that the notifier is gracefully
525
        // exiting.
526
        quit chan struct{}
527

528
        sync.Mutex
529
}
530

531
// NewTxNotifier creates a TxNotifier. The current height of the blockchain is
532
// accepted as a parameter. The different hint caches (confirm and spend) are
533
// used as an optimization in order to retrieve a better starting point when
534
// dispatching a rescan for a historical event in the chain.
535
func NewTxNotifier(startHeight uint32, reorgSafetyLimit uint32,
536
        confirmHintCache ConfirmHintCache,
537
        spendHintCache SpendHintCache) *TxNotifier {
3✔
538

3✔
539
        return &TxNotifier{
3✔
540
                currentHeight:        startHeight,
3✔
541
                reorgSafetyLimit:     reorgSafetyLimit,
3✔
542
                confNotifications:    make(map[ConfRequest]*confNtfnSet),
3✔
543
                confsByInitialHeight: make(map[uint32]map[ConfRequest]struct{}),
3✔
544
                ntfnsByConfirmHeight: make(map[uint32]map[*ConfNtfn]struct{}),
3✔
545
                spendNotifications:   make(map[SpendRequest]*spendNtfnSet),
3✔
546
                spendsByHeight:       make(map[uint32]map[SpendRequest]struct{}),
3✔
547
                confirmHintCache:     confirmHintCache,
3✔
548
                spendHintCache:       spendHintCache,
3✔
549
                quit:                 make(chan struct{}),
3✔
550
        }
3✔
551
}
3✔
552

553
// newConfNtfn validates all of the parameters required to successfully create
554
// and register a confirmation notification.
555
func (n *TxNotifier) newConfNtfn(txid *chainhash.Hash,
556
        pkScript []byte, numConfs, heightHint uint32,
557
        opts *notifierOptions) (*ConfNtfn, error) {
3✔
558

3✔
559
        // An accompanying output script must always be provided.
3✔
560
        if len(pkScript) == 0 {
3✔
561
                return nil, ErrNoScript
×
562
        }
×
563

564
        // Enforce that we will not dispatch confirmations beyond the reorg
565
        // safety limit.
566
        if numConfs == 0 || numConfs > n.reorgSafetyLimit {
3✔
567
                return nil, ErrNumConfsOutOfRange
×
568
        }
×
569

570
        // A height hint must be provided to prevent scanning from the genesis
571
        // block.
572
        if heightHint == 0 {
3✔
573
                return nil, ErrNoHeightHint
×
574
        }
×
575

576
        // Ensure the output script is of a supported type.
577
        confRequest, err := NewConfRequest(txid, pkScript)
3✔
578
        if err != nil {
3✔
579
                return nil, err
×
580
        }
×
581

582
        confID := atomic.AddUint64(&n.confClientCounter, 1)
3✔
583
        return &ConfNtfn{
3✔
584
                ConfID:           confID,
3✔
585
                ConfRequest:      confRequest,
3✔
586
                NumConfirmations: numConfs,
3✔
587
                Event: NewConfirmationEvent(numConfs, func() {
6✔
588
                        n.CancelConf(confRequest, confID)
3✔
589
                }),
3✔
590
                HeightHint:   heightHint,
591
                includeBlock: opts.includeBlock,
592
        }, nil
593
}
594

595
// RegisterConf handles a new confirmation notification request. The client will
596
// be notified when the transaction/output script gets a sufficient number of
597
// confirmations in the blockchain.
598
//
599
// NOTE: If the transaction/output script has already been included in a block
600
// on the chain, the confirmation details must be provided with the
601
// UpdateConfDetails method, otherwise we will wait for the transaction/output
602
// script to confirm even though it already has.
603
func (n *TxNotifier) RegisterConf(txid *chainhash.Hash, pkScript []byte,
604
        numConfs, heightHint uint32,
605
        optFuncs ...NotifierOption) (*ConfRegistration, error) {
3✔
606

3✔
607
        select {
3✔
608
        case <-n.quit:
×
609
                return nil, ErrTxNotifierExiting
×
610
        default:
3✔
611
        }
612

613
        opts := defaultNotifierOptions()
3✔
614
        for _, optFunc := range optFuncs {
6✔
615
                optFunc(opts)
3✔
616
        }
3✔
617

618
        // We'll start by performing a series of validation checks.
619
        ntfn, err := n.newConfNtfn(txid, pkScript, numConfs, heightHint, opts)
3✔
620
        if err != nil {
3✔
621
                return nil, err
×
622
        }
×
623

624
        // Before proceeding to register the notification, we'll query our
625
        // height hint cache to determine whether a better one exists.
626
        //
627
        // TODO(conner): verify that all submitted height hints are identical.
628
        startHeight := ntfn.HeightHint
3✔
629
        hint, err := n.confirmHintCache.QueryConfirmHint(ntfn.ConfRequest)
3✔
630
        if err == nil {
6✔
631
                if hint > startHeight {
6✔
632
                        Log.Debugf("Using height hint %d retrieved from cache "+
3✔
633
                                "for %v instead of %d for conf subscription",
3✔
634
                                hint, ntfn.ConfRequest, startHeight)
3✔
635
                        startHeight = hint
3✔
636
                }
3✔
637
        } else if err != ErrConfirmHintNotFound {
3✔
638
                Log.Errorf("Unable to query confirm hint for %v: %v",
×
639
                        ntfn.ConfRequest, err)
×
640
        }
×
641

642
        Log.Infof("New confirmation subscription: conf_id=%d, %v, "+
3✔
643
                "num_confs=%v height_hint=%d", ntfn.ConfID, ntfn.ConfRequest,
3✔
644
                numConfs, startHeight)
3✔
645

3✔
646
        n.Lock()
3✔
647
        defer n.Unlock()
3✔
648

3✔
649
        confSet, ok := n.confNotifications[ntfn.ConfRequest]
3✔
650
        if !ok {
6✔
651
                // If this is the first registration for this request, construct
3✔
652
                // a confSet to coalesce all notifications for the same request.
3✔
653
                confSet = newConfNtfnSet()
3✔
654
                n.confNotifications[ntfn.ConfRequest] = confSet
3✔
655
        }
3✔
656
        confSet.ntfns[ntfn.ConfID] = ntfn
3✔
657

3✔
658
        switch confSet.rescanStatus {
3✔
659

660
        // A prior rescan has already completed and we are actively watching at
661
        // tip for this request.
662
        case rescanComplete:
3✔
663
                // If the confirmation details for this set of notifications has
3✔
664
                // already been found, we'll attempt to deliver them immediately
3✔
665
                // to this client.
3✔
666
                Log.Debugf("Attempting to dispatch confirmation for %v on "+
3✔
667
                        "registration since rescan has finished",
3✔
668
                        ntfn.ConfRequest)
3✔
669

3✔
670
                // The default notification we assigned above includes the
3✔
671
                // block along with the rest of the details. However not all
3✔
672
                // clients want the block, so we make a copy here w/o the block
3✔
673
                // if needed so we can give clients only what they ask for.
3✔
674
                confDetails := confSet.details
3✔
675
                if !ntfn.includeBlock && confDetails != nil {
6✔
676
                        confDetailsCopy := *confDetails
3✔
677
                        confDetailsCopy.Block = nil
3✔
678

3✔
679
                        confDetails = &confDetailsCopy
3✔
680
                }
3✔
681

682
                err := n.dispatchConfDetails(ntfn, confDetails)
3✔
683
                if err != nil {
3✔
684
                        return nil, err
×
685
                }
×
686

687
                return &ConfRegistration{
3✔
688
                        Event:              ntfn.Event,
3✔
689
                        HistoricalDispatch: nil,
3✔
690
                        Height:             n.currentHeight,
3✔
691
                }, nil
3✔
692

693
        // A rescan is already in progress, return here to prevent dispatching
694
        // another. When the rescan returns, this notification's details will be
695
        // updated as well.
696
        case rescanPending:
3✔
697
                Log.Debugf("Waiting for pending rescan to finish before "+
3✔
698
                        "notifying %v at tip", ntfn.ConfRequest)
3✔
699

3✔
700
                return &ConfRegistration{
3✔
701
                        Event:              ntfn.Event,
3✔
702
                        HistoricalDispatch: nil,
3✔
703
                        Height:             n.currentHeight,
3✔
704
                }, nil
3✔
705

706
        // If no rescan has been dispatched, attempt to do so now.
707
        case rescanNotStarted:
3✔
708
        }
709

710
        // If the provided or cached height hint indicates that the
711
        // transaction with the given txid/output script is to be confirmed at a
712
        // height greater than the notifier's current height, we'll refrain from
713
        // spawning a historical dispatch.
714
        if startHeight > n.currentHeight {
6✔
715
                Log.Debugf("Height hint is above current height, not "+
3✔
716
                        "dispatching historical confirmation rescan for %v",
3✔
717
                        ntfn.ConfRequest)
3✔
718

3✔
719
                // Set the rescan status to complete, which will allow the
3✔
720
                // notifier to start delivering messages for this set
3✔
721
                // immediately.
3✔
722
                confSet.rescanStatus = rescanComplete
3✔
723
                return &ConfRegistration{
3✔
724
                        Event:              ntfn.Event,
3✔
725
                        HistoricalDispatch: nil,
3✔
726
                        Height:             n.currentHeight,
3✔
727
                }, nil
3✔
728
        }
3✔
729

730
        Log.Debugf("Dispatching historical confirmation rescan for %v",
3✔
731
                ntfn.ConfRequest)
3✔
732

3✔
733
        // Construct the parameters for historical dispatch, scanning the range
3✔
734
        // of blocks between our best known height hint and the notifier's
3✔
735
        // current height. The notifier will begin also watching for
3✔
736
        // confirmations at tip starting with the next block.
3✔
737
        dispatch := &HistoricalConfDispatch{
3✔
738
                ConfRequest: ntfn.ConfRequest,
3✔
739
                StartHeight: startHeight,
3✔
740
                EndHeight:   n.currentHeight,
3✔
741
        }
3✔
742

3✔
743
        // Set this confSet's status to pending, ensuring subsequent
3✔
744
        // registrations don't also attempt a dispatch.
3✔
745
        confSet.rescanStatus = rescanPending
3✔
746

3✔
747
        return &ConfRegistration{
3✔
748
                Event:              ntfn.Event,
3✔
749
                HistoricalDispatch: dispatch,
3✔
750
                Height:             n.currentHeight,
3✔
751
        }, nil
3✔
752
}
753

754
// CancelConf cancels an existing request for a spend notification of an
755
// outpoint/output script. The request is identified by its spend ID.
756
func (n *TxNotifier) CancelConf(confRequest ConfRequest, confID uint64) {
3✔
757
        select {
3✔
758
        case <-n.quit:
×
759
                return
×
760
        default:
3✔
761
        }
762

763
        n.Lock()
3✔
764
        defer n.Unlock()
3✔
765

3✔
766
        confSet, ok := n.confNotifications[confRequest]
3✔
767
        if !ok {
3✔
768
                return
×
769
        }
×
770
        ntfn, ok := confSet.ntfns[confID]
3✔
771
        if !ok {
3✔
772
                return
×
773
        }
×
774

775
        Log.Debugf("Canceling confirmation notification: conf_id=%d, %v",
3✔
776
                confID, confRequest)
3✔
777

3✔
778
        // We'll close all the notification channels to let the client know
3✔
779
        // their cancel request has been fulfilled.
3✔
780
        close(ntfn.Event.Confirmed)
3✔
781
        close(ntfn.Event.Updates)
3✔
782
        close(ntfn.Event.NegativeConf)
3✔
783

3✔
784
        // Finally, we'll clean up any lingering references to this
3✔
785
        // notification.
3✔
786
        delete(confSet.ntfns, confID)
3✔
787

3✔
788
        // Remove the queued confirmation notification if the transaction has
3✔
789
        // already confirmed, but hasn't met its required number of
3✔
790
        // confirmations.
3✔
791
        if confSet.details != nil {
6✔
792
                confHeight := confSet.details.BlockHeight +
3✔
793
                        ntfn.NumConfirmations - 1
3✔
794
                delete(n.ntfnsByConfirmHeight[confHeight], ntfn)
3✔
795
        }
3✔
796
}
797

798
// UpdateConfDetails attempts to update the confirmation details for an active
799
// notification within the notifier. This should only be used in the case of a
800
// transaction/output script that has confirmed before the notifier's current
801
// height.
802
//
803
// NOTE: The notification should be registered first to ensure notifications are
804
// dispatched correctly.
805
func (n *TxNotifier) UpdateConfDetails(confRequest ConfRequest,
806
        details *TxConfirmation) error {
3✔
807

3✔
808
        select {
3✔
809
        case <-n.quit:
×
810
                return ErrTxNotifierExiting
×
811
        default:
3✔
812
        }
813

814
        // Ensure we hold the lock throughout handling the notification to
815
        // prevent the notifier from advancing its height underneath us.
816
        n.Lock()
3✔
817
        defer n.Unlock()
3✔
818

3✔
819
        // First, we'll determine whether we have an active confirmation
3✔
820
        // notification for the given txid/script.
3✔
821
        confSet, ok := n.confNotifications[confRequest]
3✔
822
        if !ok {
3✔
823
                return fmt.Errorf("confirmation notification for %v not found",
×
824
                        confRequest)
×
825
        }
×
826

827
        // If the confirmation details were already found at tip, all existing
828
        // notifications will have been dispatched or queued for dispatch. We
829
        // can exit early to avoid sending too many notifications on the
830
        // buffered channels.
831
        if confSet.details != nil {
3✔
832
                return nil
×
833
        }
×
834

835
        // The historical dispatch has been completed for this confSet. We'll
836
        // update the rescan status and cache any details that were found. If
837
        // the details are nil, that implies we did not find them and will
838
        // continue to watch for them at tip.
839
        confSet.rescanStatus = rescanComplete
3✔
840

3✔
841
        // The notifier has yet to reach the height at which the
3✔
842
        // transaction/output script was included in a block, so we should defer
3✔
843
        // until handling it then within ConnectTip.
3✔
844
        if details == nil {
6✔
845
                Log.Debugf("Confirmation details for %v not found during "+
3✔
846
                        "historical dispatch, waiting to dispatch at tip",
3✔
847
                        confRequest)
3✔
848

3✔
849
                // We'll commit the current height as the confirm hint to
3✔
850
                // prevent another potentially long rescan if we restart before
3✔
851
                // a new block comes in.
3✔
852
                err := n.confirmHintCache.CommitConfirmHint(
3✔
853
                        n.currentHeight, confRequest,
3✔
854
                )
3✔
855
                if err != nil {
3✔
856
                        // The error is not fatal as this is an optimistic
×
857
                        // optimization, so we'll avoid returning an error.
×
858
                        Log.Debugf("Unable to update confirm hint to %d for "+
×
859
                                "%v: %v", n.currentHeight, confRequest, err)
×
860
                }
×
861

862
                return nil
3✔
863
        }
864

865
        if details.BlockHeight > n.currentHeight {
3✔
866
                Log.Debugf("Confirmation details for %v found above current "+
×
867
                        "height, waiting to dispatch at tip", confRequest)
×
868

×
869
                return nil
×
870
        }
×
871

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

3✔
874
        err := n.confirmHintCache.CommitConfirmHint(
3✔
875
                details.BlockHeight, confRequest,
3✔
876
        )
3✔
877
        if err != nil {
3✔
878
                // The error is not fatal, so we should not return an error to
×
879
                // the caller.
×
880
                Log.Errorf("Unable to update confirm hint to %d for %v: %v",
×
881
                        details.BlockHeight, confRequest, err)
×
882
        }
×
883

884
        // Cache the details found in the rescan and attempt to dispatch any
885
        // notifications that have not yet been delivered.
886
        confSet.details = details
3✔
887
        for _, ntfn := range confSet.ntfns {
6✔
888
                // The default notification we assigned above includes the
3✔
889
                // block along with the rest of the details. However not all
3✔
890
                // clients want the block, so we make a copy here w/o the block
3✔
891
                // if needed so we can give clients only what they ask for.
3✔
892
                confDetails := *details
3✔
893
                if !ntfn.includeBlock {
6✔
894
                        confDetails.Block = nil
3✔
895
                }
3✔
896

897
                err = n.dispatchConfDetails(ntfn, &confDetails)
3✔
898
                if err != nil {
3✔
899
                        return err
×
900
                }
×
901
        }
902

903
        return nil
3✔
904
}
905

906
// dispatchConfDetails attempts to cache and dispatch details to a particular
907
// client if the transaction/output script has sufficiently confirmed. If the
908
// provided details are nil, this method will be a no-op.
909
func (n *TxNotifier) dispatchConfDetails(
910
        ntfn *ConfNtfn, details *TxConfirmation) error {
3✔
911

3✔
912
        // If there are no conf details to dispatch or if the notification has
3✔
913
        // already been dispatched, then we can skip dispatching to this
3✔
914
        // client.
3✔
915
        if details == nil || ntfn.dispatched {
6✔
916
                Log.Debugf("Skipping dispatch of conf details(%v) for "+
3✔
917
                        "request %v, dispatched=%v", details, ntfn.ConfRequest,
3✔
918
                        ntfn.dispatched)
3✔
919

3✔
920
                return nil
3✔
921
        }
3✔
922

923
        // Now, we'll examine whether the transaction/output script of this
924
        // request has reached its required number of confirmations. If it has,
925
        // we'll dispatch a confirmation notification to the caller.
926
        confHeight := details.BlockHeight + ntfn.NumConfirmations - 1
3✔
927
        if confHeight <= n.currentHeight {
6✔
928
                Log.Debugf("Dispatching %v confirmation notification for %v",
3✔
929
                        ntfn.NumConfirmations, ntfn.ConfRequest)
3✔
930

3✔
931
                // We'll send a 0 value to the Updates channel,
3✔
932
                // indicating that the transaction/output script has already
3✔
933
                // been confirmed.
3✔
934
                select {
3✔
935
                case ntfn.Event.Updates <- 0:
3✔
936
                case <-n.quit:
×
937
                        return ErrTxNotifierExiting
×
938
                }
939

940
                select {
3✔
941
                case ntfn.Event.Confirmed <- details:
3✔
942
                        ntfn.dispatched = true
3✔
943
                case <-n.quit:
×
944
                        return ErrTxNotifierExiting
×
945
                }
946
        } else {
3✔
947
                Log.Debugf("Queueing %v confirmation notification for %v at tip ",
3✔
948
                        ntfn.NumConfirmations, ntfn.ConfRequest)
3✔
949

3✔
950
                // Otherwise, we'll keep track of the notification
3✔
951
                // request by the height at which we should dispatch the
3✔
952
                // confirmation notification.
3✔
953
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
3✔
954
                if !exists {
6✔
955
                        ntfnSet = make(map[*ConfNtfn]struct{})
3✔
956
                        n.ntfnsByConfirmHeight[confHeight] = ntfnSet
3✔
957
                }
3✔
958
                ntfnSet[ntfn] = struct{}{}
3✔
959

3✔
960
                // We'll also send an update to the client of how many
3✔
961
                // confirmations are left for the transaction/output script to
3✔
962
                // be confirmed.
3✔
963
                numConfsLeft := confHeight - n.currentHeight
3✔
964
                select {
3✔
965
                case ntfn.Event.Updates <- numConfsLeft:
3✔
966
                case <-n.quit:
×
967
                        return ErrTxNotifierExiting
×
968
                }
969
        }
970

971
        // As a final check, we'll also watch the transaction/output script if
972
        // it's still possible for it to get reorged out of the chain.
973
        reorgSafeHeight := details.BlockHeight + n.reorgSafetyLimit
3✔
974
        if reorgSafeHeight > n.currentHeight {
6✔
975
                txSet, exists := n.confsByInitialHeight[details.BlockHeight]
3✔
976
                if !exists {
6✔
977
                        txSet = make(map[ConfRequest]struct{})
3✔
978
                        n.confsByInitialHeight[details.BlockHeight] = txSet
3✔
979
                }
3✔
980
                txSet[ntfn.ConfRequest] = struct{}{}
3✔
981
        }
982

983
        return nil
3✔
984
}
985

986
// newSpendNtfn validates all of the parameters required to successfully create
987
// and register a spend notification.
988
func (n *TxNotifier) newSpendNtfn(outpoint *wire.OutPoint,
989
        pkScript []byte, heightHint uint32) (*SpendNtfn, error) {
3✔
990

3✔
991
        // An accompanying output script must always be provided.
3✔
992
        if len(pkScript) == 0 {
3✔
993
                return nil, ErrNoScript
×
994
        }
×
995

996
        // A height hint must be provided to prevent scanning from the genesis
997
        // block.
998
        if heightHint == 0 {
3✔
999
                return nil, ErrNoHeightHint
×
1000
        }
×
1001

1002
        // Ensure the output script is of a supported type.
1003
        spendRequest, err := NewSpendRequest(outpoint, pkScript)
3✔
1004
        if err != nil {
6✔
1005
                return nil, err
3✔
1006
        }
3✔
1007

1008
        spendID := atomic.AddUint64(&n.spendClientCounter, 1)
3✔
1009
        return &SpendNtfn{
3✔
1010
                SpendID:      spendID,
3✔
1011
                SpendRequest: spendRequest,
3✔
1012
                Event: NewSpendEvent(func() {
6✔
1013
                        n.CancelSpend(spendRequest, spendID)
3✔
1014
                }),
3✔
1015
                HeightHint: heightHint,
1016
        }, nil
1017
}
1018

1019
// RegisterSpend handles a new spend notification request. The client will be
1020
// notified once the outpoint/output script is detected as spent within the
1021
// chain.
1022
//
1023
// NOTE: If the outpoint/output script has already been spent within the chain
1024
// before the notifier's current tip, the spend details must be provided with
1025
// the UpdateSpendDetails method, otherwise we will wait for the outpoint/output
1026
// script to be spent at tip, even though it already has.
1027
func (n *TxNotifier) RegisterSpend(outpoint *wire.OutPoint, pkScript []byte,
1028
        heightHint uint32) (*SpendRegistration, error) {
3✔
1029

3✔
1030
        select {
3✔
1031
        case <-n.quit:
×
1032
                return nil, ErrTxNotifierExiting
×
1033
        default:
3✔
1034
        }
1035

1036
        // We'll start by performing a series of validation checks.
1037
        ntfn, err := n.newSpendNtfn(outpoint, pkScript, heightHint)
3✔
1038
        if err != nil {
6✔
1039
                return nil, err
3✔
1040
        }
3✔
1041

1042
        // Before proceeding to register the notification, we'll query our spend
1043
        // hint cache to determine whether a better one exists.
1044
        startHeight := ntfn.HeightHint
3✔
1045
        hint, err := n.spendHintCache.QuerySpendHint(ntfn.SpendRequest)
3✔
1046
        if err == nil {
6✔
1047
                if hint > startHeight {
6✔
1048
                        Log.Debugf("Using height hint %d retrieved from cache "+
3✔
1049
                                "for %v instead of %d for spend subscription",
3✔
1050
                                hint, ntfn.SpendRequest, startHeight)
3✔
1051
                        startHeight = hint
3✔
1052
                }
3✔
1053
        } else if err != ErrSpendHintNotFound {
3✔
1054
                Log.Errorf("Unable to query spend hint for %v: %v",
×
1055
                        ntfn.SpendRequest, err)
×
1056
        }
×
1057

1058
        n.Lock()
3✔
1059
        defer n.Unlock()
3✔
1060

3✔
1061
        Log.Debugf("New spend subscription: spend_id=%d, %v, height_hint=%d",
3✔
1062
                ntfn.SpendID, ntfn.SpendRequest, startHeight)
3✔
1063

3✔
1064
        // Keep track of the notification request so that we can properly
3✔
1065
        // dispatch a spend notification later on.
3✔
1066
        spendSet, ok := n.spendNotifications[ntfn.SpendRequest]
3✔
1067
        if !ok {
6✔
1068
                // If this is the first registration for the request, we'll
3✔
1069
                // construct a spendNtfnSet to coalesce all notifications.
3✔
1070
                spendSet = newSpendNtfnSet()
3✔
1071
                n.spendNotifications[ntfn.SpendRequest] = spendSet
3✔
1072
        }
3✔
1073
        spendSet.ntfns[ntfn.SpendID] = ntfn
3✔
1074

3✔
1075
        // We'll now let the caller know whether a historical rescan is needed
3✔
1076
        // depending on the current rescan status.
3✔
1077
        switch spendSet.rescanStatus {
3✔
1078

1079
        // If the spending details for this request have already been determined
1080
        // and cached, then we can use them to immediately dispatch the spend
1081
        // notification to the client.
1082
        case rescanComplete:
3✔
1083
                Log.Debugf("Attempting to dispatch spend for %v on "+
3✔
1084
                        "registration since rescan has finished",
3✔
1085
                        ntfn.SpendRequest)
3✔
1086

3✔
1087
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1088
                if err != nil {
3✔
1089
                        return nil, err
×
1090
                }
×
1091

1092
                return &SpendRegistration{
3✔
1093
                        Event:              ntfn.Event,
3✔
1094
                        HistoricalDispatch: nil,
3✔
1095
                        Height:             n.currentHeight,
3✔
1096
                }, nil
3✔
1097

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

3✔
1104
                return &SpendRegistration{
3✔
1105
                        Event:              ntfn.Event,
3✔
1106
                        HistoricalDispatch: nil,
3✔
1107
                        Height:             n.currentHeight,
3✔
1108
                }, nil
3✔
1109

1110
        // Otherwise, we'll fall through and let the caller know that a rescan
1111
        // should be dispatched to determine whether the request has already
1112
        // been spent.
1113
        case rescanNotStarted:
3✔
1114
        }
1115

1116
        // However, if the spend hint, either provided by the caller or
1117
        // retrieved from the cache, is found to be at a later height than the
1118
        // TxNotifier is aware of, then we'll refrain from dispatching a
1119
        // historical rescan and wait for the spend to come in at tip.
1120
        if startHeight > n.currentHeight {
3✔
1121
                Log.Debugf("Spend hint of %d for %v is above current height %d",
×
1122
                        startHeight, ntfn.SpendRequest, n.currentHeight)
×
1123

×
1124
                // We'll also set the rescan status as complete to ensure that
×
1125
                // spend hints for this request get updated upon
×
1126
                // connected/disconnected blocks.
×
1127
                spendSet.rescanStatus = rescanComplete
×
1128
                return &SpendRegistration{
×
1129
                        Event:              ntfn.Event,
×
1130
                        HistoricalDispatch: nil,
×
1131
                        Height:             n.currentHeight,
×
1132
                }, nil
×
1133
        }
×
1134

1135
        // We'll set the rescan status to pending to ensure subsequent
1136
        // notifications don't also attempt a historical dispatch.
1137
        spendSet.rescanStatus = rescanPending
3✔
1138

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

3✔
1142
        return &SpendRegistration{
3✔
1143
                Event: ntfn.Event,
3✔
1144
                HistoricalDispatch: &HistoricalSpendDispatch{
3✔
1145
                        SpendRequest: ntfn.SpendRequest,
3✔
1146
                        StartHeight:  startHeight,
3✔
1147
                        EndHeight:    n.currentHeight,
3✔
1148
                },
3✔
1149
                Height: n.currentHeight,
3✔
1150
        }, nil
3✔
1151
}
1152

1153
// CancelSpend cancels an existing request for a spend notification of an
1154
// outpoint/output script. The request is identified by its spend ID.
1155
func (n *TxNotifier) CancelSpend(spendRequest SpendRequest, spendID uint64) {
3✔
1156
        select {
3✔
1157
        case <-n.quit:
×
1158
                return
×
1159
        default:
3✔
1160
        }
1161

1162
        n.Lock()
3✔
1163
        defer n.Unlock()
3✔
1164

3✔
1165
        spendSet, ok := n.spendNotifications[spendRequest]
3✔
1166
        if !ok {
3✔
1167
                return
×
1168
        }
×
1169
        ntfn, ok := spendSet.ntfns[spendID]
3✔
1170
        if !ok {
3✔
1171
                return
×
1172
        }
×
1173

1174
        Log.Debugf("Canceling spend notification: spend_id=%d, %v", spendID,
3✔
1175
                spendRequest)
3✔
1176

3✔
1177
        // We'll close all the notification channels to let the client know
3✔
1178
        // their cancel request has been fulfilled.
3✔
1179
        close(ntfn.Event.Spend)
3✔
1180
        close(ntfn.Event.Reorg)
3✔
1181
        close(ntfn.Event.Done)
3✔
1182
        delete(spendSet.ntfns, spendID)
3✔
1183
}
1184

1185
// ProcessRelevantSpendTx processes a transaction provided externally. This will
1186
// check whether the transaction is relevant to the notifier if it spends any
1187
// outpoints/output scripts for which we currently have registered notifications
1188
// for. If it is relevant, spend notifications will be dispatched to the caller.
1189
func (n *TxNotifier) ProcessRelevantSpendTx(tx *btcutil.Tx,
1190
        blockHeight uint32) error {
3✔
1191

3✔
1192
        select {
3✔
1193
        case <-n.quit:
×
1194
                return ErrTxNotifierExiting
×
1195
        default:
3✔
1196
        }
1197

1198
        // Ensure we hold the lock throughout handling the notification to
1199
        // prevent the notifier from advancing its height underneath us.
1200
        n.Lock()
3✔
1201
        defer n.Unlock()
3✔
1202

3✔
1203
        // We'll use a channel to coalesce all the spend requests that this
3✔
1204
        // transaction fulfills.
3✔
1205
        type spend struct {
3✔
1206
                request *SpendRequest
3✔
1207
                details *SpendDetail
3✔
1208
        }
3✔
1209

3✔
1210
        // We'll set up the onSpend filter callback to gather all the fulfilled
3✔
1211
        // spends requests within this transaction.
3✔
1212
        var spends []spend
3✔
1213
        onSpend := func(request SpendRequest, details *SpendDetail) {
6✔
1214
                spends = append(spends, spend{&request, details})
3✔
1215
        }
3✔
1216
        n.filterTx(nil, tx, blockHeight, nil, onSpend)
3✔
1217

3✔
1218
        // After the transaction has been filtered, we can finally dispatch
3✔
1219
        // notifications for each request.
3✔
1220
        for _, spend := range spends {
6✔
1221
                err := n.updateSpendDetails(*spend.request, spend.details)
3✔
1222
                if err != nil {
3✔
1223
                        return err
×
1224
                }
×
1225
        }
1226

1227
        return nil
3✔
1228
}
1229

1230
// UpdateSpendDetails attempts to update the spend details for all active spend
1231
// notification requests for an outpoint/output script. This method should be
1232
// used once a historical scan of the chain has finished. If the historical scan
1233
// did not find a spending transaction for it, the spend details may be nil.
1234
//
1235
// NOTE: A notification request for the outpoint/output script must be
1236
// registered first to ensure notifications are delivered.
1237
func (n *TxNotifier) UpdateSpendDetails(spendRequest SpendRequest,
1238
        details *SpendDetail) error {
3✔
1239

3✔
1240
        select {
3✔
1241
        case <-n.quit:
×
1242
                return ErrTxNotifierExiting
×
1243
        default:
3✔
1244
        }
1245

1246
        // Ensure we hold the lock throughout handling the notification to
1247
        // prevent the notifier from advancing its height underneath us.
1248
        n.Lock()
3✔
1249
        defer n.Unlock()
3✔
1250

3✔
1251
        return n.updateSpendDetails(spendRequest, details)
3✔
1252
}
1253

1254
// updateSpendDetails attempts to update the spend details for all active spend
1255
// notification requests for an outpoint/output script. This method should be
1256
// used once a historical scan of the chain has finished. If the historical scan
1257
// did not find a spending transaction for it, the spend details may be nil.
1258
//
1259
// NOTE: This method must be called with the TxNotifier's lock held.
1260
func (n *TxNotifier) updateSpendDetails(spendRequest SpendRequest,
1261
        details *SpendDetail) error {
3✔
1262

3✔
1263
        // Mark the ongoing historical rescan for this request as finished. This
3✔
1264
        // will allow us to update the spend hints for it at tip.
3✔
1265
        spendSet, ok := n.spendNotifications[spendRequest]
3✔
1266
        if !ok {
3✔
1267
                return fmt.Errorf("spend notification for %v not found",
×
1268
                        spendRequest)
×
1269
        }
×
1270

1271
        // If the spend details have already been found either at tip, then the
1272
        // notifications should have already been dispatched, so we can exit
1273
        // early to prevent sending duplicate notifications.
1274
        if spendSet.details != nil {
4✔
1275
                return nil
1✔
1276
        }
1✔
1277

1278
        // Since the historical rescan has completed for this request, we'll
1279
        // mark its rescan status as complete in order to ensure that the
1280
        // TxNotifier can properly update its spend hints upon
1281
        // connected/disconnected blocks.
1282
        spendSet.rescanStatus = rescanComplete
3✔
1283

3✔
1284
        // If the historical rescan was not able to find a spending transaction
3✔
1285
        // for this request, then we can track the spend at tip.
3✔
1286
        if details == nil {
6✔
1287
                // We'll commit the current height as the spend hint to prevent
3✔
1288
                // another potentially long rescan if we restart before a new
3✔
1289
                // block comes in.
3✔
1290
                err := n.spendHintCache.CommitSpendHint(
3✔
1291
                        n.currentHeight, spendRequest,
3✔
1292
                )
3✔
1293
                if err != nil {
3✔
1294
                        // The error is not fatal as this is an optimistic
×
1295
                        // optimization, so we'll avoid returning an error.
×
1296
                        Log.Debugf("Unable to update spend hint to %d for %v: %v",
×
1297
                                n.currentHeight, spendRequest, err)
×
1298
                }
×
1299

1300
                Log.Debugf("Updated spend hint to height=%v for unconfirmed "+
3✔
1301
                        "spend request %v", n.currentHeight, spendRequest)
3✔
1302
                return nil
3✔
1303
        }
1304

1305
        // Return an error if the witness data is not present in the spending
1306
        // transaction.
1307
        //
1308
        // NOTE: if the witness stack is empty, we will do a critical log which
1309
        // shuts down the node.
1310
        if !details.HasSpenderWitness() {
3✔
1311
                Log.Criticalf("Found spending tx for outpoint=%v, but the "+
×
1312
                        "transaction %v does not have witness",
×
1313
                        spendRequest.OutPoint, details.SpendingTx.TxHash())
×
1314

×
1315
                return ErrEmptyWitnessStack
×
1316
        }
×
1317

1318
        // If the historical rescan found the spending transaction for this
1319
        // request, but it's at a later height than the notifier (this can
1320
        // happen due to latency with the backend during a reorg), then we'll
1321
        // defer handling the notification until the notifier has caught up to
1322
        // such height.
1323
        if uint32(details.SpendingHeight) > n.currentHeight {
6✔
1324
                return nil
3✔
1325
        }
3✔
1326

1327
        // Now that we've determined the request has been spent, we'll commit
1328
        // its spending height as its hint in the cache and dispatch
1329
        // notifications to all of its respective clients.
1330
        err := n.spendHintCache.CommitSpendHint(
3✔
1331
                uint32(details.SpendingHeight), spendRequest,
3✔
1332
        )
3✔
1333
        if err != nil {
3✔
1334
                // The error is not fatal as this is an optimistic optimization,
×
1335
                // so we'll avoid returning an error.
×
1336
                Log.Debugf("Unable to update spend hint to %d for %v: %v",
×
1337
                        details.SpendingHeight, spendRequest, err)
×
1338
        }
×
1339

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

3✔
1343
        spendSet.details = details
3✔
1344
        for _, ntfn := range spendSet.ntfns {
6✔
1345
                err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1346
                if err != nil {
3✔
1347
                        return err
×
1348
                }
×
1349
        }
1350

1351
        return nil
3✔
1352
}
1353

1354
// dispatchSpendDetails dispatches a spend notification to the client.
1355
//
1356
// NOTE: This must be called with the TxNotifier's lock held.
1357
func (n *TxNotifier) dispatchSpendDetails(ntfn *SpendNtfn, details *SpendDetail) error {
3✔
1358
        // If there are no spend details to dispatch or if the notification has
3✔
1359
        // already been dispatched, then we can skip dispatching to this client.
3✔
1360
        if details == nil || ntfn.dispatched {
6✔
1361
                Log.Debugf("Skipping dispatch of spend details(%v) for "+
3✔
1362
                        "request %v, dispatched=%v", details, ntfn.SpendRequest,
3✔
1363
                        ntfn.dispatched)
3✔
1364
                return nil
3✔
1365
        }
3✔
1366

1367
        Log.Debugf("Dispatching confirmed spend notification for %v at "+
3✔
1368
                "current height=%d: %v", ntfn.SpendRequest, n.currentHeight,
3✔
1369
                details)
3✔
1370

3✔
1371
        select {
3✔
1372
        case ntfn.Event.Spend <- details:
3✔
1373
                ntfn.dispatched = true
3✔
1374
        case <-n.quit:
×
1375
                return ErrTxNotifierExiting
×
1376
        }
1377

1378
        spendHeight := uint32(details.SpendingHeight)
3✔
1379

3✔
1380
        // We also add to spendsByHeight to notify on chain reorgs.
3✔
1381
        reorgSafeHeight := spendHeight + n.reorgSafetyLimit
3✔
1382
        if reorgSafeHeight > n.currentHeight {
6✔
1383
                txSet, exists := n.spendsByHeight[spendHeight]
3✔
1384
                if !exists {
6✔
1385
                        txSet = make(map[SpendRequest]struct{})
3✔
1386
                        n.spendsByHeight[spendHeight] = txSet
3✔
1387
                }
3✔
1388
                txSet[ntfn.SpendRequest] = struct{}{}
3✔
1389
        }
1390

1391
        return nil
3✔
1392
}
1393

1394
// ConnectTip handles a new block extending the current chain. It will go
1395
// through every transaction and determine if it is relevant to any of its
1396
// clients. A transaction can be relevant in either of the following two ways:
1397
//
1398
//  1. One of the inputs in the transaction spends an outpoint/output script
1399
//     for which we currently have an active spend registration for.
1400
//
1401
//  2. The transaction has a txid or output script for which we currently have
1402
//     an active confirmation registration for.
1403
//
1404
// In the event that the transaction is relevant, a confirmation/spend
1405
// notification will be queued for dispatch to the relevant clients.
1406
// Confirmation notifications will only be dispatched for transactions/output
1407
// scripts that have met the required number of confirmations required by the
1408
// client.
1409
//
1410
// NOTE: In order to actually dispatch the relevant transaction notifications to
1411
// clients, NotifyHeight must be called with the same block height in order to
1412
// maintain correctness.
1413
func (n *TxNotifier) ConnectTip(block *btcutil.Block,
1414
        blockHeight uint32) error {
3✔
1415

3✔
1416
        select {
3✔
1417
        case <-n.quit:
×
1418
                return ErrTxNotifierExiting
×
1419
        default:
3✔
1420
        }
1421

1422
        n.Lock()
3✔
1423
        defer n.Unlock()
3✔
1424

3✔
1425
        if blockHeight != n.currentHeight+1 {
3✔
1426
                return fmt.Errorf("received blocks out of order: "+
×
1427
                        "current height=%d, new height=%d",
×
1428
                        n.currentHeight, blockHeight)
×
1429
        }
×
1430
        n.currentHeight++
3✔
1431
        n.reorgDepth = 0
3✔
1432

3✔
1433
        // First, we'll iterate over all the transactions found in this block to
3✔
1434
        // determine if it includes any relevant transactions to the TxNotifier.
3✔
1435
        if block != nil {
6✔
1436
                Log.Debugf("Filtering %d txns for %d spend requests at "+
3✔
1437
                        "height %d", len(block.Transactions()),
3✔
1438
                        len(n.spendNotifications), blockHeight)
3✔
1439

3✔
1440
                for _, tx := range block.Transactions() {
6✔
1441
                        n.filterTx(
3✔
1442
                                block, tx, blockHeight,
3✔
1443
                                n.handleConfDetailsAtTip,
3✔
1444
                                n.handleSpendDetailsAtTip,
3✔
1445
                        )
3✔
1446
                }
3✔
1447
        }
1448

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

3✔
1454
        // Finally, we'll clear the entries from our set of notifications for
3✔
1455
        // requests that are no longer under the risk of being reorged out of
3✔
1456
        // the chain.
3✔
1457
        if blockHeight >= n.reorgSafetyLimit {
6✔
1458
                matureBlockHeight := blockHeight - n.reorgSafetyLimit
3✔
1459
                for confRequest := range n.confsByInitialHeight[matureBlockHeight] {
3✔
1460
                        confSet := n.confNotifications[confRequest]
×
1461
                        for _, ntfn := range confSet.ntfns {
×
1462
                                select {
×
1463
                                case ntfn.Event.Done <- struct{}{}:
×
1464
                                case <-n.quit:
×
1465
                                        return ErrTxNotifierExiting
×
1466
                                }
1467
                        }
1468

1469
                        delete(n.confNotifications, confRequest)
×
1470
                }
1471
                delete(n.confsByInitialHeight, matureBlockHeight)
3✔
1472

3✔
1473
                for spendRequest := range n.spendsByHeight[matureBlockHeight] {
3✔
1474
                        spendSet := n.spendNotifications[spendRequest]
×
1475
                        for _, ntfn := range spendSet.ntfns {
×
1476
                                select {
×
1477
                                case ntfn.Event.Done <- struct{}{}:
×
1478
                                case <-n.quit:
×
1479
                                        return ErrTxNotifierExiting
×
1480
                                }
1481
                        }
1482

1483
                        Log.Debugf("Deleting mature spend request %v at "+
×
1484
                                "height=%d", spendRequest, blockHeight)
×
1485
                        delete(n.spendNotifications, spendRequest)
×
1486
                }
1487
                delete(n.spendsByHeight, matureBlockHeight)
3✔
1488
        }
1489

1490
        return nil
3✔
1491
}
1492

1493
// filterTx determines whether the transaction spends or confirms any
1494
// outstanding pending requests. The onConf and onSpend callbacks can be used to
1495
// retrieve all the requests fulfilled by this transaction as they occur.
1496
func (n *TxNotifier) filterTx(block *btcutil.Block, tx *btcutil.Tx,
1497
        blockHeight uint32, onConf func(ConfRequest, *TxConfirmation),
1498
        onSpend func(SpendRequest, *SpendDetail)) {
3✔
1499

3✔
1500
        // In order to determine if this transaction is relevant to the
3✔
1501
        // notifier, we'll check its inputs for any outstanding spend
3✔
1502
        // requests.
3✔
1503
        txHash := tx.Hash()
3✔
1504
        if onSpend != nil {
6✔
1505
                // notifyDetails is a helper closure that will construct the
3✔
1506
                // spend details of a request and hand them off to the onSpend
3✔
1507
                // callback.
3✔
1508
                notifyDetails := func(spendRequest SpendRequest,
3✔
1509
                        prevOut wire.OutPoint, inputIdx uint32) {
6✔
1510

3✔
1511
                        Log.Debugf("Found spend of %v: spend_tx=%v, "+
3✔
1512
                                "block_height=%d", spendRequest, txHash,
3✔
1513
                                blockHeight)
3✔
1514

3✔
1515
                        onSpend(spendRequest, &SpendDetail{
3✔
1516
                                SpentOutPoint:     &prevOut,
3✔
1517
                                SpenderTxHash:     txHash,
3✔
1518
                                SpendingTx:        tx.MsgTx(),
3✔
1519
                                SpenderInputIndex: inputIdx,
3✔
1520
                                SpendingHeight:    int32(blockHeight),
3✔
1521
                        })
3✔
1522
                }
3✔
1523

1524
                for i, txIn := range tx.MsgTx().TxIn {
6✔
1525
                        // We'll re-derive the script of the output being spent
3✔
1526
                        // to determine if the inputs spends any registered
3✔
1527
                        // requests.
3✔
1528
                        prevOut := txIn.PreviousOutPoint
3✔
1529
                        pkScript, err := txscript.ComputePkScript(
3✔
1530
                                txIn.SignatureScript, txIn.Witness,
3✔
1531
                        )
3✔
1532
                        if err != nil {
3✔
1533
                                continue
×
1534
                        }
1535
                        spendRequest := SpendRequest{
3✔
1536
                                OutPoint: prevOut,
3✔
1537
                                PkScript: pkScript,
3✔
1538
                        }
3✔
1539

3✔
1540
                        // If we have any, we'll record their spend height so
3✔
1541
                        // that notifications get dispatched to the respective
3✔
1542
                        // clients.
3✔
1543
                        if _, ok := n.spendNotifications[spendRequest]; ok {
6✔
1544
                                notifyDetails(spendRequest, prevOut, uint32(i))
3✔
1545
                        }
3✔
1546

1547
                        // Now try with an empty taproot key pkScript, since we
1548
                        // cannot derive the spent pkScript directly from the
1549
                        // witness. But we have the outpoint, which should be
1550
                        // enough.
1551
                        spendRequest.PkScript = ZeroTaprootPkScript
3✔
1552
                        if _, ok := n.spendNotifications[spendRequest]; ok {
6✔
1553
                                notifyDetails(spendRequest, prevOut, uint32(i))
3✔
1554
                        }
3✔
1555

1556
                        // Restore the pkScript but try with a zero outpoint
1557
                        // instead (won't be possible for Taproot).
1558
                        spendRequest.PkScript = pkScript
3✔
1559
                        spendRequest.OutPoint = ZeroOutPoint
3✔
1560
                        if _, ok := n.spendNotifications[spendRequest]; ok {
3✔
1561
                                notifyDetails(spendRequest, prevOut, uint32(i))
×
1562
                        }
×
1563
                }
1564
        }
1565

1566
        // We'll also check its outputs to determine if there are any
1567
        // outstanding confirmation requests.
1568
        if onConf != nil {
6✔
1569
                // notifyDetails is a helper closure that will construct the
3✔
1570
                // confirmation details of a request and hand them off to the
3✔
1571
                // onConf callback.
3✔
1572
                notifyDetails := func(confRequest ConfRequest) {
6✔
1573
                        Log.Debugf("Found initial confirmation of %v: "+
3✔
1574
                                "height=%d, hash=%v", confRequest,
3✔
1575
                                blockHeight, block.Hash())
3✔
1576

3✔
1577
                        details := &TxConfirmation{
3✔
1578
                                Tx:          tx.MsgTx(),
3✔
1579
                                BlockHash:   block.Hash(),
3✔
1580
                                BlockHeight: blockHeight,
3✔
1581
                                TxIndex:     uint32(tx.Index()),
3✔
1582
                                Block:       block.MsgBlock(),
3✔
1583
                        }
3✔
1584

3✔
1585
                        onConf(confRequest, details)
3✔
1586
                }
3✔
1587

1588
                for _, txOut := range tx.MsgTx().TxOut {
6✔
1589
                        // We'll parse the script of the output to determine if
3✔
1590
                        // we have any registered requests for it or the
3✔
1591
                        // transaction itself.
3✔
1592
                        pkScript, err := txscript.ParsePkScript(txOut.PkScript)
3✔
1593
                        if err != nil {
6✔
1594
                                continue
3✔
1595
                        }
1596
                        confRequest := ConfRequest{
3✔
1597
                                TxID:     *txHash,
3✔
1598
                                PkScript: pkScript,
3✔
1599
                        }
3✔
1600

3✔
1601
                        // If we have any, we'll record their confirmed height
3✔
1602
                        // so that notifications get dispatched when they
3✔
1603
                        // reaches the clients' desired number of confirmations.
3✔
1604
                        if _, ok := n.confNotifications[confRequest]; ok {
6✔
1605
                                notifyDetails(confRequest)
3✔
1606
                        }
3✔
1607
                        confRequest.TxID = ZeroHash
3✔
1608
                        if _, ok := n.confNotifications[confRequest]; ok {
3✔
1609
                                notifyDetails(confRequest)
×
1610
                        }
×
1611
                }
1612
        }
1613
}
1614

1615
// handleConfDetailsAtTip tracks the confirmation height of the txid/output
1616
// script in order to properly dispatch a confirmation notification after
1617
// meeting each request's desired number of confirmations for all current and
1618
// future registered clients.
1619
func (n *TxNotifier) handleConfDetailsAtTip(confRequest ConfRequest,
1620
        details *TxConfirmation) {
3✔
1621

3✔
1622
        // TODO(wilmer): cancel pending historical rescans if any?
3✔
1623
        confSet := n.confNotifications[confRequest]
3✔
1624

3✔
1625
        // If we already have details for this request, we don't want to add it
3✔
1626
        // again since we have already dispatched notifications for it.
3✔
1627
        if confSet.details != nil {
6✔
1628
                Log.Warnf("Ignoring address reuse for %s at height %d.",
3✔
1629
                        confRequest, details.BlockHeight)
3✔
1630
                return
3✔
1631
        }
3✔
1632

1633
        confSet.rescanStatus = rescanComplete
3✔
1634
        confSet.details = details
3✔
1635

3✔
1636
        for _, ntfn := range confSet.ntfns {
6✔
1637
                // In the event that this notification was aware that the
3✔
1638
                // transaction/output script was reorged out of the chain, we'll
3✔
1639
                // consume the reorg notification if it hasn't been done yet
3✔
1640
                // already.
3✔
1641
                select {
3✔
1642
                case <-ntfn.Event.NegativeConf:
3✔
1643
                default:
3✔
1644
                }
1645

1646
                // We'll note this client's required number of confirmations so
1647
                // that we can notify them when expected.
1648
                confHeight := details.BlockHeight + ntfn.NumConfirmations - 1
3✔
1649
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
3✔
1650
                if !exists {
6✔
1651
                        ntfnSet = make(map[*ConfNtfn]struct{})
3✔
1652
                        n.ntfnsByConfirmHeight[confHeight] = ntfnSet
3✔
1653
                }
3✔
1654
                ntfnSet[ntfn] = struct{}{}
3✔
1655
        }
1656

1657
        // We'll also note the initial confirmation height in order to correctly
1658
        // handle dispatching notifications when the transaction/output script
1659
        // gets reorged out of the chain.
1660
        txSet, exists := n.confsByInitialHeight[details.BlockHeight]
3✔
1661
        if !exists {
6✔
1662
                txSet = make(map[ConfRequest]struct{})
3✔
1663
                n.confsByInitialHeight[details.BlockHeight] = txSet
3✔
1664
        }
3✔
1665
        txSet[confRequest] = struct{}{}
3✔
1666
}
1667

1668
// handleSpendDetailsAtTip tracks the spend height of the outpoint/output script
1669
// in order to properly dispatch a spend notification for all current and future
1670
// registered clients.
1671
func (n *TxNotifier) handleSpendDetailsAtTip(spendRequest SpendRequest,
1672
        details *SpendDetail) {
3✔
1673

3✔
1674
        // TODO(wilmer): cancel pending historical rescans if any?
3✔
1675
        spendSet := n.spendNotifications[spendRequest]
3✔
1676
        spendSet.rescanStatus = rescanComplete
3✔
1677
        spendSet.details = details
3✔
1678

3✔
1679
        for _, ntfn := range spendSet.ntfns {
6✔
1680
                // In the event that this notification was aware that the
3✔
1681
                // spending transaction of its outpoint/output script was
3✔
1682
                // reorged out of the chain, we'll consume the reorg
3✔
1683
                // notification if it hasn't been done yet already.
3✔
1684
                select {
3✔
1685
                case <-ntfn.Event.Reorg:
×
1686
                default:
3✔
1687
                }
1688
        }
1689

1690
        // We'll note the spending height of the request in order to correctly
1691
        // handle dispatching notifications when the spending transactions gets
1692
        // reorged out of the chain.
1693
        spendHeight := uint32(details.SpendingHeight)
3✔
1694
        opSet, exists := n.spendsByHeight[spendHeight]
3✔
1695
        if !exists {
6✔
1696
                opSet = make(map[SpendRequest]struct{})
3✔
1697
                n.spendsByHeight[spendHeight] = opSet
3✔
1698
        }
3✔
1699
        opSet[spendRequest] = struct{}{}
3✔
1700

3✔
1701
        Log.Debugf("Spend request %v spent at tip=%d", spendRequest,
3✔
1702
                spendHeight)
3✔
1703
}
1704

1705
// NotifyHeight dispatches confirmation and spend notifications to the clients
1706
// who registered for a notification which has been fulfilled at the passed
1707
// height.
1708
func (n *TxNotifier) NotifyHeight(height uint32) error {
3✔
1709
        n.Lock()
3✔
1710
        defer n.Unlock()
3✔
1711

3✔
1712
        // First, we'll dispatch an update to all of the notification clients
3✔
1713
        // for our watched requests with the number of confirmations left at
3✔
1714
        // this new height.
3✔
1715
        for _, confRequests := range n.confsByInitialHeight {
6✔
1716
                for confRequest := range confRequests {
6✔
1717
                        confSet := n.confNotifications[confRequest]
3✔
1718
                        for _, ntfn := range confSet.ntfns {
6✔
1719
                                txConfHeight := confSet.details.BlockHeight +
3✔
1720
                                        ntfn.NumConfirmations - 1
3✔
1721
                                numConfsLeft := txConfHeight - height
3✔
1722

3✔
1723
                                // Since we don't clear notifications until
3✔
1724
                                // transactions/output scripts are no longer
3✔
1725
                                // under the risk of being reorganized out of
3✔
1726
                                // the chain, we'll skip sending updates for
3✔
1727
                                // those that have already been confirmed.
3✔
1728
                                if int32(numConfsLeft) < 0 {
6✔
1729
                                        continue
3✔
1730
                                }
1731

1732
                                select {
3✔
1733
                                case ntfn.Event.Updates <- numConfsLeft:
3✔
1734
                                case <-n.quit:
×
1735
                                        return ErrTxNotifierExiting
×
1736
                                }
1737
                        }
1738
                }
1739
        }
1740

1741
        // Then, we'll dispatch notifications for all the requests that have
1742
        // become confirmed at this new block height.
1743
        for ntfn := range n.ntfnsByConfirmHeight[height] {
6✔
1744
                confSet := n.confNotifications[ntfn.ConfRequest]
3✔
1745

3✔
1746
                Log.Debugf("Dispatching %v confirmation notification for %v",
3✔
1747
                        ntfn.NumConfirmations, ntfn.ConfRequest)
3✔
1748

3✔
1749
                // The default notification we assigned above includes the
3✔
1750
                // block along with the rest of the details. However not all
3✔
1751
                // clients want the block, so we make a copy here w/o the block
3✔
1752
                // if needed so we can give clients only what they ask for.
3✔
1753
                confDetails := *confSet.details
3✔
1754
                if !ntfn.includeBlock {
6✔
1755
                        confDetails.Block = nil
3✔
1756
                }
3✔
1757

1758
                select {
3✔
1759
                case ntfn.Event.Confirmed <- &confDetails:
3✔
1760
                        ntfn.dispatched = true
3✔
1761
                case <-n.quit:
×
1762
                        return ErrTxNotifierExiting
×
1763
                }
1764
        }
1765
        delete(n.ntfnsByConfirmHeight, height)
3✔
1766

3✔
1767
        // Finally, we'll dispatch spend notifications for all the requests that
3✔
1768
        // were spent at this new block height.
3✔
1769
        for spendRequest := range n.spendsByHeight[height] {
6✔
1770
                spendSet := n.spendNotifications[spendRequest]
3✔
1771
                for _, ntfn := range spendSet.ntfns {
6✔
1772
                        err := n.dispatchSpendDetails(ntfn, spendSet.details)
3✔
1773
                        if err != nil {
3✔
1774
                                return err
×
1775
                        }
×
1776
                }
1777
        }
1778

1779
        return nil
3✔
1780
}
1781

1782
// DisconnectTip handles the tip of the current chain being disconnected during
1783
// a chain reorganization. If any watched requests were included in this block,
1784
// internal structures are updated to ensure confirmation/spend notifications
1785
// are consumed (if not already), and reorg notifications are dispatched
1786
// instead. Confirmation/spend notifications will be dispatched again upon block
1787
// inclusion.
1788
func (n *TxNotifier) DisconnectTip(blockHeight uint32) error {
3✔
1789
        select {
3✔
1790
        case <-n.quit:
×
1791
                return ErrTxNotifierExiting
×
1792
        default:
3✔
1793
        }
1794

1795
        n.Lock()
3✔
1796
        defer n.Unlock()
3✔
1797

3✔
1798
        if blockHeight != n.currentHeight {
3✔
1799
                return fmt.Errorf("received blocks out of order: "+
×
1800
                        "current height=%d, disconnected height=%d",
×
1801
                        n.currentHeight, blockHeight)
×
1802
        }
×
1803
        n.currentHeight--
3✔
1804
        n.reorgDepth++
3✔
1805

3✔
1806
        // With the block disconnected, we'll update the confirm and spend hints
3✔
1807
        // for our notification requests to reflect the new height, except for
3✔
1808
        // those that have confirmed/spent at previous heights.
3✔
1809
        n.updateHints(blockHeight)
3✔
1810

3✔
1811
        // We'll go through all of our watched confirmation requests and attempt
3✔
1812
        // to drain their notification channels to ensure sending notifications
3✔
1813
        // to the clients is always non-blocking.
3✔
1814
        for initialHeight, txHashes := range n.confsByInitialHeight {
6✔
1815
                for txHash := range txHashes {
6✔
1816
                        // If the transaction/output script has been reorged out
3✔
1817
                        // of the chain, we'll make sure to remove the cached
3✔
1818
                        // confirmation details to prevent notifying clients
3✔
1819
                        // with old information.
3✔
1820
                        confSet := n.confNotifications[txHash]
3✔
1821
                        if initialHeight == blockHeight {
6✔
1822
                                confSet.details = nil
3✔
1823
                        }
3✔
1824

1825
                        for _, ntfn := range confSet.ntfns {
6✔
1826
                                // First, we'll attempt to drain an update
3✔
1827
                                // from each notification to ensure sends to the
3✔
1828
                                // Updates channel are always non-blocking.
3✔
1829
                                select {
3✔
1830
                                case <-ntfn.Event.Updates:
3✔
1831
                                case <-n.quit:
×
1832
                                        return ErrTxNotifierExiting
×
1833
                                default:
3✔
1834
                                }
1835

1836
                                // Then, we'll check if the current
1837
                                // transaction/output script was included in the
1838
                                // block currently being disconnected. If it
1839
                                // was, we'll need to dispatch a reorg
1840
                                // notification to the client.
1841
                                if initialHeight == blockHeight {
6✔
1842
                                        err := n.dispatchConfReorg(
3✔
1843
                                                ntfn, blockHeight,
3✔
1844
                                        )
3✔
1845
                                        if err != nil {
3✔
1846
                                                return err
×
1847
                                        }
×
1848
                                }
1849
                        }
1850
                }
1851
        }
1852

1853
        // We'll also go through our watched spend requests and attempt to drain
1854
        // their dispatched notifications to ensure dispatching notifications to
1855
        // clients later on is always non-blocking. We're only interested in
1856
        // requests whose spending transaction was included at the height being
1857
        // disconnected.
1858
        for op := range n.spendsByHeight[blockHeight] {
3✔
1859
                // Since the spending transaction is being reorged out of the
×
1860
                // chain, we'll need to clear out the spending details of the
×
1861
                // request.
×
1862
                spendSet := n.spendNotifications[op]
×
1863
                spendSet.details = nil
×
1864

×
1865
                // For all requests which have had a spend notification
×
1866
                // dispatched, we'll attempt to drain it and send a reorg
×
1867
                // notification instead.
×
1868
                for _, ntfn := range spendSet.ntfns {
×
1869
                        if err := n.dispatchSpendReorg(ntfn); err != nil {
×
1870
                                return err
×
1871
                        }
×
1872
                }
1873
        }
1874

1875
        // Finally, we can remove the requests that were confirmed and/or spent
1876
        // at the height being disconnected. We'll still continue to track them
1877
        // until they have been confirmed/spent and are no longer under the risk
1878
        // of being reorged out of the chain again.
1879
        delete(n.confsByInitialHeight, blockHeight)
3✔
1880
        delete(n.spendsByHeight, blockHeight)
3✔
1881

3✔
1882
        return nil
3✔
1883
}
1884

1885
// updateHints attempts to update the confirm and spend hints for all relevant
1886
// requests respectively. The height parameter is used to determine which
1887
// requests we should update based on whether a new block is being
1888
// connected/disconnected.
1889
//
1890
// NOTE: This must be called with the TxNotifier's lock held and after its
1891
// height has already been reflected by a block being connected/disconnected.
1892
func (n *TxNotifier) updateHints(height uint32) {
3✔
1893
        // TODO(wilmer): update under one database transaction.
3✔
1894
        //
3✔
1895
        // To update the height hint for all the required confirmation requests
3✔
1896
        // under one database transaction, we'll gather the set of unconfirmed
3✔
1897
        // requests along with the ones that confirmed at the height being
3✔
1898
        // connected/disconnected.
3✔
1899
        confRequests := n.unconfirmedRequests()
3✔
1900
        for confRequest := range n.confsByInitialHeight[height] {
6✔
1901
                confRequests = append(confRequests, confRequest)
3✔
1902
        }
3✔
1903
        err := n.confirmHintCache.CommitConfirmHint(
3✔
1904
                n.currentHeight, confRequests...,
3✔
1905
        )
3✔
1906
        if err != nil {
3✔
1907
                // The error is not fatal as this is an optimistic optimization,
×
1908
                // so we'll avoid returning an error.
×
1909
                Log.Debugf("Unable to update confirm hints to %d for "+
×
1910
                        "%v: %v", n.currentHeight, confRequests, err)
×
1911
        }
×
1912

1913
        // Similarly, to update the height hint for all the required spend
1914
        // requests under one database transaction, we'll gather the set of
1915
        // unspent requests along with the ones that were spent at the height
1916
        // being connected/disconnected.
1917
        spendRequests := n.unspentRequests()
3✔
1918
        for spendRequest := range n.spendsByHeight[height] {
6✔
1919
                spendRequests = append(spendRequests, spendRequest)
3✔
1920
        }
3✔
1921
        err = n.spendHintCache.CommitSpendHint(n.currentHeight, spendRequests...)
3✔
1922
        if err != nil {
3✔
1923
                // The error is not fatal as this is an optimistic optimization,
×
1924
                // so we'll avoid returning an error.
×
1925
                Log.Debugf("Unable to update spend hints to %d for "+
×
1926
                        "%v: %v", n.currentHeight, spendRequests, err)
×
1927
        }
×
1928
}
1929

1930
// unconfirmedRequests returns the set of confirmation requests that are
1931
// still seen as unconfirmed by the TxNotifier.
1932
//
1933
// NOTE: This method must be called with the TxNotifier's lock held.
1934
func (n *TxNotifier) unconfirmedRequests() []ConfRequest {
3✔
1935
        var unconfirmed []ConfRequest
3✔
1936
        for confRequest, confNtfnSet := range n.confNotifications {
6✔
1937
                // If the notification is already aware of its confirmation
3✔
1938
                // details, or it's in the process of learning them, we'll skip
3✔
1939
                // it as we can't yet determine if it's confirmed or not.
3✔
1940
                if confNtfnSet.rescanStatus != rescanComplete ||
3✔
1941
                        confNtfnSet.details != nil {
6✔
1942
                        continue
3✔
1943
                }
1944

1945
                unconfirmed = append(unconfirmed, confRequest)
3✔
1946
        }
1947

1948
        return unconfirmed
3✔
1949
}
1950

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

1966
                unspent = append(unspent, spendRequest)
3✔
1967
        }
1968

1969
        return unspent
3✔
1970
}
1971

1972
// dispatchConfReorg dispatches a reorg notification to the client if the
1973
// confirmation notification was already delivered.
1974
//
1975
// NOTE: This must be called with the TxNotifier's lock held.
1976
func (n *TxNotifier) dispatchConfReorg(ntfn *ConfNtfn,
1977
        heightDisconnected uint32) error {
3✔
1978

3✔
1979
        // If the request's confirmation notification has yet to be dispatched,
3✔
1980
        // we'll need to clear its entry within the ntfnsByConfirmHeight index
3✔
1981
        // to prevent from notifying the client once the notifier reaches the
3✔
1982
        // confirmation height.
3✔
1983
        if !ntfn.dispatched {
6✔
1984
                confHeight := heightDisconnected + ntfn.NumConfirmations - 1
3✔
1985
                ntfnSet, exists := n.ntfnsByConfirmHeight[confHeight]
3✔
1986
                if exists {
6✔
1987
                        delete(ntfnSet, ntfn)
3✔
1988
                }
3✔
1989
                return nil
3✔
1990
        }
1991

1992
        // Otherwise, the entry within the ntfnsByConfirmHeight has already been
1993
        // deleted, so we'll attempt to drain the confirmation notification to
1994
        // ensure sends to the Confirmed channel are always non-blocking.
1995
        select {
3✔
1996
        case <-ntfn.Event.Confirmed:
×
1997
        case <-n.quit:
×
1998
                return ErrTxNotifierExiting
×
1999
        default:
3✔
2000
        }
2001

2002
        ntfn.dispatched = false
3✔
2003

3✔
2004
        // Send a negative confirmation notification to the client indicating
3✔
2005
        // how many blocks have been disconnected successively.
3✔
2006
        select {
3✔
2007
        case ntfn.Event.NegativeConf <- int32(n.reorgDepth):
3✔
2008
        case <-n.quit:
×
2009
                return ErrTxNotifierExiting
×
2010
        }
2011

2012
        return nil
3✔
2013
}
2014

2015
// dispatchSpendReorg dispatches a reorg notification to the client if a spend
2016
// notiification was already delivered.
2017
//
2018
// NOTE: This must be called with the TxNotifier's lock held.
2019
func (n *TxNotifier) dispatchSpendReorg(ntfn *SpendNtfn) error {
×
2020
        if !ntfn.dispatched {
×
2021
                return nil
×
2022
        }
×
2023

2024
        // Attempt to drain the spend notification to ensure sends to the Spend
2025
        // channel are always non-blocking.
2026
        select {
×
2027
        case <-ntfn.Event.Spend:
×
2028
        default:
×
2029
        }
2030

2031
        // Send a reorg notification to the client in order for them to
2032
        // correctly handle reorgs.
2033
        select {
×
2034
        case ntfn.Event.Reorg <- struct{}{}:
×
2035
        case <-n.quit:
×
2036
                return ErrTxNotifierExiting
×
2037
        }
2038

2039
        ntfn.dispatched = false
×
2040

×
2041
        return nil
×
2042
}
2043

2044
// TearDown is to be called when the owner of the TxNotifier is exiting. This
2045
// closes the event channels of all registered notifications that have not been
2046
// dispatched yet.
2047
func (n *TxNotifier) TearDown() {
3✔
2048
        close(n.quit)
3✔
2049

3✔
2050
        n.Lock()
3✔
2051
        defer n.Unlock()
3✔
2052

3✔
2053
        for _, confSet := range n.confNotifications {
6✔
2054
                for confID, ntfn := range confSet.ntfns {
6✔
2055
                        close(ntfn.Event.Confirmed)
3✔
2056
                        close(ntfn.Event.Updates)
3✔
2057
                        close(ntfn.Event.NegativeConf)
3✔
2058
                        close(ntfn.Event.Done)
3✔
2059
                        delete(confSet.ntfns, confID)
3✔
2060
                }
3✔
2061
        }
2062

2063
        for _, spendSet := range n.spendNotifications {
6✔
2064
                for spendID, ntfn := range spendSet.ntfns {
6✔
2065
                        close(ntfn.Event.Spend)
3✔
2066
                        close(ntfn.Event.Reorg)
3✔
2067
                        close(ntfn.Event.Done)
3✔
2068
                        delete(spendSet.ntfns, spendID)
3✔
2069
                }
3✔
2070
        }
2071
}
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