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

lightningnetwork / lnd / 11219354629

07 Oct 2024 03:56PM UTC coverage: 58.585% (-0.2%) from 58.814%
11219354629

Pull #9147

github

ziggie1984
fixup! sqlc: migration up script for payments.
Pull Request #9147: [Part 1|3] Introduce SQL Payment schema into LND

130227 of 222287 relevant lines covered (58.59%)

29106.19 hits per line

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

81.57
/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 {
201
        return &BreachArbitrator{
202
                cfg:           cfg,
203
                subscriptions: make(map[wire.OutPoint]chan struct{}),
204
                quit:          make(chan struct{}),
205
        }
206
}
207

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

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

2✔
232
        // Load all currently closed channels from disk, we will use the
12✔
233
        // channels that have been marked fully closed to filter the retribution
10✔
234
        // information loaded from disk. This is necessary in the event that the
10✔
235
        // channel was marked fully closed, but was not removed from the
×
236
        // retribution store.
×
237
        closedChans, err := b.cfg.DB.FetchClosedChannels(false)
×
238
        if err != nil {
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",
244
                len(closedChans), len(breachRetInfos))
10✔
245

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

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

12✔
262
                chanPoint := &chanSummary.ChanPoint
2✔
263
                if _, ok := breachRetInfos[*chanPoint]; ok {
2✔
264
                        if err := b.cfg.Store.Remove(chanPoint); err != nil {
2✔
265
                                brarLog.Errorf("Unable to remove closed "+
4✔
266
                                        "chanid=%v from breach arbiter: %v",
2✔
267
                                        chanPoint, err)
268
                                return err
269
                        }
2✔
270
                        delete(breachRetInfos, *chanPoint)
2✔
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 {
×
280
                retInfo := breachRetInfos[chanPoint]
×
281

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

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

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

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

2✔
308
        return nil
2✔
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
10✔
313
// the BreachArbitrator have gracefully exited.
10✔
314
func (b *BreachArbitrator) Stop() error {
10✔
315
        b.stopped.Do(func() {
10✔
316
                brarLog.Infof("Breach arbiter shutting down...")
317
                defer brarLog.Debug("Breach arbiter shutdown complete")
318

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

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

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

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

2✔
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()
×
353
        defer b.Unlock()
×
354
        b.subscriptions[*chanPoint] = c
×
355

×
356
        return false, nil
357
}
358

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

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

8✔
372
// contractObserver is the primary goroutine for the BreachArbitrator. This
2✔
373
// goroutine is responsible for handling breach events coming from the
2✔
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
6✔
377
// wallet.
378
//
379
// NOTE: This MUST be run as a goroutine.
380
func (b *BreachArbitrator) contractObserver() {
381
        defer b.wg.Done()
382

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

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

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

10✔
401
// spend is used to wrap the index of the retributionInfo output that gets
402
// spent together with the spend details.
10✔
403
type spend struct {
10✔
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) {
414

415
        inputs := breachInfo.breachedOutputs
416

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

15✔
528
                return spends, nil
31✔
529

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

535
// convertToSecondLevelRevoke takes a breached output, and a transaction that
15✔
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
2✔
538
// when we go to sweep a breached commitment transaction, but the cheating
2✔
539
// party has already attempted to take it to the second level.
540
func convertToSecondLevelRevoke(bo *breachedOutput, breachInfo *retributionInfo,
541
        spendDetails *chainntnfs.SpendDetail) {
542

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

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

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

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

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

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

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

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

631
                        // In this case we'll morph our initial revoke
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
                }
2✔
641

2✔
642
                // Now that we have determined the spend is done by us, we
2✔
643
                // count the total and revoked funds swept depending on the
2✔
644
                // input type.
2✔
645
                switch breachedOutput.witnessType {
2✔
646
                // If the output being revoked is the remote commitment output
2✔
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:
14✔
653

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

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

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

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

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

44✔
678
        // Update our remaining set of outputs before continuing with
14✔
679
        // another attempt at publication.
680
        breachInfo.breachedOutputs = inputs[:nextIndex]
681
        return totalFunds, revokedFunds
18✔
682
}
18✔
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.
15✔
688
//
15✔
689
// NOTE: This MUST be run as a goroutine.
690
//
691
//nolint:funlen
692
func (b *BreachArbitrator) exactRetribution(
693
        confChan *chainntnfs.ConfirmationEvent, breachInfo *retributionInfo) {
694

695
        defer b.wg.Done()
696

697
        // TODO(roasbeef): state needs to be checkpointed here
698
        select {
699
        case _, ok := <-confChan.Confirmed:
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
8✔
704
                }
8✔
705

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

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

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

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

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

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

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

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

×
755
        wg.Add(1)
×
756
        go func() {
×
757
                defer wg.Done()
×
758

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

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

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

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

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

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

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

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

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

21✔
819
                        wg.Wait()
6✔
820
                        goto justiceTxBroadcast
6✔
821

6✔
822
                // On every new block, we check whether we should republish the
6✔
823
                // transactions.
6✔
824
                case epoch, ok := <-newBlockChan.Epochs:
6✔
825
                        if !ok {
6✔
826
                                return
6✔
827
                        }
6✔
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 +
835
                                blocksPassedSplitPublish
836
                        if uint32(epoch.Height) < splitHeight {
837
                                continue Loop
6✔
838
                        }
839

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

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

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

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

1✔
869
                        if justiceTxs.spendHTLCs != nil {
1✔
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 "+
1✔
879
                                                "HTLC out spending justice "+
2✔
880
                                                "tx: %v", err)
1✔
881
                                }
1✔
882
                        }
1✔
883

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

1✔
887
                                brarLog.Debugf("Broadcasting justice tx "+
1✔
888
                                        "spending second-level HTLC output: %v",
1✔
889
                                        lnutils.SpewLogClosure(tx))
1✔
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
                                }
2✔
897
                        }
1✔
898

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

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

×
911
        // Wait for our go routine to exit.
912
        wg.Wait()
913
}
1✔
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 {
×
918
        // With the channel closed, mark it in the database as such.
×
919
        err := b.cfg.DB.MarkChanFullyClosed(chanPoint)
×
920
        if err != nil {
×
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)
×
927
        if err != nil {
×
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.
2✔
938
        b.notifyBreachComplete(chanPoint)
2✔
939

940
        return nil
941
}
942

943
// handleBreachHandoff handles a new breach event, by writing it to disk, then
6✔
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
6✔
949
// transaction receives a necessary number of confirmations.
6✔
950
//
6✔
951
// NOTE: This MUST be run as a goroutine.
6✔
952
func (b *BreachArbitrator) handleBreachHandoff(
×
953
        breachEvent *ContractBreachEvent) {
×
954

955
        defer b.wg.Done()
956

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

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

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

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

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

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

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

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

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

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

10✔
1018
        // Now that the breach has been persisted, try to send an
10✔
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)
×
1023

×
1024
        // Bail if we failed to persist retribution info.
×
1025
        if err != nil {
×
1026
                return
1027
        }
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
11✔
1031
        // the breach transaction (the revoked commitment transaction) has been
1✔
1032
        // confirmed in the chain to ensure we're not dealing with a moving
1✔
1033
        // target.
1✔
1034
        breachTXID := &retInfo.commitHash
1✔
1035
        breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
1036
        cfChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
1037
                breachTXID, breachScript, 1, retInfo.breachHeight,
1038
        )
1039
        if err != nil {
9✔
1040
                brarLog.Errorf("Unable to register for conf updates for "+
9✔
1041
                        "txid: %v, err: %v", breachTXID, err)
9✔
1042
                return
9✔
1043
        }
9✔
1044

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

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

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

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

8✔
1069
        witnessFunc input.WitnessGenerator
8✔
1070
}
8✔
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,
8✔
1077
        signDescriptor *input.SignDescriptor,
8✔
1078
        confHeight uint32) breachedOutput {
8✔
1079

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

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

1092
// Amount returns the number of satoshis contained in the breached output.
1093
func (bo *breachedOutput) Amount() btcutil.Amount {
1094
        return bo.amt
1095
}
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 {
1100
        return bo.outpoint
1101
}
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 {
1107
        return nil
1108
}
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) {
51✔
1113
        return 0, false
51✔
1114
}
51✔
1115

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

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

1128
// CraftInputScript computes a valid witness that allows us to spend from the
174✔
1129
// breached output. It does so by first generating and memoizing the witness
174✔
1130
// generation function, which parameterized primarily by the witness type and
174✔
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,
404✔
1135
        prevOutputFetcher txscript.PrevOutputFetcher,
404✔
1136
        txinIdx int) (*input.Script, error) {
404✔
1137

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

2✔
1144
        // Now that we have ensured that the witness generation function has
1145
        // been initialized, we can proceed to execute it and generate the
1146
        // witness for this particular breached output.
1147
        return bo.witnessFunc(txn, hashCache, txinIdx)
×
1148
}
×
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 {
131✔
1154
        // If the output is a to_remote output we can claim, and it's of the
131✔
1155
        // confirmed type (or is a taproot channel that always has the CSV 1),
131✔
1156
        // we must wait one block before claiming it.
1157
        switch bo.witnessType {
1158
        case input.CommitmentToRemoteConfirmed, input.TaprootRemoteCommitSpend:
1159
                return 1
369✔
1160
        }
369✔
1161

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

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

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

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

75✔
1181
// retributionInfo encapsulates all the data needed to sweep all the contested
75✔
1182
// funds within a channel whose contract has been breached by the prior
75✔
1183
// counterparty. This struct is used to create the justice transaction which
75✔
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
72✔
1189
        chainHash    chainhash.Hash
72✔
1190
        breachHeight uint32
72✔
1191

72✔
1192
        breachedOutputs []breachedOutput
72✔
1193
}
4✔
1194

4✔
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.
70✔
1199
func newRetributionInfo(chanPoint *wire.OutPoint,
1200
        breachInfo *lnwallet.BreachRetribution) *retributionInfo {
1201

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

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

1213
        isTaproot := func() bool {
1214
                if breachInfo.LocalOutputSignDesc != nil {
40✔
1215
                        return txscript.IsPayToTaproot(
40✔
1216
                                breachInfo.LocalOutputSignDesc.Output.PkScript,
40✔
1217
                        )
1218
                }
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 {
1233
                var witnessType input.StandardWitnessType
1234
                switch {
1235
                case isTaproot:
1236
                        witnessType = input.TaprootRemoteCommitSpend
1237

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

1241
                        witnessType = input.CommitSpendNoDelayTweakless
12✔
1242

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

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

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

×
1263
                breachedOutputs = append(breachedOutputs, localOutput)
×
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 {
1272
                var witType input.StandardWitnessType
1273
                if isTaproot {
24✔
1274
                        witType = input.TaprootCommitmentRevoke
12✔
1275
                } else {
12✔
1276
                        witType = input.CommitmentRevoke
2✔
1277
                }
2✔
1278

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

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

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

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

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

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

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

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

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

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

21✔
1340
// justiceTxVariants is a struct that holds transactions which exacts "justice"
9✔
1341
// by sweeping ALL the funds within the channel which we are now entitled to
9✔
1342
// due to a breach of the channel's contract by the counterparty. There are
9✔
1343
// four variants of justice transactions:
9✔
1344
//
9✔
1345
// 1. The "normal" justice tx that spends all breached outputs.
2✔
1346
// 2. A tx that spends only the breached to_local output and to_remote output
2✔
1347
// (can be nil if none of these exist).
1348
// 3. A tx that spends all the breached commitment level HTLC outputs (can be
2✔
1349
// nil if none of these exist or if all have been taken to the second level).
2✔
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
7✔
1355
// the HTLC outputs with low fee children, hindering our normal justice tx that
7✔
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.
9✔
1359
type justiceTxVariants struct {
9✔
1360
        spendAll              *wire.MsgTx
9✔
1361
        spendCommitOuts       *wire.MsgTx
9✔
1362
        spendHTLCs            *wire.MsgTx
9✔
1363
        spendSecondLevelHTLCs []*wire.MsgTx
9✔
1364
}
9✔
1365

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

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

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

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

1392
                        htlcInputs = append(htlcInputs, inp)
1393

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

1397
                        secondLevelInputs = append(secondLevelInputs, inp)
1398

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

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

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

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

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

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

1434
                        continue
9✔
1435
                }
9✔
1436

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

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

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

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

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

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

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

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

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

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

1494
        txWeight := weightEstimate.Weight()
1495

1496
        return b.sweepSpendableOutputsTxn(txWeight, spendableOutputs...)
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) {
1503

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

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

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

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

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

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

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

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

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

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

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

×
1584
                return nil
1585
        }
1586

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

40✔
1595
        return txn, nil
×
1596
}
×
1597

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

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

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

40✔
1619
        for _, bo := range retInfo.breachedOutputs {
40✔
1620
                switch bo.WitnessType() {
40✔
1621
                // For spending from our commitment output on the remote
×
1622
                // commitment, we'll need to stash the control block.
×
1623
                case input.TaprootRemoteCommitSpend:
×
1624
                        //nolint:lll
×
1625
                        tapCase.CtrlBlocks.CommitSweepCtrlBlock = bo.signDesc.ControlBlock
×
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:
40✔
1630
                        //nolint:lll
40✔
1631
                        tapCase.CtrlBlocks.RevokeSweepCtrlBlock = bo.signDesc.ControlBlock
40✔
1632

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

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

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

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

1652
        return tapCase
1653
}
1654

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

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

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

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

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

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

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

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

1702
        return nil
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 {
1708
        return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
1709
                // If this is our first contract breach, the retributionBucket
21✔
1710
                // won't exist, in which case, we just create a new bucket.
21✔
1711
                retBucket, err := tx.CreateTopLevelBucket(retributionBucket)
21✔
1712
                if err != nil {
21✔
1713
                        return err
21✔
1714
                }
1715
                tapRetBucket, err := tx.CreateTopLevelBucket(
1716
                        taprootRetributionBucket,
1717
                )
1718
                if err != nil {
2✔
1719
                        return err
2✔
1720
                }
2✔
1721

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

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

2✔
1732
                err = retBucket.Put(outBuf.Bytes(), retBuf.Bytes())
2✔
1733
                if err != nil {
2✔
1734
                        return err
2✔
1735
                }
2✔
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 {
2✔
1740
                case len(ret.breachedOutputs) == 0:
2✔
1741
                        return nil
2✔
1742

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

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

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

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

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

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

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

2✔
1788
        return found, err
2✔
1789
}
4✔
1790

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

2✔
1803
                // We return an error if the bucket is not already created,
2✔
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 {
1808
                        return errors.New("unable to remove retribution " +
2✔
1809
                                "because the retribution bucket doesn't exist")
2✔
1810
                }
2✔
1811

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

×
1908
        return nil
1909
}
14✔
1910

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

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

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

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

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

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

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

×
1955
        return nil
1956
}
10✔
1957

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

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

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

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

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

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

1986
        return nil
40✔
1987
}
42✔
1988

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

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

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

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

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

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

2019
        return nil
18✔
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