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

lightningnetwork / lnd / 11124677510

01 Oct 2024 11:49AM UTC coverage: 58.814% (+0.08%) from 58.735%
11124677510

push

github

web-flow
Merge pull request #8911 from ellemouton/reduceMCRouteEncoding

routing+channeldb: use a more minimal encoding for MC routes

561 of 893 new or added lines in 12 files covered. (62.82%)

60 existing lines in 15 files now uncovered.

130302 of 221548 relevant lines covered (58.81%)

28707.83 hits per line

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

82.23
/contractcourt/breach_arbitrator.go
1
package contractcourt
2

3
import (
4
        "bytes"
5
        "encoding/binary"
6
        "errors"
7
        "fmt"
8
        "io"
9
        "sync"
10

11
        "github.com/btcsuite/btcd/blockchain"
12
        "github.com/btcsuite/btcd/btcutil"
13
        "github.com/btcsuite/btcd/chaincfg/chainhash"
14
        "github.com/btcsuite/btcd/txscript"
15
        "github.com/btcsuite/btcd/wire"
16
        "github.com/lightningnetwork/lnd/chainntnfs"
17
        "github.com/lightningnetwork/lnd/channeldb"
18
        "github.com/lightningnetwork/lnd/input"
19
        "github.com/lightningnetwork/lnd/kvdb"
20
        "github.com/lightningnetwork/lnd/labels"
21
        "github.com/lightningnetwork/lnd/lntypes"
22
        "github.com/lightningnetwork/lnd/lnutils"
23
        "github.com/lightningnetwork/lnd/lnwallet"
24
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
25
)
26

27
const (
28
        // justiceTxConfTarget is the number of blocks we'll use as a
29
        // confirmation target when creating the justice transaction. We'll
30
        // choose an aggressive target, since we want to be sure it confirms
31
        // quickly.
32
        justiceTxConfTarget = 2
33

34
        // blocksPassedSplitPublish is the number of blocks without
35
        // confirmation of the justice tx we'll wait before starting to publish
36
        // smaller variants of the justice tx. We do this to mitigate an attack
37
        // the channel peer can do by pinning the HTLC outputs of the
38
        // commitment with low-fee HTLC transactions.
39
        blocksPassedSplitPublish = 4
40
)
41

42
var (
43
        // retributionBucket stores retribution state on disk between detecting
44
        // a contract breach, broadcasting a justice transaction that sweeps the
45
        // channel, and finally witnessing the justice transaction confirm on
46
        // the blockchain. It is critical that such state is persisted on disk,
47
        // so that if our node restarts at any point during the retribution
48
        // procedure, we can recover and continue from the persisted state.
49
        retributionBucket = []byte("retribution")
50

51
        // taprootRetributionBucket stores the tarpoot specific retribution
52
        // information. This includes things like the control blocks for both
53
        // commitment outputs, and the taptweak needed to sweep each HTLC (one
54
        // for the first and one for the second level).
55
        taprootRetributionBucket = []byte("tap-retribution")
56

57
        // errBrarShuttingDown is an error returned if the BreachArbitrator has
58
        // been signalled to exit.
59
        errBrarShuttingDown = errors.New("BreachArbitrator shutting down")
60
)
61

62
// ContractBreachEvent is an event the BreachArbitrator will receive in case a
63
// contract breach is observed on-chain. It contains the necessary information
64
// to handle the breach, and a ProcessACK closure we will use to ACK the event
65
// when we have safely stored all the necessary information.
66
type ContractBreachEvent struct {
67
        // ChanPoint is the channel point of the breached channel.
68
        ChanPoint wire.OutPoint
69

70
        // ProcessACK is an closure that should be called with a nil error iff
71
        // the breach retribution info is safely stored in the retribution
72
        // store. In case storing the information to the store fails, a non-nil
73
        // error should be used. When this closure returns, it means that the
74
        // contract court has marked the channel pending close in the DB, and
75
        // it is safe for the BreachArbitrator to carry on its duty.
76
        ProcessACK func(error)
77

78
        // BreachRetribution is the information needed to act on this contract
79
        // breach.
80
        BreachRetribution *lnwallet.BreachRetribution
81
}
82

83
// ChannelCloseType is an enum which signals the type of channel closure the
84
// peer should execute.
85
type ChannelCloseType uint8
86

87
const (
88
        // CloseRegular indicates a regular cooperative channel closure
89
        // should be attempted.
90
        CloseRegular ChannelCloseType = iota
91

92
        // CloseBreach indicates that a channel breach has been detected, and
93
        // the link should immediately be marked as unavailable.
94
        CloseBreach
95
)
96

97
// RetributionStorer provides an interface for managing a persistent map from
98
// wire.OutPoint -> retributionInfo. Upon learning of a breach, a
99
// BreachArbitrator should record the retributionInfo for the breached channel,
100
// which serves a checkpoint in the event that retribution needs to be resumed
101
// after failure. A RetributionStore provides an interface for managing the
102
// persisted set, as well as mapping user defined functions over the entire
103
// on-disk contents.
104
//
105
// Calls to RetributionStore may occur concurrently. A concrete instance of
106
// RetributionStore should use appropriate synchronization primitives, or
107
// be otherwise safe for concurrent access.
108
type RetributionStorer interface {
109
        // Add persists the retributionInfo to disk, using the information's
110
        // chanPoint as the key. This method should overwrite any existing
111
        // entries found under the same key, and an error should be raised if
112
        // the addition fails.
113
        Add(retInfo *retributionInfo) error
114

115
        // IsBreached queries the retribution store to see if the breach arbiter
116
        // is aware of any breaches for the provided channel point.
117
        IsBreached(chanPoint *wire.OutPoint) (bool, error)
118

119
        // Remove deletes the retributionInfo from disk, if any exists, under
120
        // the given key. An error should be re raised if the removal fails.
121
        Remove(key *wire.OutPoint) error
122

123
        // ForAll iterates over the existing on-disk contents and applies a
124
        // chosen, read-only callback to each. This method should ensure that it
125
        // immediately propagate any errors generated by the callback.
126
        ForAll(cb func(*retributionInfo) error, reset func()) error
127
}
128

129
// BreachConfig bundles the required subsystems used by the breach arbiter. An
130
// instance of BreachConfig is passed to NewBreachArbitrator during
131
// instantiation.
132
type BreachConfig struct {
133
        // CloseLink allows the breach arbiter to shutdown any channel links for
134
        // which it detects a breach, ensuring now further activity will
135
        // continue across the link. The method accepts link's channel point and
136
        // a close type to be included in the channel close summary.
137
        CloseLink func(*wire.OutPoint, ChannelCloseType)
138

139
        // DB provides access to the user's channels, allowing the breach
140
        // arbiter to determine the current state of a user's channels, and how
141
        // it should respond to channel closure.
142
        DB *channeldb.ChannelStateDB
143

144
        // Estimator is used by the breach arbiter to determine an appropriate
145
        // fee level when generating, signing, and broadcasting sweep
146
        // transactions.
147
        Estimator chainfee.Estimator
148

149
        // GenSweepScript generates the receiving scripts for swept outputs.
150
        GenSweepScript func() ([]byte, error)
151

152
        // Notifier provides a publish/subscribe interface for event driven
153
        // notifications regarding the confirmation of txids.
154
        Notifier chainntnfs.ChainNotifier
155

156
        // PublishTransaction facilitates the process of broadcasting a
157
        // transaction to the network.
158
        PublishTransaction func(*wire.MsgTx, string) error
159

160
        // ContractBreaches is a channel where the BreachArbitrator will receive
161
        // notifications in the event of a contract breach being observed. A
162
        // ContractBreachEvent must be ACKed by the BreachArbitrator, such that
163
        // the sending subsystem knows that the event is properly handed off.
164
        ContractBreaches <-chan *ContractBreachEvent
165

166
        // Signer is used by the breach arbiter to generate sweep transactions,
167
        // which move coins from previously open channels back to the user's
168
        // wallet.
169
        Signer input.Signer
170

171
        // Store is a persistent resource that maintains information regarding
172
        // breached channels. This is used in conjunction with DB to recover
173
        // from crashes, restarts, or other failures.
174
        Store RetributionStorer
175
}
176

177
// BreachArbitrator is a special subsystem which is responsible for watching and
178
// acting on the detection of any attempted uncooperative channel breaches by
179
// channel counterparties. This file essentially acts as deterrence code for
180
// those attempting to launch attacks against the daemon. In practice it's
181
// expected that the logic in this file never gets executed, but it is
182
// important to have it in place just in case we encounter cheating channel
183
// counterparties.
184
// TODO(roasbeef): closures in config for subsystem pointers to decouple?
185
type BreachArbitrator struct {
186
        started sync.Once
187
        stopped sync.Once
188

189
        cfg *BreachConfig
190

191
        subscriptions map[wire.OutPoint]chan struct{}
192

193
        quit chan struct{}
194
        wg   sync.WaitGroup
195
        sync.Mutex
196
}
197

198
// NewBreachArbitrator creates a new instance of a BreachArbitrator initialized
199
// with its dependent objects.
200
func NewBreachArbitrator(cfg *BreachConfig) *BreachArbitrator {
12✔
201
        return &BreachArbitrator{
12✔
202
                cfg:           cfg,
12✔
203
                subscriptions: make(map[wire.OutPoint]chan struct{}),
12✔
204
                quit:          make(chan struct{}),
12✔
205
        }
12✔
206
}
12✔
207

208
// Start is an idempotent method that officially starts the BreachArbitrator
209
// along with all other goroutines it needs to perform its functions.
210
func (b *BreachArbitrator) Start() error {
12✔
211
        var err error
12✔
212
        b.started.Do(func() {
24✔
213
                brarLog.Info("Breach arbiter starting")
12✔
214
                err = b.start()
12✔
215
        })
12✔
216
        return err
12✔
217
}
218

219
func (b *BreachArbitrator) start() error {
12✔
220
        // Load all retributions currently persisted in the retribution store.
12✔
221
        var breachRetInfos map[wire.OutPoint]retributionInfo
12✔
222
        if err := b.cfg.Store.ForAll(func(ret *retributionInfo) error {
16✔
223
                breachRetInfos[ret.chanPoint] = *ret
4✔
224
                return nil
4✔
225
        }, func() {
16✔
226
                breachRetInfos = make(map[wire.OutPoint]retributionInfo)
12✔
227
        }); err != nil {
12✔
228
                brarLog.Errorf("Unable to create retribution info: %v", err)
×
229
                return err
×
230
        }
×
231

232
        // Load all currently closed channels from disk, we will use the
233
        // channels that have been marked fully closed to filter the retribution
234
        // information loaded from disk. This is necessary in the event that the
235
        // channel was marked fully closed, but was not removed from the
236
        // retribution store.
237
        closedChans, err := b.cfg.DB.FetchClosedChannels(false)
12✔
238
        if err != nil {
12✔
239
                brarLog.Errorf("Unable to fetch closing channels: %v", err)
×
240
                return err
×
241
        }
×
242

243
        brarLog.Debugf("Found %v closing channels, %v retribution records",
12✔
244
                len(closedChans), len(breachRetInfos))
12✔
245

12✔
246
        // Using the set of non-pending, closed channels, reconcile any
12✔
247
        // discrepancies between the channeldb and the retribution store by
12✔
248
        // removing any retribution information for which we have already
12✔
249
        // finished our responsibilities. If the removal is successful, we also
12✔
250
        // remove the entry from our in-memory map, to avoid any further action
12✔
251
        // for this channel.
12✔
252
        // TODO(halseth): no need continue on IsPending once closed channels
12✔
253
        // actually means close transaction is confirmed.
12✔
254
        for _, chanSummary := range closedChans {
16✔
255
                brarLog.Debugf("Working on close channel: %v, is_pending: %v",
4✔
256
                        chanSummary.ChanPoint, chanSummary.IsPending)
4✔
257

4✔
258
                if chanSummary.IsPending {
8✔
259
                        continue
4✔
260
                }
261

262
                chanPoint := &chanSummary.ChanPoint
4✔
263
                if _, ok := breachRetInfos[*chanPoint]; ok {
4✔
264
                        if err := b.cfg.Store.Remove(chanPoint); err != nil {
×
265
                                brarLog.Errorf("Unable to remove closed "+
×
266
                                        "chanid=%v from breach arbiter: %v",
×
267
                                        chanPoint, err)
×
268
                                return err
×
269
                        }
×
270
                        delete(breachRetInfos, *chanPoint)
×
271

×
272
                        brarLog.Debugf("Skipped closed channel: %v",
×
273
                                chanSummary.ChanPoint)
×
274
                }
275
        }
276

277
        // Spawn the exactRetribution tasks to monitor and resolve any breaches
278
        // that were loaded from the retribution store.
279
        for chanPoint := range breachRetInfos {
16✔
280
                retInfo := breachRetInfos[chanPoint]
4✔
281

4✔
282
                brarLog.Debugf("Handling breach handoff on startup "+
4✔
283
                        "for ChannelPoint(%v)", chanPoint)
4✔
284

4✔
285
                // Register for a notification when the breach transaction is
4✔
286
                // confirmed on chain.
4✔
287
                breachTXID := retInfo.commitHash
4✔
288
                breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
4✔
289
                confChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
4✔
290
                        &breachTXID, breachScript, 1, retInfo.breachHeight,
4✔
291
                )
4✔
292
                if err != nil {
4✔
293
                        brarLog.Errorf("Unable to register for conf updates "+
×
294
                                "for txid: %v, err: %v", breachTXID, err)
×
295
                        return err
×
296
                }
×
297

298
                // Launch a new goroutine which to finalize the channel
299
                // retribution after the breach transaction confirms.
300
                b.wg.Add(1)
4✔
301
                go b.exactRetribution(confChan, &retInfo)
4✔
302
        }
303

304
        // Start watching the remaining active channels!
305
        b.wg.Add(1)
12✔
306
        go b.contractObserver()
12✔
307

12✔
308
        return nil
12✔
309
}
310

311
// Stop is an idempotent method that signals the BreachArbitrator to execute a
312
// graceful shutdown. This function will block until all goroutines spawned by
313
// the BreachArbitrator have gracefully exited.
314
func (b *BreachArbitrator) Stop() error {
12✔
315
        b.stopped.Do(func() {
24✔
316
                brarLog.Infof("Breach arbiter shutting down...")
12✔
317
                defer brarLog.Debug("Breach arbiter shutdown complete")
12✔
318

12✔
319
                close(b.quit)
12✔
320
                b.wg.Wait()
12✔
321
        })
12✔
322
        return nil
12✔
323
}
324

325
// IsBreached queries the breach arbiter's retribution store to see if it is
326
// aware of any channel breaches for a particular channel point.
327
func (b *BreachArbitrator) IsBreached(chanPoint *wire.OutPoint) (bool, error) {
12✔
328
        return b.cfg.Store.IsBreached(chanPoint)
12✔
329
}
12✔
330

331
// SubscribeBreachComplete is used by outside subsystems to be notified of a
332
// successful breach resolution.
333
func (b *BreachArbitrator) SubscribeBreachComplete(chanPoint *wire.OutPoint,
334
        c chan struct{}) (bool, error) {
4✔
335

4✔
336
        breached, err := b.cfg.Store.IsBreached(chanPoint)
4✔
337
        if err != nil {
4✔
338
                // If an error occurs, no subscription will be registered.
×
339
                return false, err
×
340
        }
×
341

342
        if !breached {
4✔
UNCOV
343
                // If chanPoint no longer exists in the Store, then the breach
×
UNCOV
344
                // was cleaned up successfully. Any subscription that occurs
×
UNCOV
345
                // happens after the breach information was persisted to the
×
UNCOV
346
                // underlying store.
×
UNCOV
347
                return true, nil
×
UNCOV
348
        }
×
349

350
        // Otherwise since the channel point is not resolved, add a
351
        // subscription. There can only be one subscription per channel point.
352
        b.Lock()
4✔
353
        defer b.Unlock()
4✔
354
        b.subscriptions[*chanPoint] = c
4✔
355

4✔
356
        return false, nil
4✔
357
}
358

359
// notifyBreachComplete is used by the BreachArbitrator to notify outside
360
// subsystems that the breach resolution process is complete.
361
func (b *BreachArbitrator) notifyBreachComplete(chanPoint *wire.OutPoint) {
8✔
362
        b.Lock()
8✔
363
        defer b.Unlock()
8✔
364
        if c, ok := b.subscriptions[*chanPoint]; ok {
12✔
365
                close(c)
4✔
366
        }
4✔
367

368
        // Remove the subscription.
369
        delete(b.subscriptions, *chanPoint)
8✔
370
}
371

372
// contractObserver is the primary goroutine for the BreachArbitrator. This
373
// goroutine is responsible for handling breach events coming from the
374
// contractcourt on the ContractBreaches channel. If a channel breach is
375
// detected, then the contractObserver will execute the retribution logic
376
// required to sweep ALL outputs from a contested channel into the daemon's
377
// wallet.
378
//
379
// NOTE: This MUST be run as a goroutine.
380
func (b *BreachArbitrator) contractObserver() {
12✔
381
        defer b.wg.Done()
12✔
382

12✔
383
        brarLog.Infof("Starting contract observer, watching for breaches.")
12✔
384

12✔
385
        for {
32✔
386
                select {
20✔
387
                case breachEvent := <-b.cfg.ContractBreaches:
12✔
388
                        // We have been notified about a contract breach!
12✔
389
                        // Handle the handoff, making sure we ACK the event
12✔
390
                        // after we have safely added it to the retribution
12✔
391
                        // store.
12✔
392
                        b.wg.Add(1)
12✔
393
                        go b.handleBreachHandoff(breachEvent)
12✔
394

395
                case <-b.quit:
12✔
396
                        return
12✔
397
                }
398
        }
399
}
400

401
// spend is used to wrap the index of the retributionInfo output that gets
402
// spent together with the spend details.
403
type spend struct {
404
        index  int
405
        detail *chainntnfs.SpendDetail
406
}
407

408
// waitForSpendEvent waits for any of the breached outputs to get spent, and
409
// returns the spend details for those outputs. The spendNtfns map is a cache
410
// used to store registered spend subscriptions, in case we must call this
411
// method multiple times.
412
func (b *BreachArbitrator) waitForSpendEvent(breachInfo *retributionInfo,
413
        spendNtfns map[wire.OutPoint]*chainntnfs.SpendEvent) ([]spend, error) {
17✔
414

17✔
415
        inputs := breachInfo.breachedOutputs
17✔
416

17✔
417
        // We create a channel the first goroutine that gets a spend event can
17✔
418
        // signal. We make it buffered in case multiple spend events come in at
17✔
419
        // the same time.
17✔
420
        anySpend := make(chan struct{}, len(inputs))
17✔
421

17✔
422
        // The allSpends channel will be used to pass spend events from all the
17✔
423
        // goroutines that detects a spend before they are signalled to exit.
17✔
424
        allSpends := make(chan spend, len(inputs))
17✔
425

17✔
426
        // exit will be used to signal the goroutines that they can exit.
17✔
427
        exit := make(chan struct{})
17✔
428
        var wg sync.WaitGroup
17✔
429

17✔
430
        // We'll now launch a goroutine for each of the HTLC outputs, that will
17✔
431
        // signal the moment they detect a spend event.
17✔
432
        for i := range inputs {
48✔
433
                breachedOutput := &inputs[i]
31✔
434

31✔
435
                brarLog.Infof("Checking spend from %v(%v) for ChannelPoint(%v)",
31✔
436
                        breachedOutput.witnessType, breachedOutput.outpoint,
31✔
437
                        breachInfo.chanPoint)
31✔
438

31✔
439
                // If we have already registered for a notification for this
31✔
440
                // output, we'll reuse it.
31✔
441
                spendNtfn, ok := spendNtfns[breachedOutput.outpoint]
31✔
442
                if !ok {
49✔
443
                        var err error
18✔
444
                        spendNtfn, err = b.cfg.Notifier.RegisterSpendNtfn(
18✔
445
                                &breachedOutput.outpoint,
18✔
446
                                breachedOutput.signDesc.Output.PkScript,
18✔
447
                                breachInfo.breachHeight,
18✔
448
                        )
18✔
449
                        if err != nil {
18✔
450
                                brarLog.Errorf("Unable to check for spentness "+
×
451
                                        "of outpoint=%v: %v",
×
452
                                        breachedOutput.outpoint, err)
×
453

×
454
                                // Registration may have failed if we've been
×
455
                                // instructed to shutdown. If so, return here
×
456
                                // to avoid entering an infinite loop.
×
457
                                select {
×
458
                                case <-b.quit:
×
459
                                        return nil, errBrarShuttingDown
×
460
                                default:
×
461
                                        continue
×
462
                                }
463
                        }
464
                        spendNtfns[breachedOutput.outpoint] = spendNtfn
18✔
465
                }
466

467
                // Launch a goroutine waiting for a spend event.
468
                b.wg.Add(1)
31✔
469
                wg.Add(1)
31✔
470
                go func(index int, spendEv *chainntnfs.SpendEvent) {
62✔
471
                        defer b.wg.Done()
31✔
472
                        defer wg.Done()
31✔
473

31✔
474
                        select {
31✔
475
                        // The output has been taken to the second level!
476
                        case sp, ok := <-spendEv.Spend:
18✔
477
                                if !ok {
18✔
478
                                        return
×
479
                                }
×
480

481
                                brarLog.Infof("Detected spend on %s(%v) by "+
18✔
482
                                        "txid(%v) for ChannelPoint(%v)",
18✔
483
                                        inputs[index].witnessType,
18✔
484
                                        inputs[index].outpoint,
18✔
485
                                        sp.SpenderTxHash,
18✔
486
                                        breachInfo.chanPoint)
18✔
487

18✔
488
                                // First we send the spend event on the
18✔
489
                                // allSpends channel, such that it can be
18✔
490
                                // handled after all go routines have exited.
18✔
491
                                allSpends <- spend{index, sp}
18✔
492

18✔
493
                                // Finally we'll signal the anySpend channel
18✔
494
                                // that a spend was detected, such that the
18✔
495
                                // other goroutines can be shut down.
18✔
496
                                anySpend <- struct{}{}
18✔
497
                        case <-exit:
17✔
498
                                return
17✔
499
                        case <-b.quit:
4✔
500
                                return
4✔
501
                        }
502
                }(i, spendNtfn)
503
        }
504

505
        // We'll wait for any of the outputs to be spent, or that we are
506
        // signalled to exit.
507
        select {
17✔
508
        // A goroutine have signalled that a spend occurred.
509
        case <-anySpend:
17✔
510
                // Signal for the remaining goroutines to exit.
17✔
511
                close(exit)
17✔
512
                wg.Wait()
17✔
513

17✔
514
                // At this point all goroutines that can send on the allSpends
17✔
515
                // channel have exited. We can therefore safely close the
17✔
516
                // channel before ranging over its content.
17✔
517
                close(allSpends)
17✔
518

17✔
519
                // Gather all detected spends and return them.
17✔
520
                var spends []spend
17✔
521
                for s := range allSpends {
35✔
522
                        breachedOutput := &inputs[s.index]
18✔
523
                        delete(spendNtfns, breachedOutput.outpoint)
18✔
524

18✔
525
                        spends = append(spends, s)
18✔
526
                }
18✔
527

528
                return spends, nil
17✔
529

530
        case <-b.quit:
4✔
531
                return nil, errBrarShuttingDown
4✔
532
        }
533
}
534

535
// convertToSecondLevelRevoke takes a breached output, and a transaction that
536
// spends it to the second level, and mutates the breach output into one that
537
// is able to properly sweep that second level output. We'll use this function
538
// when we go to sweep a breached commitment transaction, but the cheating
539
// party has already attempted to take it to the second level.
540
func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo,
541
        spendDetails *chainntnfs.SpendDetail) {
2✔
542

2✔
543
        // In this case, we'll modify the witness type of this output to
2✔
544
        // actually prepare for a second level revoke.
2✔
545
        isTaproot := txscript.IsPayToTaproot(bo.signDesc.Output.PkScript)
2✔
546
        if isTaproot {
2✔
547
                bo.witnessType = input.TaprootHtlcSecondLevelRevoke
×
548
        } else {
2✔
549
                bo.witnessType = input.HtlcSecondLevelRevoke
2✔
550
        }
2✔
551

552
        // We'll also redirect the outpoint to this second level output, so the
553
        // spending transaction updates it inputs accordingly.
554
        spendingTx := spendDetails.SpendingTx
2✔
555
        spendInputIndex := spendDetails.SpenderInputIndex
2✔
556
        oldOp := bo.outpoint
2✔
557
        bo.outpoint = wire.OutPoint{
2✔
558
                Hash:  spendingTx.TxHash(),
2✔
559
                Index: spendInputIndex,
2✔
560
        }
2✔
561

2✔
562
        // Next, we need to update the amount so we can do fee estimation
2✔
563
        // properly, and also so we can generate a valid signature as we need
2✔
564
        // to know the new input value (the second level transactions shaves
2✔
565
        // off some funds to fees).
2✔
566
        newAmt := spendingTx.TxOut[spendInputIndex].Value
2✔
567
        bo.amt = btcutil.Amount(newAmt)
2✔
568
        bo.signDesc.Output.Value = newAmt
2✔
569
        bo.signDesc.Output.PkScript = spendingTx.TxOut[spendInputIndex].PkScript
2✔
570

2✔
571
        // For taproot outputs, the taptweak also needs to be swapped out. We
2✔
572
        // do this unconditionally as this field isn't used at all for segwit
2✔
573
        // v0 outputs.
2✔
574
        bo.signDesc.TapTweak = bo.secondLevelTapTweak[:]
2✔
575

2✔
576
        // Finally, we'll need to adjust the witness program in the
2✔
577
        // SignDescriptor.
2✔
578
        bo.signDesc.WitnessScript = bo.secondLevelWitnessScript
2✔
579

2✔
580
        brarLog.Warnf("HTLC(%v) for ChannelPoint(%v) has been spent to the "+
2✔
581
                "second-level, adjusting -> %v", oldOp, breachInfo.chanPoint,
2✔
582
                bo.outpoint)
2✔
583
}
584

585
// updateBreachInfo mutates the passed breachInfo by removing or converting any
586
// outputs among the spends. It also counts the total and revoked funds swept
587
// by our justice spends.
588
func updateBreachInfo(breachInfo *retributionInfo, spends []spend) (
589
        btcutil.Amount, btcutil.Amount) {
17✔
590

17✔
591
        inputs := breachInfo.breachedOutputs
17✔
592
        doneOutputs := make(map[int]struct{})
17✔
593

17✔
594
        var totalFunds, revokedFunds btcutil.Amount
17✔
595
        for _, s := range spends {
35✔
596
                breachedOutput := &inputs[s.index]
18✔
597
                txIn := s.detail.SpendingTx.TxIn[s.detail.SpenderInputIndex]
18✔
598

18✔
599
                switch breachedOutput.witnessType {
18✔
600
                case input.TaprootHtlcAcceptedRevoke:
4✔
601
                        fallthrough
4✔
602
                case input.TaprootHtlcOfferedRevoke:
4✔
603
                        fallthrough
4✔
604
                case input.HtlcAcceptedRevoke:
4✔
605
                        fallthrough
4✔
606
                case input.HtlcOfferedRevoke:
8✔
607
                        // If the HTLC output was spent using the revocation
8✔
608
                        // key, it is our own spend, and we can forget the
8✔
609
                        // output. Otherwise it has been taken to the second
8✔
610
                        // level.
8✔
611
                        signDesc := &breachedOutput.signDesc
8✔
612
                        ok, err := input.IsHtlcSpendRevoke(txIn, signDesc)
8✔
613
                        if err != nil {
8✔
614
                                brarLog.Errorf("Unable to determine if "+
×
615
                                        "revoke spend: %v", err)
×
616
                                break
×
617
                        }
618

619
                        if ok {
14✔
620
                                brarLog.Debugf("HTLC spend was our own " +
6✔
621
                                        "revocation spend")
6✔
622
                                break
6✔
623
                        }
624

625
                        brarLog.Infof("Spend on second-level "+
2✔
626
                                "%s(%v) for ChannelPoint(%v) "+
2✔
627
                                "transitions to second-level output",
2✔
628
                                breachedOutput.witnessType,
2✔
629
                                breachedOutput.outpoint, breachInfo.chanPoint)
2✔
630

2✔
631
                        // In this case we'll morph our initial revoke
2✔
632
                        // spend to instead point to the second level
2✔
633
                        // output, and update the sign descriptor in the
2✔
634
                        // process.
2✔
635
                        convertToSecondLevelRevoke(
2✔
636
                                breachedOutput, breachInfo, s.detail,
2✔
637
                        )
2✔
638

2✔
639
                        continue
2✔
640
                }
641

642
                // Now that we have determined the spend is done by us, we
643
                // count the total and revoked funds swept depending on the
644
                // input type.
645
                switch breachedOutput.witnessType {
16✔
646
                // If the output being revoked is the remote commitment output
647
                // or an offered HTLC output, its amount contributes to the
648
                // value of funds being revoked from the counter party.
649
                case input.CommitmentRevoke, input.TaprootCommitmentRevoke,
650
                        input.HtlcSecondLevelRevoke,
651
                        input.TaprootHtlcSecondLevelRevoke,
652
                        input.TaprootHtlcOfferedRevoke, input.HtlcOfferedRevoke:
12✔
653

12✔
654
                        revokedFunds += breachedOutput.Amount()
12✔
655
                }
656

657
                totalFunds += breachedOutput.Amount()
16✔
658
                brarLog.Infof("Spend on %s(%v) for ChannelPoint(%v) "+
16✔
659
                        "transitions output to terminal state, "+
16✔
660
                        "removing input from justice transaction",
16✔
661
                        breachedOutput.witnessType,
16✔
662
                        breachedOutput.outpoint, breachInfo.chanPoint)
16✔
663

16✔
664
                doneOutputs[s.index] = struct{}{}
16✔
665
        }
666

667
        // Filter the inputs for which we can no longer proceed.
668
        var nextIndex int
17✔
669
        for i := range inputs {
48✔
670
                if _, ok := doneOutputs[i]; ok {
47✔
671
                        continue
16✔
672
                }
673

674
                inputs[nextIndex] = inputs[i]
19✔
675
                nextIndex++
19✔
676
        }
677

678
        // Update our remaining set of outputs before continuing with
679
        // another attempt at publication.
680
        breachInfo.breachedOutputs = inputs[:nextIndex]
17✔
681
        return totalFunds, revokedFunds
17✔
682
}
683

684
// exactRetribution is a goroutine which is executed once a contract breach has
685
// been detected by a breachObserver. This function is responsible for
686
// punishing a counterparty for violating the channel contract by sweeping ALL
687
// the lingering funds within the channel into the daemon's wallet.
688
//
689
// NOTE: This MUST be run as a goroutine.
690
//
691
//nolint:funlen
692
func (b *BreachArbitrator) exactRetribution(
693
        confChan *chainntnfs.ConfirmationEvent, breachInfo *retributionInfo) {
10✔
694

10✔
695
        defer b.wg.Done()
10✔
696

10✔
697
        // TODO(roasbeef): state needs to be checkpointed here
10✔
698
        select {
10✔
699
        case _, ok := <-confChan.Confirmed:
8✔
700
                // If the second value is !ok, then the channel has been closed
8✔
701
                // signifying a daemon shutdown, so we exit.
8✔
702
                if !ok {
8✔
703
                        return
×
704
                }
×
705

706
                // Otherwise, if this is a real confirmation notification, then
707
                // we fall through to complete our duty.
708
        case <-b.quit:
2✔
709
                return
2✔
710
        }
711

712
        brarLog.Debugf("Breach transaction %v has been confirmed, sweeping "+
8✔
713
                "revoked funds", breachInfo.commitHash)
8✔
714

8✔
715
        // We may have to wait for some of the HTLC outputs to be spent to the
8✔
716
        // second level before broadcasting the justice tx. We'll store the
8✔
717
        // SpendEvents between each attempt to not re-register unnecessarily.
8✔
718
        spendNtfns := make(map[wire.OutPoint]*chainntnfs.SpendEvent)
8✔
719

8✔
720
        // Compute both the total value of funds being swept and the
8✔
721
        // amount of funds that were revoked from the counter party.
8✔
722
        var totalFunds, revokedFunds btcutil.Amount
8✔
723

8✔
724
justiceTxBroadcast:
8✔
725
        // With the breach transaction confirmed, we now create the
726
        // justice tx which will claim ALL the funds within the
727
        // channel.
728
        justiceTxs, err := b.createJusticeTx(breachInfo.breachedOutputs)
17✔
729
        if err != nil {
17✔
730
                brarLog.Errorf("Unable to create justice tx: %v", err)
×
731
                return
×
732
        }
×
733
        finalTx := justiceTxs.spendAll
17✔
734

17✔
735
        brarLog.Debugf("Broadcasting justice tx: %v", lnutils.SpewLogClosure(
17✔
736
                finalTx))
17✔
737

17✔
738
        // We'll now attempt to broadcast the transaction which finalized the
17✔
739
        // channel's retribution against the cheating counter party.
17✔
740
        label := labels.MakeLabel(labels.LabelTypeJusticeTransaction, nil)
17✔
741
        err = b.cfg.PublishTransaction(finalTx, label)
17✔
742
        if err != nil {
31✔
743
                brarLog.Errorf("Unable to broadcast justice tx: %v", err)
14✔
744
        }
14✔
745

746
        // Regardless of publication succeeded or not, we now wait for any of
747
        // the inputs to be spent. If any input got spent by the remote, we
748
        // must recreate our justice transaction.
749
        var (
17✔
750
                spendChan = make(chan []spend, 1)
17✔
751
                errChan   = make(chan error, 1)
17✔
752
                wg        sync.WaitGroup
17✔
753
        )
17✔
754

17✔
755
        wg.Add(1)
17✔
756
        go func() {
34✔
757
                defer wg.Done()
17✔
758

17✔
759
                spends, err := b.waitForSpendEvent(breachInfo, spendNtfns)
17✔
760
                if err != nil {
21✔
761
                        errChan <- err
4✔
762
                        return
4✔
763
                }
4✔
764
                spendChan <- spends
17✔
765
        }()
766

767
        // We'll also register for block notifications, such that in case our
768
        // justice tx doesn't confirm within a reasonable timeframe, we can
769
        // start to more aggressively sweep the time sensitive outputs.
770
        newBlockChan, err := b.cfg.Notifier.RegisterBlockEpochNtfn(nil)
17✔
771
        if err != nil {
17✔
772
                brarLog.Errorf("Unable to register for block notifications: %v",
×
773
                        err)
×
774
                return
×
775
        }
×
776
        defer newBlockChan.Cancel()
17✔
777

17✔
778
Loop:
17✔
779
        for {
39✔
780
                select {
22✔
781
                case spends := <-spendChan:
17✔
782
                        // Update the breach info with the new spends.
17✔
783
                        t, r := updateBreachInfo(breachInfo, spends)
17✔
784
                        totalFunds += t
17✔
785
                        revokedFunds += r
17✔
786

17✔
787
                        brarLog.Infof("%v spends from breach tx for "+
17✔
788
                                "ChannelPoint(%v) has been detected, %v "+
17✔
789
                                "revoked funds (%v total) have been claimed",
17✔
790
                                len(spends), breachInfo.chanPoint,
17✔
791
                                revokedFunds, totalFunds)
17✔
792

17✔
793
                        if len(breachInfo.breachedOutputs) == 0 {
25✔
794
                                brarLog.Infof("Justice for ChannelPoint(%v) "+
8✔
795
                                        "has been served, %v revoked funds "+
8✔
796
                                        "(%v total) have been claimed. No "+
8✔
797
                                        "more outputs to sweep, marking fully "+
8✔
798
                                        "resolved", breachInfo.chanPoint,
8✔
799
                                        revokedFunds, totalFunds)
8✔
800

8✔
801
                                err = b.cleanupBreach(&breachInfo.chanPoint)
8✔
802
                                if err != nil {
8✔
803
                                        brarLog.Errorf("Failed to cleanup "+
×
804
                                                "breached ChannelPoint(%v): %v",
×
805
                                                breachInfo.chanPoint, err)
×
806
                                }
×
807

808
                                // TODO(roasbeef): add peer to blacklist?
809

810
                                // TODO(roasbeef): close other active channels
811
                                // with offending peer
812
                                break Loop
8✔
813
                        }
814

815
                        brarLog.Infof("Attempting another justice tx "+
13✔
816
                                "with %d inputs",
13✔
817
                                len(breachInfo.breachedOutputs))
13✔
818

13✔
819
                        wg.Wait()
13✔
820
                        goto justiceTxBroadcast
13✔
821

822
                // On every new block, we check whether we should republish the
823
                // transactions.
824
                case epoch, ok := <-newBlockChan.Epochs:
9✔
825
                        if !ok {
9✔
826
                                return
×
827
                        }
×
828

829
                        // If less than four blocks have passed since the
830
                        // breach confirmed, we'll continue waiting. It was
831
                        // published with a 2-block fee estimate, so it's not
832
                        // unexpected that four blocks without confirmation can
833
                        // pass.
834
                        splitHeight := breachInfo.breachHeight +
9✔
835
                                blocksPassedSplitPublish
9✔
836
                        if uint32(epoch.Height) < splitHeight {
17✔
837
                                continue Loop
8✔
838
                        }
839

840
                        brarLog.Warnf("Block height %v arrived without "+
1✔
841
                                "justice tx confirming (breached at "+
1✔
842
                                "height %v), splitting justice tx.",
1✔
843
                                epoch.Height, breachInfo.breachHeight)
1✔
844

1✔
845
                        // Otherwise we'll attempt to publish the two separate
1✔
846
                        // justice transactions that sweeps the commitment
1✔
847
                        // outputs and the HTLC outputs separately. This is to
1✔
848
                        // mitigate the case where our "spend all" justice TX
1✔
849
                        // doesn't propagate because the HTLC outputs have been
1✔
850
                        // pinned by low fee HTLC txs.
1✔
851
                        label := labels.MakeLabel(
1✔
852
                                labels.LabelTypeJusticeTransaction, nil,
1✔
853
                        )
1✔
854
                        if justiceTxs.spendCommitOuts != nil {
2✔
855
                                tx := justiceTxs.spendCommitOuts
1✔
856

1✔
857
                                brarLog.Debugf("Broadcasting justice tx "+
1✔
858
                                        "spending commitment outs: %v",
1✔
859
                                        lnutils.SpewLogClosure(tx))
1✔
860

1✔
861
                                err = b.cfg.PublishTransaction(tx, label)
1✔
862
                                if err != nil {
1✔
863
                                        brarLog.Warnf("Unable to broadcast "+
×
864
                                                "commit out spending justice "+
×
865
                                                "tx: %v", err)
×
866
                                }
×
867
                        }
868

869
                        if justiceTxs.spendHTLCs != nil {
2✔
870
                                tx := justiceTxs.spendHTLCs
1✔
871

1✔
872
                                brarLog.Debugf("Broadcasting justice tx "+
1✔
873
                                        "spending HTLC outs: %v",
1✔
874
                                        lnutils.SpewLogClosure(tx))
1✔
875

1✔
876
                                err = b.cfg.PublishTransaction(tx, label)
1✔
877
                                if err != nil {
1✔
878
                                        brarLog.Warnf("Unable to broadcast "+
×
879
                                                "HTLC out spending justice "+
×
880
                                                "tx: %v", err)
×
881
                                }
×
882
                        }
883

884
                        for _, tx := range justiceTxs.spendSecondLevelHTLCs {
1✔
885
                                tx := tx
×
886

×
887
                                brarLog.Debugf("Broadcasting justice tx "+
×
888
                                        "spending second-level HTLC output: %v",
×
889
                                        lnutils.SpewLogClosure(tx))
×
890

×
891
                                err = b.cfg.PublishTransaction(tx, label)
×
892
                                if err != nil {
×
893
                                        brarLog.Warnf("Unable to broadcast "+
×
894
                                                "second-level HTLC out "+
×
895
                                                "spending justice tx: %v", err)
×
896
                                }
×
897
                        }
898

899
                case err := <-errChan:
×
900
                        if err != errBrarShuttingDown {
×
901
                                brarLog.Errorf("error waiting for "+
×
902
                                        "spend event: %v", err)
×
903
                        }
×
904
                        break Loop
×
905

906
                case <-b.quit:
4✔
907
                        break Loop
4✔
908
                }
909
        }
910

911
        // Wait for our go routine to exit.
912
        wg.Wait()
8✔
913
}
914

915
// cleanupBreach marks the given channel point as fully resolved and removes the
916
// retribution for that the channel from the retribution store.
917
func (b *BreachArbitrator) cleanupBreach(chanPoint *wire.OutPoint) error {
8✔
918
        // With the channel closed, mark it in the database as such.
8✔
919
        err := b.cfg.DB.MarkChanFullyClosed(chanPoint)
8✔
920
        if err != nil {
8✔
921
                return fmt.Errorf("unable to mark chan as closed: %w", err)
×
922
        }
×
923

924
        // Justice has been carried out; we can safely delete the retribution
925
        // info from the database.
926
        err = b.cfg.Store.Remove(chanPoint)
8✔
927
        if err != nil {
8✔
928
                return fmt.Errorf("unable to remove retribution from db: %w",
×
929
                        err)
×
930
        }
×
931

932
        // This is after the Remove call so that the chan passed in via
933
        // SubscribeBreachComplete is always notified, no matter when it is
934
        // called. Otherwise, if notifyBreachComplete was before Remove, a
935
        // very rare edge case could occur in which SubscribeBreachComplete
936
        // is called after notifyBreachComplete and before Remove, meaning the
937
        // caller would never be notified.
938
        b.notifyBreachComplete(chanPoint)
8✔
939

8✔
940
        return nil
8✔
941
}
942

943
// handleBreachHandoff handles a new breach event, by writing it to disk, then
944
// notifies the BreachArbitrator contract observer goroutine that a channel's
945
// contract has been breached by the prior counterparty. Once notified the
946
// BreachArbitrator will attempt to sweep ALL funds within the channel using the
947
// information provided within the BreachRetribution generated due to the
948
// breach of channel contract. The funds will be swept only after the breaching
949
// transaction receives a necessary number of confirmations.
950
//
951
// NOTE: This MUST be run as a goroutine.
952
func (b *BreachArbitrator) handleBreachHandoff(
953
        breachEvent *ContractBreachEvent) {
12✔
954

12✔
955
        defer b.wg.Done()
12✔
956

12✔
957
        chanPoint := breachEvent.ChanPoint
12✔
958
        brarLog.Debugf("Handling breach handoff for ChannelPoint(%v)",
12✔
959
                chanPoint)
12✔
960

12✔
961
        // A read from this channel indicates that a channel breach has been
12✔
962
        // detected! So we notify the main coordination goroutine with the
12✔
963
        // information needed to bring the counterparty to justice.
12✔
964
        breachInfo := breachEvent.BreachRetribution
12✔
965
        brarLog.Warnf("REVOKED STATE #%v FOR ChannelPoint(%v) "+
12✔
966
                "broadcast, REMOTE PEER IS DOING SOMETHING "+
12✔
967
                "SKETCHY!!!", breachInfo.RevokedStateNum,
12✔
968
                chanPoint)
12✔
969

12✔
970
        // Immediately notify the HTLC switch that this link has been
12✔
971
        // breached in order to ensure any incoming or outgoing
12✔
972
        // multi-hop HTLCs aren't sent over this link, nor any other
12✔
973
        // links associated with this peer.
12✔
974
        b.cfg.CloseLink(&chanPoint, CloseBreach)
12✔
975

12✔
976
        // TODO(roasbeef): need to handle case of remote broadcast
12✔
977
        // mid-local initiated state-transition, possible
12✔
978
        // false-positive?
12✔
979

12✔
980
        // Acquire the mutex to ensure consistency between the call to
12✔
981
        // IsBreached and Add below.
12✔
982
        b.Lock()
12✔
983

12✔
984
        // We first check if this breach info is already added to the
12✔
985
        // retribution store.
12✔
986
        breached, err := b.cfg.Store.IsBreached(&chanPoint)
12✔
987
        if err != nil {
12✔
988
                b.Unlock()
×
989
                brarLog.Errorf("Unable to check breach info in DB: %v", err)
×
990

×
991
                // Notify about the failed lookup and return.
×
992
                breachEvent.ProcessACK(err)
×
993
                return
×
994
        }
×
995

996
        // If this channel is already marked as breached in the retribution
997
        // store, we already have handled the handoff for this breach. In this
998
        // case we can safely ACK the handoff, and return.
999
        if breached {
13✔
1000
                b.Unlock()
1✔
1001
                breachEvent.ProcessACK(nil)
1✔
1002
                return
1✔
1003
        }
1✔
1004

1005
        // Using the breach information provided by the wallet and the
1006
        // channel snapshot, construct the retribution information that
1007
        // will be persisted to disk.
1008
        retInfo := newRetributionInfo(&chanPoint, breachInfo)
11✔
1009

11✔
1010
        // Persist the pending retribution state to disk.
11✔
1011
        err = b.cfg.Store.Add(retInfo)
11✔
1012
        b.Unlock()
11✔
1013
        if err != nil {
12✔
1014
                brarLog.Errorf("Unable to persist retribution "+
1✔
1015
                        "info to db: %v", err)
1✔
1016
        }
1✔
1017

1018
        // Now that the breach has been persisted, try to send an
1019
        // acknowledgment back to the close observer with the error. If
1020
        // the ack is successful, the close observer will mark the
1021
        // channel as pending-closed in the channeldb.
1022
        breachEvent.ProcessACK(err)
11✔
1023

11✔
1024
        // Bail if we failed to persist retribution info.
11✔
1025
        if err != nil {
12✔
1026
                return
1✔
1027
        }
1✔
1028

1029
        // Now that a new channel contract has been added to the retribution
1030
        // store, we first register for a notification to be dispatched once
1031
        // the breach transaction (the revoked commitment transaction) has been
1032
        // confirmed in the chain to ensure we're not dealing with a moving
1033
        // target.
1034
        breachTXID := &retInfo.commitHash
10✔
1035
        breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
10✔
1036
        cfChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
10✔
1037
                breachTXID, breachScript, 1, retInfo.breachHeight,
10✔
1038
        )
10✔
1039
        if err != nil {
10✔
1040
                brarLog.Errorf("Unable to register for conf updates for "+
×
1041
                        "txid: %v, err: %v", breachTXID, err)
×
1042
                return
×
1043
        }
×
1044

1045
        brarLog.Warnf("A channel has been breached with txid: %v. Waiting "+
10✔
1046
                "for confirmation, then justice will be served!", breachTXID)
10✔
1047

10✔
1048
        // With the retribution state persisted, channel close persisted, and
10✔
1049
        // notification registered, we launch a new goroutine which will
10✔
1050
        // finalize the channel retribution after the breach transaction has
10✔
1051
        // been confirmed.
10✔
1052
        b.wg.Add(1)
10✔
1053
        go b.exactRetribution(cfChan, retInfo)
10✔
1054
}
1055

1056
// breachedOutput contains all the information needed to sweep a breached
1057
// output. A breached output is an output that we are now entitled to due to a
1058
// revoked commitment transaction being broadcast.
1059
type breachedOutput struct {
1060
        amt         btcutil.Amount
1061
        outpoint    wire.OutPoint
1062
        witnessType input.StandardWitnessType
1063
        signDesc    input.SignDescriptor
1064
        confHeight  uint32
1065

1066
        secondLevelWitnessScript []byte
1067
        secondLevelTapTweak      [32]byte
1068

1069
        witnessFunc input.WitnessGenerator
1070
}
1071

1072
// makeBreachedOutput assembles a new breachedOutput that can be used by the
1073
// breach arbiter to construct a justice or sweep transaction.
1074
func makeBreachedOutput(outpoint *wire.OutPoint,
1075
        witnessType input.StandardWitnessType,
1076
        secondLevelScript []byte,
1077
        signDescriptor *input.SignDescriptor,
1078
        confHeight uint32) breachedOutput {
53✔
1079

53✔
1080
        amount := signDescriptor.Output.Value
53✔
1081

53✔
1082
        return breachedOutput{
53✔
1083
                amt:                      btcutil.Amount(amount),
53✔
1084
                outpoint:                 *outpoint,
53✔
1085
                secondLevelWitnessScript: secondLevelScript,
53✔
1086
                witnessType:              witnessType,
53✔
1087
                signDesc:                 *signDescriptor,
53✔
1088
                confHeight:               confHeight,
53✔
1089
        }
53✔
1090
}
53✔
1091

1092
// Amount returns the number of satoshis contained in the breached output.
1093
func (bo *breachedOutput) Amount() btcutil.Amount {
176✔
1094
        return bo.amt
176✔
1095
}
176✔
1096

1097
// OutPoint returns the breached output's identifier that is to be included as a
1098
// transaction input.
1099
func (bo *breachedOutput) OutPoint() wire.OutPoint {
402✔
1100
        return bo.outpoint
402✔
1101
}
402✔
1102

1103
// RequiredTxOut returns a non-nil TxOut if input commits to a certain
1104
// transaction output. This is used in the SINGLE|ANYONECANPAY case to make
1105
// sure any presigned input is still valid by including the output.
1106
func (bo *breachedOutput) RequiredTxOut() *wire.TxOut {
4✔
1107
        return nil
4✔
1108
}
4✔
1109

1110
// RequiredLockTime returns whether this input commits to a tx locktime that
1111
// must be used in the transaction including it.
1112
func (bo *breachedOutput) RequiredLockTime() (uint32, bool) {
×
1113
        return 0, false
×
1114
}
×
1115

1116
// WitnessType returns the type of witness that must be generated to spend the
1117
// breached output.
1118
func (bo *breachedOutput) WitnessType() input.WitnessType {
130✔
1119
        return bo.witnessType
130✔
1120
}
130✔
1121

1122
// SignDesc returns the breached output's SignDescriptor, which is used during
1123
// signing to compute the witness.
1124
func (bo *breachedOutput) SignDesc() *input.SignDescriptor {
365✔
1125
        return &bo.signDesc
365✔
1126
}
365✔
1127

1128
// CraftInputScript computes a valid witness that allows us to spend from the
1129
// breached output. It does so by first generating and memoizing the witness
1130
// generation function, which parameterized primarily by the witness type and
1131
// sign descriptor. The method then returns the witness computed by invoking
1132
// this function on the first and subsequent calls.
1133
func (bo *breachedOutput) CraftInputScript(signer input.Signer, txn *wire.MsgTx,
1134
        hashCache *txscript.TxSigHashes,
1135
        prevOutputFetcher txscript.PrevOutputFetcher,
1136
        txinIdx int) (*input.Script, error) {
75✔
1137

75✔
1138
        // First, we ensure that the witness generation function has been
75✔
1139
        // initialized for this breached output.
75✔
1140
        signDesc := bo.SignDesc()
75✔
1141
        signDesc.PrevOutputFetcher = prevOutputFetcher
75✔
1142
        bo.witnessFunc = bo.witnessType.WitnessGenerator(signer, signDesc)
75✔
1143

75✔
1144
        // Now that we have ensured that the witness generation function has
75✔
1145
        // been initialized, we can proceed to execute it and generate the
75✔
1146
        // witness for this particular breached output.
75✔
1147
        return bo.witnessFunc(txn, hashCache, txinIdx)
75✔
1148
}
75✔
1149

1150
// BlocksToMaturity returns the relative timelock, as a number of blocks, that
1151
// must be built on top of the confirmation height before the output can be
1152
// spent.
1153
func (bo *breachedOutput) BlocksToMaturity() uint32 {
72✔
1154
        // If the output is a to_remote output we can claim, and it's of the
72✔
1155
        // confirmed type (or is a taproot channel that always has the CSV 1),
72✔
1156
        // we must wait one block before claiming it.
72✔
1157
        switch bo.witnessType {
72✔
1158
        case input.CommitmentToRemoteConfirmed, input.TaprootRemoteCommitSpend:
6✔
1159
                return 1
6✔
1160
        }
1161

1162
        // All other breached outputs have no CSV delay.
1163
        return 0
70✔
1164
}
1165

1166
// HeightHint returns the minimum height at which a confirmed spending tx can
1167
// occur.
1168
func (bo *breachedOutput) HeightHint() uint32 {
4✔
1169
        return bo.confHeight
4✔
1170
}
4✔
1171

1172
// UnconfParent returns information about a possibly unconfirmed parent tx.
1173
func (bo *breachedOutput) UnconfParent() *input.TxInfo {
4✔
1174
        return nil
4✔
1175
}
4✔
1176

1177
// Add compile-time constraint ensuring breachedOutput implements the Input
1178
// interface.
1179
var _ input.Input = (*breachedOutput)(nil)
1180

1181
// retributionInfo encapsulates all the data needed to sweep all the contested
1182
// funds within a channel whose contract has been breached by the prior
1183
// counterparty. This struct is used to create the justice transaction which
1184
// spends all outputs of the commitment transaction into an output controlled
1185
// by the wallet.
1186
type retributionInfo struct {
1187
        commitHash   chainhash.Hash
1188
        chanPoint    wire.OutPoint
1189
        chainHash    chainhash.Hash
1190
        breachHeight uint32
1191

1192
        breachedOutputs []breachedOutput
1193
}
1194

1195
// newRetributionInfo constructs a retributionInfo containing all the
1196
// information required by the breach arbiter to recover funds from breached
1197
// channels.  The information is primarily populated using the BreachRetribution
1198
// delivered by the wallet when it detects a channel breach.
1199
func newRetributionInfo(chanPoint *wire.OutPoint,
1200
        breachInfo *lnwallet.BreachRetribution) *retributionInfo {
14✔
1201

14✔
1202
        // Determine the number of second layer HTLCs we will attempt to sweep.
14✔
1203
        nHtlcs := len(breachInfo.HtlcRetributions)
14✔
1204

14✔
1205
        // Initialize a slice to hold the outputs we will attempt to sweep. The
14✔
1206
        // maximum capacity of the slice is set to 2+nHtlcs to handle the case
14✔
1207
        // where the local, remote, and all HTLCs are not dust outputs.  All
14✔
1208
        // HTLC outputs provided by the wallet are guaranteed to be non-dust,
14✔
1209
        // though the commitment outputs are conditionally added depending on
14✔
1210
        // the nil-ness of their sign descriptors.
14✔
1211
        breachedOutputs := make([]breachedOutput, 0, nHtlcs+2)
14✔
1212

14✔
1213
        isTaproot := func() bool {
28✔
1214
                if breachInfo.LocalOutputSignDesc != nil {
28✔
1215
                        return txscript.IsPayToTaproot(
14✔
1216
                                breachInfo.LocalOutputSignDesc.Output.PkScript,
14✔
1217
                        )
14✔
1218
                }
14✔
1219

1220
                return txscript.IsPayToTaproot(
×
1221
                        breachInfo.RemoteOutputSignDesc.Output.PkScript,
×
1222
                )
×
1223
        }()
1224

1225
        // First, record the breach information for the local channel point if
1226
        // it is not considered dust, which is signaled by a non-nil sign
1227
        // descriptor. Here we use CommitmentNoDelay (or
1228
        // CommitmentNoDelayTweakless for newer commitments) since this output
1229
        // belongs to us and has no time-based constraints on spending. For
1230
        // taproot channels, this is a normal spend from our output on the
1231
        // commitment of the remote party.
1232
        if breachInfo.LocalOutputSignDesc != nil {
28✔
1233
                var witnessType input.StandardWitnessType
14✔
1234
                switch {
14✔
1235
                case isTaproot:
4✔
1236
                        witnessType = input.TaprootRemoteCommitSpend
4✔
1237

1238
                case !isTaproot &&
1239
                        breachInfo.LocalOutputSignDesc.SingleTweak == nil:
14✔
1240

14✔
1241
                        witnessType = input.CommitSpendNoDelayTweakless
14✔
1242

1243
                case !isTaproot:
4✔
1244
                        witnessType = input.CommitmentNoDelay
4✔
1245
                }
1246

1247
                // If the local delay is non-zero, it means this output is of
1248
                // the confirmed to_remote type.
1249
                if !isTaproot && breachInfo.LocalDelay != 0 {
18✔
1250
                        witnessType = input.CommitmentToRemoteConfirmed
4✔
1251
                }
4✔
1252

1253
                localOutput := makeBreachedOutput(
14✔
1254
                        &breachInfo.LocalOutpoint,
14✔
1255
                        witnessType,
14✔
1256
                        // No second level script as this is a commitment
14✔
1257
                        // output.
14✔
1258
                        nil,
14✔
1259
                        breachInfo.LocalOutputSignDesc,
14✔
1260
                        breachInfo.BreachHeight,
14✔
1261
                )
14✔
1262

14✔
1263
                breachedOutputs = append(breachedOutputs, localOutput)
14✔
1264
        }
1265

1266
        // Second, record the same information regarding the remote outpoint,
1267
        // again if it is not dust, which belongs to the party who tried to
1268
        // steal our money! Here we set witnessType of the breachedOutput to
1269
        // CommitmentRevoke, since we will be using a revoke key, withdrawing
1270
        // the funds from the commitment transaction immediately.
1271
        if breachInfo.RemoteOutputSignDesc != nil {
25✔
1272
                var witType input.StandardWitnessType
11✔
1273
                if isTaproot {
15✔
1274
                        witType = input.TaprootCommitmentRevoke
4✔
1275
                } else {
15✔
1276
                        witType = input.CommitmentRevoke
11✔
1277
                }
11✔
1278

1279
                remoteOutput := makeBreachedOutput(
11✔
1280
                        &breachInfo.RemoteOutpoint,
11✔
1281
                        witType,
11✔
1282
                        // No second level script as this is a commitment
11✔
1283
                        // output.
11✔
1284
                        nil,
11✔
1285
                        breachInfo.RemoteOutputSignDesc,
11✔
1286
                        breachInfo.BreachHeight,
11✔
1287
                )
11✔
1288

11✔
1289
                breachedOutputs = append(breachedOutputs, remoteOutput)
11✔
1290
        }
1291

1292
        // Lastly, for each of the breached HTLC outputs, record each as a
1293
        // breached output with the appropriate witness type based on its
1294
        // directionality. All HTLC outputs provided by the wallet are assumed
1295
        // to be non-dust.
1296
        for i, breachedHtlc := range breachInfo.HtlcRetributions {
25✔
1297
                // Using the breachedHtlc's incoming flag, determine the
11✔
1298
                // appropriate witness type that needs to be generated in order
11✔
1299
                // to sweep the HTLC output.
11✔
1300
                var htlcWitnessType input.StandardWitnessType
11✔
1301
                switch {
11✔
1302
                case isTaproot && breachedHtlc.IsIncoming:
4✔
1303
                        htlcWitnessType = input.TaprootHtlcAcceptedRevoke
4✔
1304

1305
                case isTaproot && !breachedHtlc.IsIncoming:
4✔
1306
                        htlcWitnessType = input.TaprootHtlcOfferedRevoke
4✔
1307

1308
                case !isTaproot && breachedHtlc.IsIncoming:
×
1309
                        htlcWitnessType = input.HtlcAcceptedRevoke
×
1310

1311
                case !isTaproot && !breachedHtlc.IsIncoming:
7✔
1312
                        htlcWitnessType = input.HtlcOfferedRevoke
7✔
1313
                }
1314

1315
                htlcOutput := makeBreachedOutput(
11✔
1316
                        &breachInfo.HtlcRetributions[i].OutPoint,
11✔
1317
                        htlcWitnessType,
11✔
1318
                        breachInfo.HtlcRetributions[i].SecondLevelWitnessScript,
11✔
1319
                        &breachInfo.HtlcRetributions[i].SignDesc,
11✔
1320
                        breachInfo.BreachHeight,
11✔
1321
                )
11✔
1322

11✔
1323
                // For taproot outputs, we also need to hold onto the second
11✔
1324
                // level tap tweak as well.
11✔
1325
                //nolint:lll
11✔
1326
                htlcOutput.secondLevelTapTweak = breachedHtlc.SecondLevelTapTweak
11✔
1327

11✔
1328
                breachedOutputs = append(breachedOutputs, htlcOutput)
11✔
1329
        }
1330

1331
        return &retributionInfo{
14✔
1332
                commitHash:      breachInfo.BreachTxHash,
14✔
1333
                chainHash:       breachInfo.ChainHash,
14✔
1334
                chanPoint:       *chanPoint,
14✔
1335
                breachedOutputs: breachedOutputs,
14✔
1336
                breachHeight:    breachInfo.BreachHeight,
14✔
1337
        }
14✔
1338
}
1339

1340
// justiceTxVariants is a struct that holds transactions which exacts "justice"
1341
// by sweeping ALL the funds within the channel which we are now entitled to
1342
// due to a breach of the channel's contract by the counterparty. There are
1343
// four variants of justice transactions:
1344
//
1345
// 1. The "normal" justice tx that spends all breached outputs.
1346
// 2. A tx that spends only the breached to_local output and to_remote output
1347
// (can be nil if none of these exist).
1348
// 3. A tx that spends all the breached commitment level HTLC outputs (can be
1349
// nil if none of these exist or if all have been taken to the second level).
1350
// 4. A set of txs that spend all the second-level HTLC outputs (can be empty if
1351
// no HTLC second-level txs have been confirmed).
1352
//
1353
// The reason we create these three variants, is that in certain cases (like
1354
// with the anchor output HTLC malleability), the channel counter party can pin
1355
// the HTLC outputs with low fee children, hindering our normal justice tx that
1356
// attempts to spend these outputs from propagating. In this case we want to
1357
// spend the to_local output and commitment level HTLC outputs separately,
1358
// before the CSV locks expire.
1359
type justiceTxVariants struct {
1360
        spendAll              *wire.MsgTx
1361
        spendCommitOuts       *wire.MsgTx
1362
        spendHTLCs            *wire.MsgTx
1363
        spendSecondLevelHTLCs []*wire.MsgTx
1364
}
1365

1366
// createJusticeTx creates transactions which exacts "justice" by sweeping ALL
1367
// the funds within the channel which we are now entitled to due to a breach of
1368
// the channel's contract by the counterparty. This function returns a *fully*
1369
// signed transaction with the witness for each input fully in place.
1370
func (b *BreachArbitrator) createJusticeTx(
1371
        breachedOutputs []breachedOutput) (*justiceTxVariants, error) {
18✔
1372

18✔
1373
        var (
18✔
1374
                allInputs         []input.Input
18✔
1375
                commitInputs      []input.Input
18✔
1376
                htlcInputs        []input.Input
18✔
1377
                secondLevelInputs []input.Input
18✔
1378
        )
18✔
1379

18✔
1380
        for i := range breachedOutputs {
56✔
1381
                // Grab locally scoped reference to breached output.
38✔
1382
                inp := &breachedOutputs[i]
38✔
1383
                allInputs = append(allInputs, inp)
38✔
1384

38✔
1385
                // Check if the input is from a commitment output, a commitment
38✔
1386
                // level HTLC output or a second level HTLC output.
38✔
1387
                switch inp.WitnessType() {
38✔
1388
                case input.HtlcAcceptedRevoke, input.HtlcOfferedRevoke,
1389
                        input.TaprootHtlcAcceptedRevoke,
1390
                        input.TaprootHtlcOfferedRevoke:
12✔
1391

12✔
1392
                        htlcInputs = append(htlcInputs, inp)
12✔
1393

1394
                case input.HtlcSecondLevelRevoke,
1395
                        input.TaprootHtlcSecondLevelRevoke:
4✔
1396

4✔
1397
                        secondLevelInputs = append(secondLevelInputs, inp)
4✔
1398

1399
                default:
26✔
1400
                        commitInputs = append(commitInputs, inp)
26✔
1401
                }
1402
        }
1403

1404
        var (
18✔
1405
                txs = &justiceTxVariants{}
18✔
1406
                err error
18✔
1407
        )
18✔
1408

18✔
1409
        // For each group of inputs, create a tx that spends them.
18✔
1410
        txs.spendAll, err = b.createSweepTx(allInputs...)
18✔
1411
        if err != nil {
18✔
1412
                return nil, err
×
1413
        }
×
1414

1415
        txs.spendCommitOuts, err = b.createSweepTx(commitInputs...)
18✔
1416
        if err != nil {
18✔
1417
                brarLog.Errorf("could not create sweep tx for commitment "+
×
1418
                        "outputs: %v", err)
×
1419
        }
×
1420

1421
        txs.spendHTLCs, err = b.createSweepTx(htlcInputs...)
18✔
1422
        if err != nil {
18✔
1423
                brarLog.Errorf("could not create sweep tx for HTLC outputs: %v",
×
1424
                        err)
×
1425
        }
×
1426

1427
        secondLevelSweeps := make([]*wire.MsgTx, 0, len(secondLevelInputs))
18✔
1428
        for _, input := range secondLevelInputs {
22✔
1429
                sweepTx, err := b.createSweepTx(input)
4✔
1430
                if err != nil {
4✔
1431
                        brarLog.Errorf("could not create sweep tx for "+
×
1432
                                "second-level HTLC output: %v", err)
×
1433

×
1434
                        continue
×
1435
                }
1436

1437
                secondLevelSweeps = append(secondLevelSweeps, sweepTx)
4✔
1438
        }
1439
        txs.spendSecondLevelHTLCs = secondLevelSweeps
18✔
1440

18✔
1441
        return txs, nil
18✔
1442
}
1443

1444
// createSweepTx creates a tx that sweeps the passed inputs back to our wallet.
1445
func (b *BreachArbitrator) createSweepTx(inputs ...input.Input) (*wire.MsgTx,
1446
        error) {
50✔
1447

50✔
1448
        if len(inputs) == 0 {
63✔
1449
                return nil, nil
13✔
1450
        }
13✔
1451

1452
        // We will assemble the breached outputs into a slice of spendable
1453
        // outputs, while simultaneously computing the estimated weight of the
1454
        // transaction.
1455
        var (
41✔
1456
                spendableOutputs []input.Input
41✔
1457
                weightEstimate   input.TxWeightEstimator
41✔
1458
        )
41✔
1459

41✔
1460
        // Allocate enough space to potentially hold each of the breached
41✔
1461
        // outputs in the retribution info.
41✔
1462
        spendableOutputs = make([]input.Input, 0, len(inputs))
41✔
1463

41✔
1464
        // The justice transaction we construct will be a segwit transaction
41✔
1465
        // that pays to a p2tr output. Components such as the version,
41✔
1466
        // nLockTime, and output are already included in the TxWeightEstimator.
41✔
1467
        weightEstimate.AddP2TROutput()
41✔
1468

41✔
1469
        // Next, we iterate over the breached outputs contained in the
41✔
1470
        // retribution info.  For each, we switch over the witness type such
41✔
1471
        // that we contribute the appropriate weight for each input and
41✔
1472
        // witness, finally adding to our list of spendable outputs.
41✔
1473
        for i := range inputs {
113✔
1474
                // Grab locally scoped reference to breached output.
72✔
1475
                inp := inputs[i]
72✔
1476

72✔
1477
                // First, determine the appropriate estimated witness weight
72✔
1478
                // for the give witness type of this breached output. If the
72✔
1479
                // witness weight cannot be estimated, we will omit it from the
72✔
1480
                // transaction.
72✔
1481
                witnessWeight, _, err := inp.WitnessType().SizeUpperBound()
72✔
1482
                if err != nil {
72✔
1483
                        brarLog.Warnf("could not determine witness weight "+
×
1484
                                "for breached output in retribution info: %v",
×
1485
                                err)
×
1486
                        continue
×
1487
                }
1488
                weightEstimate.AddWitnessInput(witnessWeight)
72✔
1489

72✔
1490
                // Finally, append this input to our list of spendable outputs.
72✔
1491
                spendableOutputs = append(spendableOutputs, inp)
72✔
1492
        }
1493

1494
        txWeight := weightEstimate.Weight()
41✔
1495

41✔
1496
        return b.sweepSpendableOutputsTxn(txWeight, spendableOutputs...)
41✔
1497
}
1498

1499
// sweepSpendableOutputsTxn creates a signed transaction from a sequence of
1500
// spendable outputs by sweeping the funds into a single p2wkh output.
1501
func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit,
1502
        inputs ...input.Input) (*wire.MsgTx, error) {
41✔
1503

41✔
1504
        // First, we obtain a new public key script from the wallet which we'll
41✔
1505
        // sweep the funds to.
41✔
1506
        // TODO(roasbeef): possibly create many outputs to minimize change in
41✔
1507
        // the future?
41✔
1508
        pkScript, err := b.cfg.GenSweepScript()
41✔
1509
        if err != nil {
41✔
1510
                return nil, err
×
1511
        }
×
1512

1513
        // Compute the total amount contained in the inputs.
1514
        var totalAmt btcutil.Amount
41✔
1515
        for _, inp := range inputs {
113✔
1516
                totalAmt += btcutil.Amount(inp.SignDesc().Output.Value)
72✔
1517
        }
72✔
1518

1519
        // We'll actually attempt to target inclusion within the next two
1520
        // blocks as we'd like to sweep these funds back into our wallet ASAP.
1521
        feePerKw, err := b.cfg.Estimator.EstimateFeePerKW(justiceTxConfTarget)
41✔
1522
        if err != nil {
41✔
1523
                return nil, err
×
1524
        }
×
1525
        txFee := feePerKw.FeeForWeight(txWeight)
41✔
1526

41✔
1527
        // TODO(roasbeef): already start to siphon their funds into fees
41✔
1528
        sweepAmt := int64(totalAmt - txFee)
41✔
1529

41✔
1530
        // With the fee calculated, we can now create the transaction using the
41✔
1531
        // information gathered above and the provided retribution information.
41✔
1532
        txn := wire.NewMsgTx(2)
41✔
1533

41✔
1534
        // We begin by adding the output to which our funds will be deposited.
41✔
1535
        txn.AddTxOut(&wire.TxOut{
41✔
1536
                PkScript: pkScript,
41✔
1537
                Value:    sweepAmt,
41✔
1538
        })
41✔
1539

41✔
1540
        // Next, we add all of the spendable outputs as inputs to the
41✔
1541
        // transaction.
41✔
1542
        for _, inp := range inputs {
113✔
1543
                txn.AddTxIn(&wire.TxIn{
72✔
1544
                        PreviousOutPoint: inp.OutPoint(),
72✔
1545
                        Sequence:         inp.BlocksToMaturity(),
72✔
1546
                })
72✔
1547
        }
72✔
1548

1549
        // Before signing the transaction, check to ensure that it meets some
1550
        // basic validity requirements.
1551
        btx := btcutil.NewTx(txn)
41✔
1552
        if err := blockchain.CheckTransactionSanity(btx); err != nil {
41✔
1553
                return nil, err
×
1554
        }
×
1555

1556
        // Create a sighash cache to improve the performance of hashing and
1557
        // signing SigHashAll inputs.
1558
        prevOutputFetcher, err := input.MultiPrevOutFetcher(inputs)
41✔
1559
        if err != nil {
41✔
1560
                return nil, err
×
1561
        }
×
1562
        hashCache := txscript.NewTxSigHashes(txn, prevOutputFetcher)
41✔
1563

41✔
1564
        // Create a closure that encapsulates the process of initializing a
41✔
1565
        // particular output's witness generation function, computing the
41✔
1566
        // witness, and attaching it to the transaction. This function accepts
41✔
1567
        // an integer index representing the intended txin index, and the
41✔
1568
        // breached output from which it will spend.
41✔
1569
        addWitness := func(idx int, so input.Input) error {
113✔
1570
                // First, we construct a valid witness for this outpoint and
72✔
1571
                // transaction using the SpendableOutput's witness generation
72✔
1572
                // function.
72✔
1573
                inputScript, err := so.CraftInputScript(
72✔
1574
                        b.cfg.Signer, txn, hashCache, prevOutputFetcher, idx,
72✔
1575
                )
72✔
1576
                if err != nil {
72✔
1577
                        return err
×
1578
                }
×
1579

1580
                // Then, we add the witness to the transaction at the
1581
                // appropriate txin index.
1582
                txn.TxIn[idx].Witness = inputScript.Witness
72✔
1583

72✔
1584
                return nil
72✔
1585
        }
1586

1587
        // Finally, generate a witness for each output and attach it to the
1588
        // transaction.
1589
        for i, inp := range inputs {
113✔
1590
                if err := addWitness(i, inp); err != nil {
72✔
1591
                        return nil, err
×
1592
                }
×
1593
        }
1594

1595
        return txn, nil
41✔
1596
}
1597

1598
// RetributionStore handles persistence of retribution states to disk and is
1599
// backed by a boltdb bucket. The primary responsibility of the retribution
1600
// store is to ensure that we can recover from a restart in the middle of a
1601
// breached contract retribution.
1602
type RetributionStore struct {
1603
        db kvdb.Backend
1604
}
1605

1606
// NewRetributionStore creates a new instance of a RetributionStore.
1607
func NewRetributionStore(db kvdb.Backend) *RetributionStore {
23✔
1608
        return &RetributionStore{
23✔
1609
                db: db,
23✔
1610
        }
23✔
1611
}
23✔
1612

1613
// taprootBriefcaseFromRetInfo creates a taprootBriefcase from a retribution
1614
// info struct. This stores all the tap tweak informatoin we need to inrder to
1615
// be able to hadnel breaches after a restart.
1616
func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase {
4✔
1617
        tapCase := newTaprootBriefcase()
4✔
1618

4✔
1619
        for _, bo := range retInfo.breachedOutputs {
8✔
1620
                switch bo.WitnessType() {
4✔
1621
                // For spending from our commitment output on the remote
1622
                // commitment, we'll need to stash the control block.
1623
                case input.TaprootRemoteCommitSpend:
4✔
1624
                        //nolint:lll
4✔
1625
                        tapCase.CtrlBlocks.CommitSweepCtrlBlock = bo.signDesc.ControlBlock
4✔
1626

1627
                // To spend the revoked output again, we'll store the same
1628
                // control block value as above, but in a different place.
1629
                case input.TaprootCommitmentRevoke:
4✔
1630
                        //nolint:lll
4✔
1631
                        tapCase.CtrlBlocks.RevokeSweepCtrlBlock = bo.signDesc.ControlBlock
4✔
1632

1633
                // For spending the HTLC outputs, we'll store the first and
1634
                // second level tweak values.
1635
                case input.TaprootHtlcAcceptedRevoke:
4✔
1636
                        fallthrough
4✔
1637
                case input.TaprootHtlcOfferedRevoke:
4✔
1638
                        resID := newResolverID(bo.OutPoint())
4✔
1639

4✔
1640
                        var firstLevelTweak [32]byte
4✔
1641
                        copy(firstLevelTweak[:], bo.signDesc.TapTweak)
4✔
1642
                        secondLevelTweak := bo.secondLevelTapTweak
4✔
1643

4✔
1644
                        //nolint:lll
4✔
1645
                        tapCase.TapTweaks.BreachedHtlcTweaks[resID] = firstLevelTweak
4✔
1646

4✔
1647
                        //nolint:lll
4✔
1648
                        tapCase.TapTweaks.BreachedSecondLevelHltcTweaks[resID] = secondLevelTweak
4✔
1649
                }
1650
        }
1651

1652
        return tapCase
4✔
1653
}
1654

1655
// applyTaprootRetInfo attaches the taproot specific inforamtion in the tapCase
1656
// to the passed retInfo struct.
1657
func applyTaprootRetInfo(tapCase *taprootBriefcase,
1658
        retInfo *retributionInfo) error {
4✔
1659

4✔
1660
        for i := range retInfo.breachedOutputs {
8✔
1661
                bo := retInfo.breachedOutputs[i]
4✔
1662

4✔
1663
                switch bo.WitnessType() {
4✔
1664
                // For spending from our commitment output on the remote
1665
                // commitment, we'll apply the control block.
1666
                case input.TaprootRemoteCommitSpend:
4✔
1667
                        //nolint:lll
4✔
1668
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.CommitSweepCtrlBlock
4✔
1669

1670
                // To spend the revoked output again, we'll apply the same
1671
                // control block value as above, but to a different place.
1672
                case input.TaprootCommitmentRevoke:
4✔
1673
                        //nolint:lll
4✔
1674
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.RevokeSweepCtrlBlock
4✔
1675

1676
                // For spending the HTLC outputs, we'll apply the first and
1677
                // second level tweak values.
1678
                case input.TaprootHtlcAcceptedRevoke:
4✔
1679
                        fallthrough
4✔
1680
                case input.TaprootHtlcOfferedRevoke:
4✔
1681
                        resID := newResolverID(bo.OutPoint())
4✔
1682

4✔
1683
                        tap1, ok := tapCase.TapTweaks.BreachedHtlcTweaks[resID]
4✔
1684
                        if !ok {
4✔
1685
                                return fmt.Errorf("unable to find taproot "+
×
1686
                                        "tweak for: %v", bo.OutPoint())
×
1687
                        }
×
1688
                        bo.signDesc.TapTweak = tap1[:]
4✔
1689

4✔
1690
                        //nolint:lll
4✔
1691
                        tap2, ok := tapCase.TapTweaks.BreachedSecondLevelHltcTweaks[resID]
4✔
1692
                        if !ok {
4✔
1693
                                return fmt.Errorf("unable to find taproot "+
×
1694
                                        "tweak for: %v", bo.OutPoint())
×
1695
                        }
×
1696
                        bo.secondLevelTapTweak = tap2
4✔
1697
                }
1698

1699
                retInfo.breachedOutputs[i] = bo
4✔
1700
        }
1701

1702
        return nil
4✔
1703
}
1704

1705
// Add adds a retribution state to the RetributionStore, which is then persisted
1706
// to disk.
1707
func (rs *RetributionStore) Add(ret *retributionInfo) error {
18✔
1708
        return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
36✔
1709
                // If this is our first contract breach, the retributionBucket
18✔
1710
                // won't exist, in which case, we just create a new bucket.
18✔
1711
                retBucket, err := tx.CreateTopLevelBucket(retributionBucket)
18✔
1712
                if err != nil {
18✔
1713
                        return err
×
1714
                }
×
1715
                tapRetBucket, err := tx.CreateTopLevelBucket(
18✔
1716
                        taprootRetributionBucket,
18✔
1717
                )
18✔
1718
                if err != nil {
18✔
1719
                        return err
×
1720
                }
×
1721

1722
                var outBuf bytes.Buffer
18✔
1723
                if err := writeOutpoint(&outBuf, &ret.chanPoint); err != nil {
18✔
1724
                        return err
×
1725
                }
×
1726

1727
                var retBuf bytes.Buffer
18✔
1728
                if err := ret.Encode(&retBuf); err != nil {
18✔
1729
                        return err
×
1730
                }
×
1731

1732
                err = retBucket.Put(outBuf.Bytes(), retBuf.Bytes())
18✔
1733
                if err != nil {
18✔
1734
                        return err
×
1735
                }
×
1736

1737
                // If this isn't a taproot channel, then we can exit early here
1738
                // as there's no extra data to write.
1739
                switch {
18✔
1740
                case len(ret.breachedOutputs) == 0:
×
1741
                        return nil
×
1742

1743
                case !txscript.IsPayToTaproot(
1744
                        ret.breachedOutputs[0].signDesc.Output.PkScript,
1745
                ):
18✔
1746
                        return nil
18✔
1747
                }
1748

1749
                // We'll also map the ret info into the taproot storage
1750
                // structure we need for taproot channels.
1751
                var b bytes.Buffer
4✔
1752
                tapRetcase := taprootBriefcaseFromRetInfo(ret)
4✔
1753
                if err := tapRetcase.Encode(&b); err != nil {
4✔
1754
                        return err
×
1755
                }
×
1756

1757
                return tapRetBucket.Put(outBuf.Bytes(), b.Bytes())
4✔
1758
        }, func() {})
18✔
1759
}
1760

1761
// IsBreached queries the retribution store to discern if this channel was
1762
// previously breached. This is used when connecting to a peer to determine if
1763
// it is safe to add a link to the htlcswitch, as we should never add a channel
1764
// that has already been breached.
1765
func (rs *RetributionStore) IsBreached(chanPoint *wire.OutPoint) (bool, error) {
24✔
1766
        var found bool
24✔
1767
        err := kvdb.View(rs.db, func(tx kvdb.RTx) error {
48✔
1768
                retBucket := tx.ReadBucket(retributionBucket)
24✔
1769
                if retBucket == nil {
36✔
1770
                        return nil
12✔
1771
                }
12✔
1772

1773
                var chanBuf bytes.Buffer
16✔
1774
                if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
16✔
1775
                        return err
×
1776
                }
×
1777

1778
                retInfo := retBucket.Get(chanBuf.Bytes())
16✔
1779
                if retInfo != nil {
28✔
1780
                        found = true
12✔
1781
                }
12✔
1782

1783
                return nil
16✔
1784
        }, func() {
24✔
1785
                found = false
24✔
1786
        })
24✔
1787

1788
        return found, err
24✔
1789
}
1790

1791
// Remove removes a retribution state and finalized justice transaction by
1792
// channel point  from the retribution store.
1793
func (rs *RetributionStore) Remove(chanPoint *wire.OutPoint) error {
14✔
1794
        return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
28✔
1795
                retBucket := tx.ReadWriteBucket(retributionBucket)
14✔
1796
                tapRetBucket, err := tx.CreateTopLevelBucket(
14✔
1797
                        taprootRetributionBucket,
14✔
1798
                )
14✔
1799
                if err != nil {
14✔
1800
                        return err
×
1801
                }
×
1802

1803
                // We return an error if the bucket is not already created,
1804
                // since normal operation of the breach arbiter should never
1805
                // try to remove a finalized retribution state that is not
1806
                // already stored in the db.
1807
                if retBucket == nil {
16✔
1808
                        return errors.New("unable to remove retribution " +
2✔
1809
                                "because the retribution bucket doesn't exist")
2✔
1810
                }
2✔
1811

1812
                // Serialize the channel point we are intending to remove.
1813
                var chanBuf bytes.Buffer
12✔
1814
                if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
12✔
1815
                        return err
×
1816
                }
×
1817
                chanBytes := chanBuf.Bytes()
12✔
1818

12✔
1819
                // Remove the persisted retribution info and finalized justice
12✔
1820
                // transaction.
12✔
1821
                if err := retBucket.Delete(chanBytes); err != nil {
12✔
1822
                        return err
×
1823
                }
×
1824

1825
                return tapRetBucket.Delete(chanBytes)
12✔
1826
        }, func() {})
14✔
1827
}
1828

1829
// ForAll iterates through all stored retributions and executes the passed
1830
// callback function on each retribution.
1831
func (rs *RetributionStore) ForAll(cb func(*retributionInfo) error,
1832
        reset func()) error {
50✔
1833

50✔
1834
        return kvdb.View(rs.db, func(tx kvdb.RTx) error {
100✔
1835
                // If the bucket does not exist, then there are no pending
50✔
1836
                // retributions.
50✔
1837
                retBucket := tx.ReadBucket(retributionBucket)
50✔
1838
                if retBucket == nil {
72✔
1839
                        return nil
22✔
1840
                }
22✔
1841
                tapRetBucket := tx.ReadBucket(
32✔
1842
                        taprootRetributionBucket,
32✔
1843
                )
32✔
1844

32✔
1845
                // Otherwise, we fetch each serialized retribution info,
32✔
1846
                // deserialize it, and execute the passed in callback function
32✔
1847
                // on it.
32✔
1848
                return retBucket.ForEach(func(k, retBytes []byte) error {
74✔
1849
                        ret := &retributionInfo{}
42✔
1850
                        err := ret.Decode(bytes.NewBuffer(retBytes))
42✔
1851
                        if err != nil {
42✔
1852
                                return err
×
1853
                        }
×
1854

1855
                        tapInfoBytes := tapRetBucket.Get(k)
42✔
1856
                        if tapInfoBytes != nil {
46✔
1857
                                var tapCase taprootBriefcase
4✔
1858
                                err := tapCase.Decode(
4✔
1859
                                        bytes.NewReader(tapInfoBytes),
4✔
1860
                                )
4✔
1861
                                if err != nil {
4✔
1862
                                        return err
×
1863
                                }
×
1864

1865
                                err = applyTaprootRetInfo(&tapCase, ret)
4✔
1866
                                if err != nil {
4✔
1867
                                        return err
×
1868
                                }
×
1869
                        }
1870

1871
                        return cb(ret)
42✔
1872
                })
1873
        }, reset)
1874
}
1875

1876
// Encode serializes the retribution into the passed byte stream.
1877
func (ret *retributionInfo) Encode(w io.Writer) error {
20✔
1878
        var scratch [4]byte
20✔
1879

20✔
1880
        if _, err := w.Write(ret.commitHash[:]); err != nil {
20✔
1881
                return err
×
1882
        }
×
1883

1884
        if err := writeOutpoint(w, &ret.chanPoint); err != nil {
20✔
1885
                return err
×
1886
        }
×
1887

1888
        if _, err := w.Write(ret.chainHash[:]); err != nil {
20✔
1889
                return err
×
1890
        }
×
1891

1892
        binary.BigEndian.PutUint32(scratch[:], ret.breachHeight)
20✔
1893
        if _, err := w.Write(scratch[:]); err != nil {
20✔
1894
                return err
×
1895
        }
×
1896

1897
        nOutputs := len(ret.breachedOutputs)
20✔
1898
        if err := wire.WriteVarInt(w, 0, uint64(nOutputs)); err != nil {
20✔
1899
                return err
×
1900
        }
×
1901

1902
        for _, output := range ret.breachedOutputs {
58✔
1903
                if err := output.Encode(w); err != nil {
38✔
1904
                        return err
×
1905
                }
×
1906
        }
1907

1908
        return nil
20✔
1909
}
1910

1911
// Decode deserializes a retribution from the passed byte stream.
1912
func (ret *retributionInfo) Decode(r io.Reader) error {
44✔
1913
        var scratch [32]byte
44✔
1914

44✔
1915
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
44✔
1916
                return err
×
1917
        }
×
1918
        hash, err := chainhash.NewHash(scratch[:])
44✔
1919
        if err != nil {
44✔
1920
                return err
×
1921
        }
×
1922
        ret.commitHash = *hash
44✔
1923

44✔
1924
        if err := readOutpoint(r, &ret.chanPoint); err != nil {
44✔
1925
                return err
×
1926
        }
×
1927

1928
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
44✔
1929
                return err
×
1930
        }
×
1931
        chainHash, err := chainhash.NewHash(scratch[:])
44✔
1932
        if err != nil {
44✔
1933
                return err
×
1934
        }
×
1935
        ret.chainHash = *chainHash
44✔
1936

44✔
1937
        if _, err := io.ReadFull(r, scratch[:4]); err != nil {
44✔
1938
                return err
×
1939
        }
×
1940
        ret.breachHeight = binary.BigEndian.Uint32(scratch[:4])
44✔
1941

44✔
1942
        nOutputsU64, err := wire.ReadVarInt(r, 0)
44✔
1943
        if err != nil {
44✔
1944
                return err
×
1945
        }
×
1946
        nOutputs := int(nOutputsU64)
44✔
1947

44✔
1948
        ret.breachedOutputs = make([]breachedOutput, nOutputs)
44✔
1949
        for i := range ret.breachedOutputs {
128✔
1950
                if err := ret.breachedOutputs[i].Decode(r); err != nil {
84✔
1951
                        return err
×
1952
                }
×
1953
        }
1954

1955
        return nil
44✔
1956
}
1957

1958
// Encode serializes a breachedOutput into the passed byte stream.
1959
func (bo *breachedOutput) Encode(w io.Writer) error {
42✔
1960
        var scratch [8]byte
42✔
1961

42✔
1962
        binary.BigEndian.PutUint64(scratch[:8], uint64(bo.amt))
42✔
1963
        if _, err := w.Write(scratch[:8]); err != nil {
42✔
1964
                return err
×
1965
        }
×
1966

1967
        if err := writeOutpoint(w, &bo.outpoint); err != nil {
42✔
1968
                return err
×
1969
        }
×
1970

1971
        err := input.WriteSignDescriptor(w, &bo.signDesc)
42✔
1972
        if err != nil {
42✔
1973
                return err
×
1974
        }
×
1975

1976
        err = wire.WriteVarBytes(w, 0, bo.secondLevelWitnessScript)
42✔
1977
        if err != nil {
42✔
1978
                return err
×
1979
        }
×
1980

1981
        binary.BigEndian.PutUint16(scratch[:2], uint16(bo.witnessType))
42✔
1982
        if _, err := w.Write(scratch[:2]); err != nil {
42✔
1983
                return err
×
1984
        }
×
1985

1986
        return nil
42✔
1987
}
1988

1989
// Decode deserializes a breachedOutput from the passed byte stream.
1990
func (bo *breachedOutput) Decode(r io.Reader) error {
88✔
1991
        var scratch [8]byte
88✔
1992

88✔
1993
        if _, err := io.ReadFull(r, scratch[:8]); err != nil {
88✔
1994
                return err
×
1995
        }
×
1996
        bo.amt = btcutil.Amount(binary.BigEndian.Uint64(scratch[:8]))
88✔
1997

88✔
1998
        if err := readOutpoint(r, &bo.outpoint); err != nil {
88✔
1999
                return err
×
2000
        }
×
2001

2002
        if err := input.ReadSignDescriptor(r, &bo.signDesc); err != nil {
88✔
2003
                return err
×
2004
        }
×
2005

2006
        wScript, err := wire.ReadVarBytes(r, 0, 1000, "witness script")
88✔
2007
        if err != nil {
88✔
2008
                return err
×
2009
        }
×
2010
        bo.secondLevelWitnessScript = wScript
88✔
2011

88✔
2012
        if _, err := io.ReadFull(r, scratch[:2]); err != nil {
88✔
2013
                return err
×
2014
        }
×
2015
        bo.witnessType = input.StandardWitnessType(
88✔
2016
                binary.BigEndian.Uint16(scratch[:2]),
88✔
2017
        )
88✔
2018

88✔
2019
        return nil
88✔
2020
}
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