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

lightningnetwork / lnd / 9915780197

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

push

github

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

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

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

73.6
/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 {
3✔
201
        return &BreachArbitrator{
3✔
202
                cfg:           cfg,
3✔
203
                subscriptions: make(map[wire.OutPoint]chan struct{}),
3✔
204
                quit:          make(chan struct{}),
3✔
205
        }
3✔
206
}
3✔
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 {
3✔
211
        var err error
3✔
212
        b.started.Do(func() {
6✔
213
                brarLog.Info("Breach arbiter starting")
3✔
214
                err = b.start()
3✔
215
        })
3✔
216
        return err
3✔
217
}
218

219
func (b *BreachArbitrator) start() error {
3✔
220
        // Load all retributions currently persisted in the retribution store.
3✔
221
        var breachRetInfos map[wire.OutPoint]retributionInfo
3✔
222
        if err := b.cfg.Store.ForAll(func(ret *retributionInfo) error {
6✔
223
                breachRetInfos[ret.chanPoint] = *ret
3✔
224
                return nil
3✔
225
        }, func() {
6✔
226
                breachRetInfos = make(map[wire.OutPoint]retributionInfo)
3✔
227
        }); err != nil {
3✔
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)
3✔
238
        if err != nil {
3✔
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",
3✔
244
                len(closedChans), len(breachRetInfos))
3✔
245

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

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

262
                chanPoint := &chanSummary.ChanPoint
3✔
263
                if _, ok := breachRetInfos[*chanPoint]; ok {
3✔
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 {
6✔
280
                retInfo := breachRetInfos[chanPoint]
3✔
281

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

3✔
285
                // Register for a notification when the breach transaction is
3✔
286
                // confirmed on chain.
3✔
287
                breachTXID := retInfo.commitHash
3✔
288
                breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
3✔
289
                confChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
290
                        &breachTXID, breachScript, 1, retInfo.breachHeight,
3✔
291
                )
3✔
292
                if err != nil {
3✔
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)
3✔
301
                go b.exactRetribution(confChan, &retInfo)
3✔
302
        }
303

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

3✔
308
        return nil
3✔
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 {
3✔
315
        b.stopped.Do(func() {
6✔
316
                brarLog.Infof("Breach arbiter shutting down...")
3✔
317
                defer brarLog.Debug("Breach arbiter shutdown complete")
3✔
318

3✔
319
                close(b.quit)
3✔
320
                b.wg.Wait()
3✔
321
        })
3✔
322
        return nil
3✔
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) {
×
328
        return b.cfg.Store.IsBreached(chanPoint)
×
329
}
×
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) {
3✔
335

3✔
336
        breached, err := b.cfg.Store.IsBreached(chanPoint)
3✔
337
        if err != nil {
3✔
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
1✔
344
                // was cleaned up successfully. Any subscription that occurs
1✔
345
                // happens after the breach information was persisted to the
1✔
346
                // underlying store.
1✔
347
                return true, nil
1✔
348
        }
1✔
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()
3✔
353
        defer b.Unlock()
3✔
354
        b.subscriptions[*chanPoint] = c
3✔
355

3✔
356
        return false, nil
3✔
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) {
3✔
362
        b.Lock()
3✔
363
        defer b.Unlock()
3✔
364
        if c, ok := b.subscriptions[*chanPoint]; ok {
6✔
365
                close(c)
3✔
366
        }
3✔
367

368
        // Remove the subscription.
369
        delete(b.subscriptions, *chanPoint)
3✔
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() {
3✔
381
        defer b.wg.Done()
3✔
382

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

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

395
                case <-b.quit:
3✔
396
                        return
3✔
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) {
3✔
414

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

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

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

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

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

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

3✔
439
                // If we have already registered for a notification for this
3✔
440
                // output, we'll reuse it.
3✔
441
                spendNtfn, ok := spendNtfns[breachedOutput.outpoint]
3✔
442
                if !ok {
6✔
443
                        var err error
3✔
444
                        spendNtfn, err = b.cfg.Notifier.RegisterSpendNtfn(
3✔
445
                                &breachedOutput.outpoint,
3✔
446
                                breachedOutput.signDesc.Output.PkScript,
3✔
447
                                breachInfo.breachHeight,
3✔
448
                        )
3✔
449
                        if err != nil {
3✔
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
3✔
465
                }
466

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

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

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

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

3✔
493
                                // Finally we'll signal the anySpend channel
3✔
494
                                // that a spend was detected, such that the
3✔
495
                                // other goroutines can be shut down.
3✔
496
                                anySpend <- struct{}{}
3✔
497
                        case <-exit:
3✔
498
                                return
3✔
499
                        case <-b.quit:
3✔
500
                                return
3✔
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 {
3✔
508
        // A goroutine have signalled that a spend occurred.
509
        case <-anySpend:
3✔
510
                // Signal for the remaining goroutines to exit.
3✔
511
                close(exit)
3✔
512
                wg.Wait()
3✔
513

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

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

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

528
                return spends, nil
3✔
529

530
        case <-b.quit:
3✔
531
                return nil, errBrarShuttingDown
3✔
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) {
×
542

×
543
        // In this case, we'll modify the witness type of this output to
×
544
        // actually prepare for a second level revoke.
×
545
        isTaproot := txscript.IsPayToTaproot(bo.signDesc.Output.PkScript)
×
546
        if isTaproot {
×
547
                bo.witnessType = input.TaprootHtlcSecondLevelRevoke
×
548
        } else {
×
549
                bo.witnessType = input.HtlcSecondLevelRevoke
×
550
        }
×
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
×
555
        spendInputIndex := spendDetails.SpenderInputIndex
×
556
        oldOp := bo.outpoint
×
557
        bo.outpoint = wire.OutPoint{
×
558
                Hash:  spendingTx.TxHash(),
×
559
                Index: spendInputIndex,
×
560
        }
×
561

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

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

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

×
580
        brarLog.Warnf("HTLC(%v) for ChannelPoint(%v) has been spent to the "+
×
581
                "second-level, adjusting -> %v", oldOp, breachInfo.chanPoint,
×
582
                bo.outpoint)
×
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) {
3✔
590

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

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

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

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

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

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

×
639
                        continue
×
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 {
3✔
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:
3✔
653

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

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

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

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

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

678
        // Update our remaining set of outputs before continuing with
679
        // another attempt at publication.
680
        breachInfo.breachedOutputs = inputs[:nextIndex]
3✔
681
        return totalFunds, revokedFunds
3✔
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) {
3✔
694

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

3✔
697
        // TODO(roasbeef): state needs to be checkpointed here
3✔
698
        select {
3✔
699
        case _, ok := <-confChan.Confirmed:
3✔
700
                // If the second value is !ok, then the channel has been closed
3✔
701
                // signifying a daemon shutdown, so we exit.
3✔
702
                if !ok {
3✔
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:
×
709
                return
×
710
        }
711

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

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

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

3✔
724
justiceTxBroadcast:
3✔
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)
3✔
729
        if err != nil {
3✔
730
                brarLog.Errorf("Unable to create justice tx: %v", err)
×
731
                return
×
732
        }
×
733
        finalTx := justiceTxs.spendAll
3✔
734

3✔
735
        brarLog.Debugf("Broadcasting justice tx: %v", newLogClosure(func() string {
6✔
736
                return spew.Sdump(finalTx)
3✔
737
        }))
3✔
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)
3✔
742
        err = b.cfg.PublishTransaction(finalTx, label)
3✔
743
        if err != nil {
6✔
744
                brarLog.Errorf("Unable to broadcast justice tx: %v", err)
3✔
745
        }
3✔
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 (
3✔
751
                spendChan = make(chan []spend, 1)
3✔
752
                errChan   = make(chan error, 1)
3✔
753
                wg        sync.WaitGroup
3✔
754
        )
3✔
755

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

3✔
760
                spends, err := b.waitForSpendEvent(breachInfo, spendNtfns)
3✔
761
                if err != nil {
6✔
762
                        errChan <- err
3✔
763
                        return
3✔
764
                }
3✔
765
                spendChan <- spends
3✔
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)
3✔
772
        if err != nil {
3✔
773
                brarLog.Errorf("Unable to register for block notifications: %v",
×
774
                        err)
×
775
                return
×
776
        }
×
777
        defer newBlockChan.Cancel()
3✔
778

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

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

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

3✔
802
                                err = b.cleanupBreach(&breachInfo.chanPoint)
3✔
803
                                if err != nil {
3✔
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
3✔
814
                        }
815

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

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

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

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

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

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

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

872
                        if justiceTxs.spendHTLCs != nil {
×
873
                                tx := justiceTxs.spendHTLCs
×
874

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

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

889
                        for _, tx := range justiceTxs.spendSecondLevelHTLCs {
×
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:
3✔
914
                        break Loop
3✔
915
                }
916
        }
917

918
        // Wait for our go routine to exit.
919
        wg.Wait()
3✔
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 {
3✔
925
        // With the channel closed, mark it in the database as such.
3✔
926
        err := b.cfg.DB.MarkChanFullyClosed(chanPoint)
3✔
927
        if err != nil {
3✔
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)
3✔
934
        if err != nil {
3✔
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)
3✔
946

3✔
947
        return nil
3✔
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) {
3✔
961

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

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

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

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

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

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

3✔
991
        // We first check if this breach info is already added to the
3✔
992
        // retribution store.
3✔
993
        breached, err := b.cfg.Store.IsBreached(&chanPoint)
3✔
994
        if err != nil {
3✔
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 {
3✔
1007
                b.Unlock()
×
1008
                breachEvent.ProcessACK(nil)
×
1009
                return
×
1010
        }
×
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)
3✔
1016

3✔
1017
        // Persist the pending retribution state to disk.
3✔
1018
        err = b.cfg.Store.Add(retInfo)
3✔
1019
        b.Unlock()
3✔
1020
        if err != nil {
3✔
1021
                brarLog.Errorf("Unable to persist retribution "+
×
1022
                        "info to db: %v", err)
×
1023
        }
×
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)
3✔
1030

3✔
1031
        // Bail if we failed to persist retribution info.
3✔
1032
        if err != nil {
3✔
1033
                return
×
1034
        }
×
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
3✔
1042
        breachScript := retInfo.breachedOutputs[0].signDesc.Output.PkScript
3✔
1043
        cfChan, err := b.cfg.Notifier.RegisterConfirmationsNtfn(
3✔
1044
                breachTXID, breachScript, 1, retInfo.breachHeight,
3✔
1045
        )
3✔
1046
        if err != nil {
3✔
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 "+
3✔
1053
                "for confirmation, then justice will be served!", breachTXID)
3✔
1054

3✔
1055
        // With the retribution state persisted, channel close persisted, and
3✔
1056
        // notification registered, we launch a new goroutine which will
3✔
1057
        // finalize the channel retribution after the breach transaction has
3✔
1058
        // been confirmed.
3✔
1059
        b.wg.Add(1)
3✔
1060
        go b.exactRetribution(cfChan, retInfo)
3✔
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 {
3✔
1086

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

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

1099
// Amount returns the number of satoshis contained in the breached output.
1100
func (bo *breachedOutput) Amount() btcutil.Amount {
3✔
1101
        return bo.amt
3✔
1102
}
3✔
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 {
3✔
1107
        return bo.outpoint
3✔
1108
}
3✔
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 {
3✔
1114
        return nil
3✔
1115
}
3✔
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 {
3✔
1126
        return bo.witnessType
3✔
1127
}
3✔
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 {
3✔
1132
        return &bo.signDesc
3✔
1133
}
3✔
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) {
3✔
1144

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

3✔
1151
        // Now that we have ensured that the witness generation function has
3✔
1152
        // been initialized, we can proceed to execute it and generate the
3✔
1153
        // witness for this particular breached output.
3✔
1154
        return bo.witnessFunc(txn, hashCache, txinIdx)
3✔
1155
}
3✔
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 {
3✔
1161
        // If the output is a to_remote output we can claim, and it's of the
3✔
1162
        // confirmed type (or is a taproot channel that always has the CSV 1),
3✔
1163
        // we must wait one block before claiming it.
3✔
1164
        switch bo.witnessType {
3✔
1165
        case input.CommitmentToRemoteConfirmed, input.TaprootRemoteCommitSpend:
3✔
1166
                return 1
3✔
1167
        }
1168

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

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

1179
// UnconfParent returns information about a possibly unconfirmed parent tx.
1180
func (bo *breachedOutput) UnconfParent() *input.TxInfo {
3✔
1181
        return nil
3✔
1182
}
3✔
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 {
3✔
1208

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

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

3✔
1220
        isTaproot := func() bool {
6✔
1221
                if breachInfo.LocalOutputSignDesc != nil {
6✔
1222
                        return txscript.IsPayToTaproot(
3✔
1223
                                breachInfo.LocalOutputSignDesc.Output.PkScript,
3✔
1224
                        )
3✔
1225
                }
3✔
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 {
6✔
1240
                var witnessType input.StandardWitnessType
3✔
1241
                switch {
3✔
1242
                case isTaproot:
3✔
1243
                        witnessType = input.TaprootRemoteCommitSpend
3✔
1244

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

3✔
1248
                        witnessType = input.CommitSpendNoDelayTweakless
3✔
1249

1250
                case !isTaproot:
3✔
1251
                        witnessType = input.CommitmentNoDelay
3✔
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 {
6✔
1257
                        witnessType = input.CommitmentToRemoteConfirmed
3✔
1258
                }
3✔
1259

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

3✔
1270
                breachedOutputs = append(breachedOutputs, localOutput)
3✔
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 {
6✔
1279
                var witType input.StandardWitnessType
3✔
1280
                if isTaproot {
6✔
1281
                        witType = input.TaprootCommitmentRevoke
3✔
1282
                } else {
6✔
1283
                        witType = input.CommitmentRevoke
3✔
1284
                }
3✔
1285

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

3✔
1296
                breachedOutputs = append(breachedOutputs, remoteOutput)
3✔
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 {
6✔
1304
                // Using the breachedHtlc's incoming flag, determine the
3✔
1305
                // appropriate witness type that needs to be generated in order
3✔
1306
                // to sweep the HTLC output.
3✔
1307
                var htlcWitnessType input.StandardWitnessType
3✔
1308
                switch {
3✔
1309
                case isTaproot && breachedHtlc.IsIncoming:
3✔
1310
                        htlcWitnessType = input.TaprootHtlcAcceptedRevoke
3✔
1311

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

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

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

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

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

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

1338
        return &retributionInfo{
3✔
1339
                commitHash:      breachInfo.BreachTxHash,
3✔
1340
                chainHash:       breachInfo.ChainHash,
3✔
1341
                chanPoint:       *chanPoint,
3✔
1342
                breachedOutputs: breachedOutputs,
3✔
1343
                breachHeight:    breachInfo.BreachHeight,
3✔
1344
        }
3✔
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) {
3✔
1379

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

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

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

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

1401
                case input.HtlcSecondLevelRevoke,
1402
                        input.TaprootHtlcSecondLevelRevoke:
×
1403

×
1404
                        secondLevelInputs = append(secondLevelInputs, inp)
×
1405

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

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

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

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

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

1434
        secondLevelSweeps := make([]*wire.MsgTx, 0, len(secondLevelInputs))
3✔
1435
        for _, input := range secondLevelInputs {
3✔
1436
                sweepTx, err := b.createSweepTx(input)
×
1437
                if err != nil {
×
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)
×
1445
        }
1446
        txs.spendSecondLevelHTLCs = secondLevelSweeps
3✔
1447

3✔
1448
        return txs, nil
3✔
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) {
3✔
1454

3✔
1455
        if len(inputs) == 0 {
6✔
1456
                return nil, nil
3✔
1457
        }
3✔
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 (
3✔
1463
                spendableOutputs []input.Input
3✔
1464
                weightEstimate   input.TxWeightEstimator
3✔
1465
        )
3✔
1466

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

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

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

3✔
1484
                // First, determine the appropriate estimated witness weight
3✔
1485
                // for the give witness type of this breached output. If the
3✔
1486
                // witness weight cannot be estimated, we will omit it from the
3✔
1487
                // transaction.
3✔
1488
                witnessWeight, _, err := inp.WitnessType().SizeUpperBound()
3✔
1489
                if err != nil {
3✔
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)
3✔
1496

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

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

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

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

1520
        // Compute the total amount contained in the inputs.
1521
        var totalAmt btcutil.Amount
3✔
1522
        for _, inp := range inputs {
6✔
1523
                totalAmt += btcutil.Amount(inp.SignDesc().Output.Value)
3✔
1524
        }
3✔
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)
3✔
1529
        if err != nil {
3✔
1530
                return nil, err
×
1531
        }
×
1532
        txFee := feePerKw.FeeForWeight(txWeight)
3✔
1533

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

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

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

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

1556
        // Before signing the transaction, check to ensure that it meets some
1557
        // basic validity requirements.
1558
        btx := btcutil.NewTx(txn)
3✔
1559
        if err := blockchain.CheckTransactionSanity(btx); err != nil {
3✔
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)
3✔
1566
        if err != nil {
3✔
1567
                return nil, err
×
1568
        }
×
1569
        hashCache := txscript.NewTxSigHashes(txn, prevOutputFetcher)
3✔
1570

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

3✔
1591
                return nil
3✔
1592
        }
1593

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

1602
        return txn, nil
3✔
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 {
3✔
1615
        return &RetributionStore{
3✔
1616
                db: db,
3✔
1617
        }
3✔
1618
}
3✔
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 {
3✔
1624
        tapCase := newTaprootBriefcase()
3✔
1625

3✔
1626
        for _, bo := range retInfo.breachedOutputs {
6✔
1627
                switch bo.WitnessType() {
3✔
1628
                // For spending from our commitment output on the remote
1629
                // commitment, we'll need to stash the control block.
1630
                case input.TaprootRemoteCommitSpend:
3✔
1631
                        //nolint:lll
3✔
1632
                        tapCase.CtrlBlocks.CommitSweepCtrlBlock = bo.signDesc.ControlBlock
3✔
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:
3✔
1637
                        //nolint:lll
3✔
1638
                        tapCase.CtrlBlocks.RevokeSweepCtrlBlock = bo.signDesc.ControlBlock
3✔
1639

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

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

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

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

1659
        return tapCase
3✔
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 {
3✔
1666

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

3✔
1670
                switch bo.WitnessType() {
3✔
1671
                // For spending from our commitment output on the remote
1672
                // commitment, we'll apply the control block.
1673
                case input.TaprootRemoteCommitSpend:
3✔
1674
                        //nolint:lll
3✔
1675
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.CommitSweepCtrlBlock
3✔
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:
3✔
1680
                        //nolint:lll
3✔
1681
                        bo.signDesc.ControlBlock = tapCase.CtrlBlocks.RevokeSweepCtrlBlock
3✔
1682

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

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

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

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

1709
        return nil
3✔
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 {
3✔
1715
        return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
6✔
1716
                // If this is our first contract breach, the retributionBucket
3✔
1717
                // won't exist, in which case, we just create a new bucket.
3✔
1718
                retBucket, err := tx.CreateTopLevelBucket(retributionBucket)
3✔
1719
                if err != nil {
3✔
1720
                        return err
×
1721
                }
×
1722
                tapRetBucket, err := tx.CreateTopLevelBucket(
3✔
1723
                        taprootRetributionBucket,
3✔
1724
                )
3✔
1725
                if err != nil {
3✔
1726
                        return err
×
1727
                }
×
1728

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

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

1739
                err = retBucket.Put(outBuf.Bytes(), retBuf.Bytes())
3✔
1740
                if err != nil {
3✔
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 {
3✔
1747
                case len(ret.breachedOutputs) == 0:
×
1748
                        return nil
×
1749

1750
                case !txscript.IsPayToTaproot(
1751
                        ret.breachedOutputs[0].signDesc.Output.PkScript,
1752
                ):
3✔
1753
                        return nil
3✔
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
3✔
1759
                tapRetcase := taprootBriefcaseFromRetInfo(ret)
3✔
1760
                if err := tapRetcase.Encode(&b); err != nil {
3✔
1761
                        return err
×
1762
                }
×
1763

1764
                return tapRetBucket.Put(outBuf.Bytes(), b.Bytes())
3✔
1765
        }, func() {})
3✔
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) {
3✔
1773
        var found bool
3✔
1774
        err := kvdb.View(rs.db, func(tx kvdb.RTx) error {
6✔
1775
                retBucket := tx.ReadBucket(retributionBucket)
3✔
1776
                if retBucket == nil {
6✔
1777
                        return nil
3✔
1778
                }
3✔
1779

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

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

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

1795
        return found, err
3✔
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 {
3✔
1801
        return kvdb.Update(rs.db, func(tx kvdb.RwTx) error {
6✔
1802
                retBucket := tx.ReadWriteBucket(retributionBucket)
3✔
1803
                tapRetBucket, err := tx.CreateTopLevelBucket(
3✔
1804
                        taprootRetributionBucket,
3✔
1805
                )
3✔
1806
                if err != nil {
3✔
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 {
3✔
1815
                        return errors.New("unable to remove retribution " +
×
1816
                                "because the retribution bucket doesn't exist")
×
1817
                }
×
1818

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

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

1832
                return tapRetBucket.Delete(chanBytes)
3✔
1833
        }, func() {})
3✔
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 {
3✔
1840

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

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

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

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

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

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

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

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

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

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

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

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

1915
        return nil
3✔
1916
}
1917

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

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

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

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

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

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

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

1962
        return nil
3✔
1963
}
1964

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

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

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

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

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

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

1993
        return nil
3✔
1994
}
1995

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

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

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

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

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

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

3✔
2026
        return nil
3✔
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