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

lightningnetwork / lnd / 9840691252

08 Jul 2024 01:34PM UTC coverage: 58.404% (+0.08%) from 58.325%
9840691252

Pull #8900

github

guggero
Makefile: add GOCC variable
Pull Request #8900: Makefile: add GOCC variable

123350 of 211200 relevant lines covered (58.4%)

27929.2 hits per line

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

81.84
/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/davecgh/go-spew/spew"
17
        "github.com/lightningnetwork/lnd/chainntnfs"
18
        "github.com/lightningnetwork/lnd/channeldb"
19
        "github.com/lightningnetwork/lnd/input"
20
        "github.com/lightningnetwork/lnd/kvdb"
21
        "github.com/lightningnetwork/lnd/labels"
22
        "github.com/lightningnetwork/lnd/lntypes"
23
        "github.com/lightningnetwork/lnd/lnwallet"
24
        "github.com/lightningnetwork/lnd/lnwallet/chainfee"
25
)
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

189
        cfg *BreachConfig
190

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12✔
308
        return nil
12✔
309
}
310

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

528
                return spends, nil
17✔
529

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
639
                        continue
2✔
640
                }
641

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

17✔
735
        brarLog.Debugf("Broadcasting justice tx: %v", newLogClosure(func() string {
21✔
736
                return spew.Sdump(finalTx)
4✔
737
        }))
4✔
738

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
858
                                brarLog.Debugf("Broadcasting justice tx "+
1✔
859
                                        "spending commitment outs: %v",
1✔
860
                                        newLogClosure(func() string {
1✔
861
                                                return spew.Sdump(tx)
×
862
                                        }))
×
863

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

872
                        if justiceTxs.spendHTLCs != nil {
2✔
873
                                tx := justiceTxs.spendHTLCs
1✔
874

1✔
875
                                brarLog.Debugf("Broadcasting justice tx "+
1✔
876
                                        "spending HTLC outs: %v",
1✔
877
                                        newLogClosure(func() string {
1✔
878
                                                return spew.Sdump(tx)
×
879
                                        }))
×
880

881
                                err = b.cfg.PublishTransaction(tx, label)
1✔
882
                                if err != nil {
1✔
883
                                        brarLog.Warnf("Unable to broadcast "+
×
884
                                                "HTLC out spending justice "+
×
885
                                                "tx: %v", err)
×
886
                                }
×
887
                        }
888

889
                        for _, tx := range justiceTxs.spendSecondLevelHTLCs {
1✔
890
                                tx := tx
×
891

×
892
                                brarLog.Debugf("Broadcasting justice tx "+
×
893
                                        "spending second-level HTLC output: %v",
×
894
                                        newLogClosure(func() string {
×
895
                                                return spew.Sdump(tx)
×
896
                                        }))
×
897

898
                                err = b.cfg.PublishTransaction(tx, label)
×
899
                                if err != nil {
×
900
                                        brarLog.Warnf("Unable to broadcast "+
×
901
                                                "second-level HTLC out "+
×
902
                                                "spending justice tx: %v", err)
×
903
                                }
×
904
                        }
905

906
                case err := <-errChan:
×
907
                        if err != errBrarShuttingDown {
×
908
                                brarLog.Errorf("error waiting for "+
×
909
                                        "spend event: %v", err)
×
910
                        }
×
911
                        break Loop
×
912

913
                case <-b.quit:
4✔
914
                        break Loop
4✔
915
                }
916
        }
917

918
        // Wait for our go routine to exit.
919
        wg.Wait()
8✔
920
}
921

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

931
        // Justice has been carried out; we can safely delete the retribution
932
        // info from the database.
933
        err = b.cfg.Store.Remove(chanPoint)
8✔
934
        if err != nil {
8✔
935
                return fmt.Errorf("unable to remove retribution from db: %w",
×
936
                        err)
×
937
        }
×
938

939
        // This is after the Remove call so that the chan passed in via
940
        // SubscribeBreachComplete is always notified, no matter when it is
941
        // called. Otherwise, if notifyBreachComplete was before Remove, a
942
        // very rare edge case could occur in which SubscribeBreachComplete
943
        // is called after notifyBreachComplete and before Remove, meaning the
944
        // caller would never be notified.
945
        b.notifyBreachComplete(chanPoint)
8✔
946

8✔
947
        return nil
8✔
948
}
949

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

12✔
962
        defer b.wg.Done()
12✔
963

12✔
964
        chanPoint := breachEvent.ChanPoint
12✔
965
        brarLog.Debugf("Handling breach handoff for ChannelPoint(%v)",
12✔
966
                chanPoint)
12✔
967

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

12✔
977
        // Immediately notify the HTLC switch that this link has been
12✔
978
        // breached in order to ensure any incoming or outgoing
12✔
979
        // multi-hop HTLCs aren't sent over this link, nor any other
12✔
980
        // links associated with this peer.
12✔
981
        b.cfg.CloseLink(&chanPoint, CloseBreach)
12✔
982

12✔
983
        // TODO(roasbeef): need to handle case of remote broadcast
12✔
984
        // mid-local initiated state-transition, possible
12✔
985
        // false-positive?
12✔
986

12✔
987
        // Acquire the mutex to ensure consistency between the call to
12✔
988
        // IsBreached and Add below.
12✔
989
        b.Lock()
12✔
990

12✔
991
        // We first check if this breach info is already added to the
12✔
992
        // retribution store.
12✔
993
        breached, err := b.cfg.Store.IsBreached(&chanPoint)
12✔
994
        if err != nil {
12✔
995
                b.Unlock()
×
996
                brarLog.Errorf("Unable to check breach info in DB: %v", err)
×
997

×
998
                // Notify about the failed lookup and return.
×
999
                breachEvent.ProcessACK(err)
×
1000
                return
×
1001
        }
×
1002

1003
        // If this channel is already marked as breached in the retribution
1004
        // store, we already have handled the handoff for this breach. In this
1005
        // case we can safely ACK the handoff, and return.
1006
        if breached {
13✔
1007
                b.Unlock()
1✔
1008
                breachEvent.ProcessACK(nil)
1✔
1009
                return
1✔
1010
        }
1✔
1011

1012
        // Using the breach information provided by the wallet and the
1013
        // channel snapshot, construct the retribution information that
1014
        // will be persisted to disk.
1015
        retInfo := newRetributionInfo(&chanPoint, breachInfo)
11✔
1016

11✔
1017
        // Persist the pending retribution state to disk.
11✔
1018
        err = b.cfg.Store.Add(retInfo)
11✔
1019
        b.Unlock()
11✔
1020
        if err != nil {
12✔
1021
                brarLog.Errorf("Unable to persist retribution "+
1✔
1022
                        "info to db: %v", err)
1✔
1023
        }
1✔
1024

1025
        // Now that the breach has been persisted, try to send an
1026
        // acknowledgment back to the close observer with the error. If
1027
        // the ack is successful, the close observer will mark the
1028
        // channel as pending-closed in the channeldb.
1029
        breachEvent.ProcessACK(err)
11✔
1030

11✔
1031
        // Bail if we failed to persist retribution info.
11✔
1032
        if err != nil {
12✔
1033
                return
1✔
1034
        }
1✔
1035

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

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

10✔
1055
        // With the retribution state persisted, channel close persisted, and
10✔
1056
        // notification registered, we launch a new goroutine which will
10✔
1057
        // finalize the channel retribution after the breach transaction has
10✔
1058
        // been confirmed.
10✔
1059
        b.wg.Add(1)
10✔
1060
        go b.exactRetribution(cfChan, retInfo)
10✔
1061
}
1062

1063
// breachedOutput contains all the information needed to sweep a breached
1064
// output. A breached output is an output that we are now entitled to due to a
1065
// revoked commitment transaction being broadcast.
1066
type breachedOutput struct {
1067
        amt         btcutil.Amount
1068
        outpoint    wire.OutPoint
1069
        witnessType input.StandardWitnessType
1070
        signDesc    input.SignDescriptor
1071
        confHeight  uint32
1072

1073
        secondLevelWitnessScript []byte
1074
        secondLevelTapTweak      [32]byte
1075

1076
        witnessFunc input.WitnessGenerator
1077
}
1078

1079
// makeBreachedOutput assembles a new breachedOutput that can be used by the
1080
// breach arbiter to construct a justice or sweep transaction.
1081
func makeBreachedOutput(outpoint *wire.OutPoint,
1082
        witnessType input.StandardWitnessType,
1083
        secondLevelScript []byte,
1084
        signDescriptor *input.SignDescriptor,
1085
        confHeight uint32) breachedOutput {
53✔
1086

53✔
1087
        amount := signDescriptor.Output.Value
53✔
1088

53✔
1089
        return breachedOutput{
53✔
1090
                amt:                      btcutil.Amount(amount),
53✔
1091
                outpoint:                 *outpoint,
53✔
1092
                secondLevelWitnessScript: secondLevelScript,
53✔
1093
                witnessType:              witnessType,
53✔
1094
                signDesc:                 *signDescriptor,
53✔
1095
                confHeight:               confHeight,
53✔
1096
        }
53✔
1097
}
53✔
1098

1099
// Amount returns the number of satoshis contained in the breached output.
1100
func (bo *breachedOutput) Amount() btcutil.Amount {
176✔
1101
        return bo.amt
176✔
1102
}
176✔
1103

1104
// OutPoint returns the breached output's identifier that is to be included as a
1105
// transaction input.
1106
func (bo *breachedOutput) OutPoint() wire.OutPoint {
398✔
1107
        return bo.outpoint
398✔
1108
}
398✔
1109

1110
// RequiredTxOut returns a non-nil TxOut if input commits to a certain
1111
// transaction output. This is used in the SINGLE|ANYONECANPAY case to make
1112
// sure any presigned input is still valid by including the output.
1113
func (bo *breachedOutput) RequiredTxOut() *wire.TxOut {
4✔
1114
        return nil
4✔
1115
}
4✔
1116

1117
// RequiredLockTime returns whether this input commits to a tx locktime that
1118
// must be used in the transaction including it.
1119
func (bo *breachedOutput) RequiredLockTime() (uint32, bool) {
×
1120
        return 0, false
×
1121
}
×
1122

1123
// WitnessType returns the type of witness that must be generated to spend the
1124
// breached output.
1125
func (bo *breachedOutput) WitnessType() input.WitnessType {
127✔
1126
        return bo.witnessType
127✔
1127
}
127✔
1128

1129
// SignDesc returns the breached output's SignDescriptor, which is used during
1130
// signing to compute the witness.
1131
func (bo *breachedOutput) SignDesc() *input.SignDescriptor {
359✔
1132
        return &bo.signDesc
359✔
1133
}
359✔
1134

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

73✔
1145
        // First, we ensure that the witness generation function has been
73✔
1146
        // initialized for this breached output.
73✔
1147
        signDesc := bo.SignDesc()
73✔
1148
        signDesc.PrevOutputFetcher = prevOutputFetcher
73✔
1149
        bo.witnessFunc = bo.witnessType.WitnessGenerator(signer, signDesc)
73✔
1150

73✔
1151
        // Now that we have ensured that the witness generation function has
73✔
1152
        // been initialized, we can proceed to execute it and generate the
73✔
1153
        // witness for this particular breached output.
73✔
1154
        return bo.witnessFunc(txn, hashCache, txinIdx)
73✔
1155
}
73✔
1156

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

1169
        // All other breached outputs have no CSV delay.
1170
        return 0
68✔
1171
}
1172

1173
// HeightHint returns the minimum height at which a confirmed spending tx can
1174
// occur.
1175
func (bo *breachedOutput) HeightHint() uint32 {
4✔
1176
        return bo.confHeight
4✔
1177
}
4✔
1178

1179
// UnconfParent returns information about a possibly unconfirmed parent tx.
1180
func (bo *breachedOutput) UnconfParent() *input.TxInfo {
4✔
1181
        return nil
4✔
1182
}
4✔
1183

1184
// Add compile-time constraint ensuring breachedOutput implements the Input
1185
// interface.
1186
var _ input.Input = (*breachedOutput)(nil)
1187

1188
// retributionInfo encapsulates all the data needed to sweep all the contested
1189
// funds within a channel whose contract has been breached by the prior
1190
// counterparty. This struct is used to create the justice transaction which
1191
// spends all outputs of the commitment transaction into an output controlled
1192
// by the wallet.
1193
type retributionInfo struct {
1194
        commitHash   chainhash.Hash
1195
        chanPoint    wire.OutPoint
1196
        chainHash    chainhash.Hash
1197
        breachHeight uint32
1198

1199
        breachedOutputs []breachedOutput
1200
}
1201

1202
// newRetributionInfo constructs a retributionInfo containing all the
1203
// information required by the breach arbiter to recover funds from breached
1204
// channels.  The information is primarily populated using the BreachRetribution
1205
// delivered by the wallet when it detects a channel breach.
1206
func newRetributionInfo(chanPoint *wire.OutPoint,
1207
        breachInfo *lnwallet.BreachRetribution) *retributionInfo {
14✔
1208

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

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

14✔
1220
        isTaproot := func() bool {
28✔
1221
                if breachInfo.LocalOutputSignDesc != nil {
28✔
1222
                        return txscript.IsPayToTaproot(
14✔
1223
                                breachInfo.LocalOutputSignDesc.Output.PkScript,
14✔
1224
                        )
14✔
1225
                }
14✔
1226

1227
                return txscript.IsPayToTaproot(
×
1228
                        breachInfo.RemoteOutputSignDesc.Output.PkScript,
×
1229
                )
×
1230
        }()
1231

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

1245
                case !isTaproot &&
1246
                        breachInfo.LocalOutputSignDesc.SingleTweak == nil:
14✔
1247

14✔
1248
                        witnessType = input.CommitSpendNoDelayTweakless
14✔
1249

1250
                case !isTaproot:
4✔
1251
                        witnessType = input.CommitmentNoDelay
4✔
1252
                }
1253

1254
                // If the local delay is non-zero, it means this output is of
1255
                // the confirmed to_remote type.
1256
                if !isTaproot && breachInfo.LocalDelay != 0 {
18✔
1257
                        witnessType = input.CommitmentToRemoteConfirmed
4✔
1258
                }
4✔
1259

1260
                localOutput := makeBreachedOutput(
14✔
1261
                        &breachInfo.LocalOutpoint,
14✔
1262
                        witnessType,
14✔
1263
                        // No second level script as this is a commitment
14✔
1264
                        // output.
14✔
1265
                        nil,
14✔
1266
                        breachInfo.LocalOutputSignDesc,
14✔
1267
                        breachInfo.BreachHeight,
14✔
1268
                )
14✔
1269

14✔
1270
                breachedOutputs = append(breachedOutputs, localOutput)
14✔
1271
        }
1272

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

1286
                remoteOutput := makeBreachedOutput(
11✔
1287
                        &breachInfo.RemoteOutpoint,
11✔
1288
                        witType,
11✔
1289
                        // No second level script as this is a commitment
11✔
1290
                        // output.
11✔
1291
                        nil,
11✔
1292
                        breachInfo.RemoteOutputSignDesc,
11✔
1293
                        breachInfo.BreachHeight,
11✔
1294
                )
11✔
1295

11✔
1296
                breachedOutputs = append(breachedOutputs, remoteOutput)
11✔
1297
        }
1298

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

1312
                case isTaproot && !breachedHtlc.IsIncoming:
4✔
1313
                        htlcWitnessType = input.TaprootHtlcOfferedRevoke
4✔
1314

1315
                case !isTaproot && breachedHtlc.IsIncoming:
×
1316
                        htlcWitnessType = input.HtlcAcceptedRevoke
×
1317

1318
                case !isTaproot && !breachedHtlc.IsIncoming:
7✔
1319
                        htlcWitnessType = input.HtlcOfferedRevoke
7✔
1320
                }
1321

1322
                htlcOutput := makeBreachedOutput(
11✔
1323
                        &breachInfo.HtlcRetributions[i].OutPoint,
11✔
1324
                        htlcWitnessType,
11✔
1325
                        breachInfo.HtlcRetributions[i].SecondLevelWitnessScript,
11✔
1326
                        &breachInfo.HtlcRetributions[i].SignDesc,
11✔
1327
                        breachInfo.BreachHeight,
11✔
1328
                )
11✔
1329

11✔
1330
                // For taproot outputs, we also need to hold onto the second
11✔
1331
                // level tap tweak as well.
11✔
1332
                //nolint:lll
11✔
1333
                htlcOutput.secondLevelTapTweak = breachedHtlc.SecondLevelTapTweak
11✔
1334

11✔
1335
                breachedOutputs = append(breachedOutputs, htlcOutput)
11✔
1336
        }
1337

1338
        return &retributionInfo{
14✔
1339
                commitHash:      breachInfo.BreachTxHash,
14✔
1340
                chainHash:       breachInfo.ChainHash,
14✔
1341
                chanPoint:       *chanPoint,
14✔
1342
                breachedOutputs: breachedOutputs,
14✔
1343
                breachHeight:    breachInfo.BreachHeight,
14✔
1344
        }
14✔
1345
}
1346

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

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

18✔
1380
        var (
18✔
1381
                allInputs         []input.Input
18✔
1382
                commitInputs      []input.Input
18✔
1383
                htlcInputs        []input.Input
18✔
1384
                secondLevelInputs []input.Input
18✔
1385
        )
18✔
1386

18✔
1387
        for i := range breachedOutputs {
55✔
1388
                // Grab locally scoped reference to breached output.
37✔
1389
                inp := &breachedOutputs[i]
37✔
1390
                allInputs = append(allInputs, inp)
37✔
1391

37✔
1392
                // Check if the input is from a commitment output, a commitment
37✔
1393
                // level HTLC output or a second level HTLC output.
37✔
1394
                switch inp.WitnessType() {
37✔
1395
                case input.HtlcAcceptedRevoke, input.HtlcOfferedRevoke,
1396
                        input.TaprootHtlcAcceptedRevoke,
1397
                        input.TaprootHtlcOfferedRevoke:
14✔
1398

14✔
1399
                        htlcInputs = append(htlcInputs, inp)
14✔
1400

1401
                case input.HtlcSecondLevelRevoke,
1402
                        input.TaprootHtlcSecondLevelRevoke:
3✔
1403

3✔
1404
                        secondLevelInputs = append(secondLevelInputs, inp)
3✔
1405

1406
                default:
24✔
1407
                        commitInputs = append(commitInputs, inp)
24✔
1408
                }
1409
        }
1410

1411
        var (
18✔
1412
                txs = &justiceTxVariants{}
18✔
1413
                err error
18✔
1414
        )
18✔
1415

18✔
1416
        // For each group of inputs, create a tx that spends them.
18✔
1417
        txs.spendAll, err = b.createSweepTx(allInputs...)
18✔
1418
        if err != nil {
18✔
1419
                return nil, err
×
1420
        }
×
1421

1422
        txs.spendCommitOuts, err = b.createSweepTx(commitInputs...)
18✔
1423
        if err != nil {
18✔
1424
                brarLog.Errorf("could not create sweep tx for commitment "+
×
1425
                        "outputs: %v", err)
×
1426
        }
×
1427

1428
        txs.spendHTLCs, err = b.createSweepTx(htlcInputs...)
18✔
1429
        if err != nil {
18✔
1430
                brarLog.Errorf("could not create sweep tx for HTLC outputs: %v",
×
1431
                        err)
×
1432
        }
×
1433

1434
        secondLevelSweeps := make([]*wire.MsgTx, 0, len(secondLevelInputs))
18✔
1435
        for _, input := range secondLevelInputs {
21✔
1436
                sweepTx, err := b.createSweepTx(input)
3✔
1437
                if err != nil {
3✔
1438
                        brarLog.Errorf("could not create sweep tx for "+
×
1439
                                "second-level HTLC output: %v", err)
×
1440

×
1441
                        continue
×
1442
                }
1443

1444
                secondLevelSweeps = append(secondLevelSweeps, sweepTx)
3✔
1445
        }
1446
        txs.spendSecondLevelHTLCs = secondLevelSweeps
18✔
1447

18✔
1448
        return txs, nil
18✔
1449
}
1450

1451
// createSweepTx creates a tx that sweeps the passed inputs back to our wallet.
1452
func (b *BreachArbitrator) createSweepTx(inputs ...input.Input) (*wire.MsgTx,
1453
        error) {
49✔
1454

49✔
1455
        if len(inputs) == 0 {
61✔
1456
                return nil, nil
12✔
1457
        }
12✔
1458

1459
        // We will assemble the breached outputs into a slice of spendable
1460
        // outputs, while simultaneously computing the estimated weight of the
1461
        // transaction.
1462
        var (
41✔
1463
                spendableOutputs []input.Input
41✔
1464
                weightEstimate   input.TxWeightEstimator
41✔
1465
        )
41✔
1466

41✔
1467
        // Allocate enough space to potentially hold each of the breached
41✔
1468
        // outputs in the retribution info.
41✔
1469
        spendableOutputs = make([]input.Input, 0, len(inputs))
41✔
1470

41✔
1471
        // The justice transaction we construct will be a segwit transaction
41✔
1472
        // that pays to a p2tr output. Components such as the version,
41✔
1473
        // nLockTime, and output are already included in the TxWeightEstimator.
41✔
1474
        weightEstimate.AddP2TROutput()
41✔
1475

41✔
1476
        // Next, we iterate over the breached outputs contained in the
41✔
1477
        // retribution info.  For each, we switch over the witness type such
41✔
1478
        // that we contribute the appropriate weight for each input and
41✔
1479
        // witness, finally adding to our list of spendable outputs.
41✔
1480
        for i := range inputs {
111✔
1481
                // Grab locally scoped reference to breached output.
70✔
1482
                inp := inputs[i]
70✔
1483

70✔
1484
                // First, determine the appropriate estimated witness weight
70✔
1485
                // for the give witness type of this breached output. If the
70✔
1486
                // witness weight cannot be estimated, we will omit it from the
70✔
1487
                // transaction.
70✔
1488
                witnessWeight, _, err := inp.WitnessType().SizeUpperBound()
70✔
1489
                if err != nil {
70✔
1490
                        brarLog.Warnf("could not determine witness weight "+
×
1491
                                "for breached output in retribution info: %v",
×
1492
                                err)
×
1493
                        continue
×
1494
                }
1495
                weightEstimate.AddWitnessInput(witnessWeight)
70✔
1496

70✔
1497
                // Finally, append this input to our list of spendable outputs.
70✔
1498
                spendableOutputs = append(spendableOutputs, inp)
70✔
1499
        }
1500

1501
        txWeight := weightEstimate.Weight()
41✔
1502

41✔
1503
        return b.sweepSpendableOutputsTxn(txWeight, spendableOutputs...)
41✔
1504
}
1505

1506
// sweepSpendableOutputsTxn creates a signed transaction from a sequence of
1507
// spendable outputs by sweeping the funds into a single p2wkh output.
1508
func (b *BreachArbitrator) sweepSpendableOutputsTxn(txWeight lntypes.WeightUnit,
1509
        inputs ...input.Input) (*wire.MsgTx, error) {
41✔
1510

41✔
1511
        // First, we obtain a new public key script from the wallet which we'll
41✔
1512
        // sweep the funds to.
41✔
1513
        // TODO(roasbeef): possibly create many outputs to minimize change in
41✔
1514
        // the future?
41✔
1515
        pkScript, err := b.cfg.GenSweepScript()
41✔
1516
        if err != nil {
41✔
1517
                return nil, err
×
1518
        }
×
1519

1520
        // Compute the total amount contained in the inputs.
1521
        var totalAmt btcutil.Amount
41✔
1522
        for _, inp := range inputs {
111✔
1523
                totalAmt += btcutil.Amount(inp.SignDesc().Output.Value)
70✔
1524
        }
70✔
1525

1526
        // We'll actually attempt to target inclusion within the next two
1527
        // blocks as we'd like to sweep these funds back into our wallet ASAP.
1528
        feePerKw, err := b.cfg.Estimator.EstimateFeePerKW(justiceTxConfTarget)
41✔
1529
        if err != nil {
41✔
1530
                return nil, err
×
1531
        }
×
1532
        txFee := feePerKw.FeeForWeight(txWeight)
41✔
1533

41✔
1534
        // TODO(roasbeef): already start to siphon their funds into fees
41✔
1535
        sweepAmt := int64(totalAmt - txFee)
41✔
1536

41✔
1537
        // With the fee calculated, we can now create the transaction using the
41✔
1538
        // information gathered above and the provided retribution information.
41✔
1539
        txn := wire.NewMsgTx(2)
41✔
1540

41✔
1541
        // We begin by adding the output to which our funds will be deposited.
41✔
1542
        txn.AddTxOut(&wire.TxOut{
41✔
1543
                PkScript: pkScript,
41✔
1544
                Value:    sweepAmt,
41✔
1545
        })
41✔
1546

41✔
1547
        // Next, we add all of the spendable outputs as inputs to the
41✔
1548
        // transaction.
41✔
1549
        for _, inp := range inputs {
111✔
1550
                txn.AddTxIn(&wire.TxIn{
70✔
1551
                        PreviousOutPoint: inp.OutPoint(),
70✔
1552
                        Sequence:         inp.BlocksToMaturity(),
70✔
1553
                })
70✔
1554
        }
70✔
1555

1556
        // Before signing the transaction, check to ensure that it meets some
1557
        // basic validity requirements.
1558
        btx := btcutil.NewTx(txn)
41✔
1559
        if err := blockchain.CheckTransactionSanity(btx); err != nil {
41✔
1560
                return nil, err
×
1561
        }
×
1562

1563
        // Create a sighash cache to improve the performance of hashing and
1564
        // signing SigHashAll inputs.
1565
        prevOutputFetcher, err := input.MultiPrevOutFetcher(inputs)
41✔
1566
        if err != nil {
41✔
1567
                return nil, err
×
1568
        }
×
1569
        hashCache := txscript.NewTxSigHashes(txn, prevOutputFetcher)
41✔
1570

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

1587
                // Then, we add the witness to the transaction at the
1588
                // appropriate txin index.
1589
                txn.TxIn[idx].Witness = inputScript.Witness
70✔
1590

70✔
1591
                return nil
70✔
1592
        }
1593

1594
        // Finally, generate a witness for each output and attach it to the
1595
        // transaction.
1596
        for i, inp := range inputs {
111✔
1597
                if err := addWitness(i, inp); err != nil {
70✔
1598
                        return nil, err
×
1599
                }
×
1600
        }
1601

1602
        return txn, nil
41✔
1603
}
1604

1605
// RetributionStore handles persistence of retribution states to disk and is
1606
// backed by a boltdb bucket. The primary responsibility of the retribution
1607
// store is to ensure that we can recover from a restart in the middle of a
1608
// breached contract retribution.
1609
type RetributionStore struct {
1610
        db kvdb.Backend
1611
}
1612

1613
// NewRetributionStore creates a new instance of a RetributionStore.
1614
func NewRetributionStore(db kvdb.Backend) *RetributionStore {
23✔
1615
        return &RetributionStore{
23✔
1616
                db: db,
23✔
1617
        }
23✔
1618
}
23✔
1619

1620
// taprootBriefcaseFromRetInfo creates a taprootBriefcase from a retribution
1621
// info struct. This stores all the tap tweak informatoin we need to inrder to
1622
// be able to hadnel breaches after a restart.
1623
func taprootBriefcaseFromRetInfo(retInfo *retributionInfo) *taprootBriefcase {
4✔
1624
        tapCase := newTaprootBriefcase()
4✔
1625

4✔
1626
        for _, bo := range retInfo.breachedOutputs {
8✔
1627
                switch bo.WitnessType() {
4✔
1628
                // For spending from our commitment output on the remote
1629
                // commitment, we'll need to stash the control block.
1630
                case input.TaprootRemoteCommitSpend:
4✔
1631
                        //nolint:lll
4✔
1632
                        tapCase.CtrlBlocks.CommitSweepCtrlBlock = bo.signDesc.ControlBlock
4✔
1633

1634
                // To spend the revoked output again, we'll store the same
1635
                // control block value as above, but in a different place.
1636
                case input.TaprootCommitmentRevoke:
4✔
1637
                        //nolint:lll
4✔
1638
                        tapCase.CtrlBlocks.RevokeSweepCtrlBlock = bo.signDesc.ControlBlock
4✔
1639

1640
                // For spending the HTLC outputs, we'll store the first and
1641
                // second level tweak values.
1642
                case input.TaprootHtlcAcceptedRevoke:
4✔
1643
                        fallthrough
4✔
1644
                case input.TaprootHtlcOfferedRevoke:
4✔
1645
                        resID := newResolverID(bo.OutPoint())
4✔
1646

4✔
1647
                        var firstLevelTweak [32]byte
4✔
1648
                        copy(firstLevelTweak[:], bo.signDesc.TapTweak)
4✔
1649
                        secondLevelTweak := bo.secondLevelTapTweak
4✔
1650

4✔
1651
                        //nolint:lll
4✔
1652
                        tapCase.TapTweaks.BreachedHtlcTweaks[resID] = firstLevelTweak
4✔
1653

4✔
1654
                        //nolint:lll
4✔
1655
                        tapCase.TapTweaks.BreachedSecondLevelHltcTweaks[resID] = secondLevelTweak
4✔
1656
                }
1657
        }
1658

1659
        return tapCase
4✔
1660
}
1661

1662
// applyTaprootRetInfo attaches the taproot specific inforamtion in the tapCase
1663
// to the passed retInfo struct.
1664
func applyTaprootRetInfo(tapCase *taprootBriefcase,
1665
        retInfo *retributionInfo) error {
4✔
1666

4✔
1667
        for i := range retInfo.breachedOutputs {
8✔
1668
                bo := retInfo.breachedOutputs[i]
4✔
1669

4✔
1670
                switch bo.WitnessType() {
4✔
1671
                // For spending from our commitment output on the remote
1672
                // commitment, we'll apply the control block.
1673
                case input.TaprootRemoteCommitSpend:
4✔
1674
                        //nolint:lll
4✔
1675
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.CommitSweepCtrlBlock
4✔
1676

1677
                // To spend the revoked output again, we'll apply the same
1678
                // control block value as above, but to a different place.
1679
                case input.TaprootCommitmentRevoke:
4✔
1680
                        //nolint:lll
4✔
1681
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.RevokeSweepCtrlBlock
4✔
1682

1683
                // For spending the HTLC outputs, we'll apply the first and
1684
                // second level tweak values.
1685
                case input.TaprootHtlcAcceptedRevoke:
4✔
1686
                        fallthrough
4✔
1687
                case input.TaprootHtlcOfferedRevoke:
4✔
1688
                        resID := newResolverID(bo.OutPoint())
4✔
1689

4✔
1690
                        tap1, ok := tapCase.TapTweaks.BreachedHtlcTweaks[resID]
4✔
1691
                        if !ok {
4✔
1692
                                return fmt.Errorf("unable to find taproot "+
×
1693
                                        "tweak for: %v", bo.OutPoint())
×
1694
                        }
×
1695
                        bo.signDesc.TapTweak = tap1[:]
4✔
1696

4✔
1697
                        //nolint:lll
4✔
1698
                        tap2, ok := tapCase.TapTweaks.BreachedSecondLevelHltcTweaks[resID]
4✔
1699
                        if !ok {
4✔
1700
                                return fmt.Errorf("unable to find taproot "+
×
1701
                                        "tweak for: %v", bo.OutPoint())
×
1702
                        }
×
1703
                        bo.secondLevelTapTweak = tap2
4✔
1704
                }
1705

1706
                retInfo.breachedOutputs[i] = bo
4✔
1707
        }
1708

1709
        return nil
4✔
1710
}
1711

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

1729
                var outBuf bytes.Buffer
18✔
1730
                if err := writeOutpoint(&outBuf, &ret.chanPoint); err != nil {
18✔
1731
                        return err
×
1732
                }
×
1733

1734
                var retBuf bytes.Buffer
18✔
1735
                if err := ret.Encode(&retBuf); err != nil {
18✔
1736
                        return err
×
1737
                }
×
1738

1739
                err = retBucket.Put(outBuf.Bytes(), retBuf.Bytes())
18✔
1740
                if err != nil {
18✔
1741
                        return err
×
1742
                }
×
1743

1744
                // If this isn't a taproot channel, then we can exit early here
1745
                // as there's no extra data to write.
1746
                switch {
18✔
1747
                case len(ret.breachedOutputs) == 0:
×
1748
                        return nil
×
1749

1750
                case !txscript.IsPayToTaproot(
1751
                        ret.breachedOutputs[0].signDesc.Output.PkScript,
1752
                ):
18✔
1753
                        return nil
18✔
1754
                }
1755

1756
                // We'll also map the ret info into the taproot storage
1757
                // structure we need for taproot channels.
1758
                var b bytes.Buffer
4✔
1759
                tapRetcase := taprootBriefcaseFromRetInfo(ret)
4✔
1760
                if err := tapRetcase.Encode(&b); err != nil {
4✔
1761
                        return err
×
1762
                }
×
1763

1764
                return tapRetBucket.Put(outBuf.Bytes(), b.Bytes())
4✔
1765
        }, func() {})
18✔
1766
}
1767

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

1780
                var chanBuf bytes.Buffer
16✔
1781
                if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
16✔
1782
                        return err
×
1783
                }
×
1784

1785
                retInfo := retBucket.Get(chanBuf.Bytes())
16✔
1786
                if retInfo != nil {
28✔
1787
                        found = true
12✔
1788
                }
12✔
1789

1790
                return nil
16✔
1791
        }, func() {
24✔
1792
                found = false
24✔
1793
        })
24✔
1794

1795
        return found, err
24✔
1796
}
1797

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

1810
                // We return an error if the bucket is not already created,
1811
                // since normal operation of the breach arbiter should never
1812
                // try to remove a finalized retribution state that is not
1813
                // already stored in the db.
1814
                if retBucket == nil {
16✔
1815
                        return errors.New("unable to remove retribution " +
2✔
1816
                                "because the retribution bucket doesn't exist")
2✔
1817
                }
2✔
1818

1819
                // Serialize the channel point we are intending to remove.
1820
                var chanBuf bytes.Buffer
12✔
1821
                if err := writeOutpoint(&chanBuf, chanPoint); err != nil {
12✔
1822
                        return err
×
1823
                }
×
1824
                chanBytes := chanBuf.Bytes()
12✔
1825

12✔
1826
                // Remove the persisted retribution info and finalized justice
12✔
1827
                // transaction.
12✔
1828
                if err := retBucket.Delete(chanBytes); err != nil {
12✔
1829
                        return err
×
1830
                }
×
1831

1832
                return tapRetBucket.Delete(chanBytes)
12✔
1833
        }, func() {})
14✔
1834
}
1835

1836
// ForAll iterates through all stored retributions and executes the passed
1837
// callback function on each retribution.
1838
func (rs *RetributionStore) ForAll(cb func(*retributionInfo) error,
1839
        reset func()) error {
50✔
1840

50✔
1841
        return kvdb.View(rs.db, func(tx kvdb.RTx) error {
100✔
1842
                // If the bucket does not exist, then there are no pending
50✔
1843
                // retributions.
50✔
1844
                retBucket := tx.ReadBucket(retributionBucket)
50✔
1845
                if retBucket == nil {
72✔
1846
                        return nil
22✔
1847
                }
22✔
1848
                tapRetBucket := tx.ReadBucket(
32✔
1849
                        taprootRetributionBucket,
32✔
1850
                )
32✔
1851

32✔
1852
                // Otherwise, we fetch each serialized retribution info,
32✔
1853
                // deserialize it, and execute the passed in callback function
32✔
1854
                // on it.
32✔
1855
                return retBucket.ForEach(func(k, retBytes []byte) error {
74✔
1856
                        ret := &retributionInfo{}
42✔
1857
                        err := ret.Decode(bytes.NewBuffer(retBytes))
42✔
1858
                        if err != nil {
42✔
1859
                                return err
×
1860
                        }
×
1861

1862
                        tapInfoBytes := tapRetBucket.Get(k)
42✔
1863
                        if tapInfoBytes != nil {
46✔
1864
                                var tapCase taprootBriefcase
4✔
1865
                                err := tapCase.Decode(
4✔
1866
                                        bytes.NewReader(tapInfoBytes),
4✔
1867
                                )
4✔
1868
                                if err != nil {
4✔
1869
                                        return err
×
1870
                                }
×
1871

1872
                                err = applyTaprootRetInfo(&tapCase, ret)
4✔
1873
                                if err != nil {
4✔
1874
                                        return err
×
1875
                                }
×
1876
                        }
1877

1878
                        return cb(ret)
42✔
1879
                })
1880
        }, reset)
1881
}
1882

1883
// Encode serializes the retribution into the passed byte stream.
1884
func (ret *retributionInfo) Encode(w io.Writer) error {
20✔
1885
        var scratch [4]byte
20✔
1886

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

1891
        if err := writeOutpoint(w, &ret.chanPoint); err != nil {
20✔
1892
                return err
×
1893
        }
×
1894

1895
        if _, err := w.Write(ret.chainHash[:]); err != nil {
20✔
1896
                return err
×
1897
        }
×
1898

1899
        binary.BigEndian.PutUint32(scratch[:], ret.breachHeight)
20✔
1900
        if _, err := w.Write(scratch[:]); err != nil {
20✔
1901
                return err
×
1902
        }
×
1903

1904
        nOutputs := len(ret.breachedOutputs)
20✔
1905
        if err := wire.WriteVarInt(w, 0, uint64(nOutputs)); err != nil {
20✔
1906
                return err
×
1907
        }
×
1908

1909
        for _, output := range ret.breachedOutputs {
58✔
1910
                if err := output.Encode(w); err != nil {
38✔
1911
                        return err
×
1912
                }
×
1913
        }
1914

1915
        return nil
20✔
1916
}
1917

1918
// Decode deserializes a retribution from the passed byte stream.
1919
func (ret *retributionInfo) Decode(r io.Reader) error {
44✔
1920
        var scratch [32]byte
44✔
1921

44✔
1922
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
44✔
1923
                return err
×
1924
        }
×
1925
        hash, err := chainhash.NewHash(scratch[:])
44✔
1926
        if err != nil {
44✔
1927
                return err
×
1928
        }
×
1929
        ret.commitHash = *hash
44✔
1930

44✔
1931
        if err := readOutpoint(r, &ret.chanPoint); err != nil {
44✔
1932
                return err
×
1933
        }
×
1934

1935
        if _, err := io.ReadFull(r, scratch[:]); err != nil {
44✔
1936
                return err
×
1937
        }
×
1938
        chainHash, err := chainhash.NewHash(scratch[:])
44✔
1939
        if err != nil {
44✔
1940
                return err
×
1941
        }
×
1942
        ret.chainHash = *chainHash
44✔
1943

44✔
1944
        if _, err := io.ReadFull(r, scratch[:4]); err != nil {
44✔
1945
                return err
×
1946
        }
×
1947
        ret.breachHeight = binary.BigEndian.Uint32(scratch[:4])
44✔
1948

44✔
1949
        nOutputsU64, err := wire.ReadVarInt(r, 0)
44✔
1950
        if err != nil {
44✔
1951
                return err
×
1952
        }
×
1953
        nOutputs := int(nOutputsU64)
44✔
1954

44✔
1955
        ret.breachedOutputs = make([]breachedOutput, nOutputs)
44✔
1956
        for i := range ret.breachedOutputs {
128✔
1957
                if err := ret.breachedOutputs[i].Decode(r); err != nil {
84✔
1958
                        return err
×
1959
                }
×
1960
        }
1961

1962
        return nil
44✔
1963
}
1964

1965
// Encode serializes a breachedOutput into the passed byte stream.
1966
func (bo *breachedOutput) Encode(w io.Writer) error {
42✔
1967
        var scratch [8]byte
42✔
1968

42✔
1969
        binary.BigEndian.PutUint64(scratch[:8], uint64(bo.amt))
42✔
1970
        if _, err := w.Write(scratch[:8]); err != nil {
42✔
1971
                return err
×
1972
        }
×
1973

1974
        if err := writeOutpoint(w, &bo.outpoint); err != nil {
42✔
1975
                return err
×
1976
        }
×
1977

1978
        err := input.WriteSignDescriptor(w, &bo.signDesc)
42✔
1979
        if err != nil {
42✔
1980
                return err
×
1981
        }
×
1982

1983
        err = wire.WriteVarBytes(w, 0, bo.secondLevelWitnessScript)
42✔
1984
        if err != nil {
42✔
1985
                return err
×
1986
        }
×
1987

1988
        binary.BigEndian.PutUint16(scratch[:2], uint16(bo.witnessType))
42✔
1989
        if _, err := w.Write(scratch[:2]); err != nil {
42✔
1990
                return err
×
1991
        }
×
1992

1993
        return nil
42✔
1994
}
1995

1996
// Decode deserializes a breachedOutput from the passed byte stream.
1997
func (bo *breachedOutput) Decode(r io.Reader) error {
88✔
1998
        var scratch [8]byte
88✔
1999

88✔
2000
        if _, err := io.ReadFull(r, scratch[:8]); err != nil {
88✔
2001
                return err
×
2002
        }
×
2003
        bo.amt = btcutil.Amount(binary.BigEndian.Uint64(scratch[:8]))
88✔
2004

88✔
2005
        if err := readOutpoint(r, &bo.outpoint); err != nil {
88✔
2006
                return err
×
2007
        }
×
2008

2009
        if err := input.ReadSignDescriptor(r, &bo.signDesc); err != nil {
88✔
2010
                return err
×
2011
        }
×
2012

2013
        wScript, err := wire.ReadVarBytes(r, 0, 1000, "witness script")
88✔
2014
        if err != nil {
88✔
2015
                return err
×
2016
        }
×
2017
        bo.secondLevelWitnessScript = wScript
88✔
2018

88✔
2019
        if _, err := io.ReadFull(r, scratch[:2]); err != nil {
88✔
2020
                return err
×
2021
        }
×
2022
        bo.witnessType = input.StandardWitnessType(
88✔
2023
                binary.BigEndian.Uint16(scratch[:2]),
88✔
2024
        )
88✔
2025

88✔
2026
        return nil
88✔
2027
}
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