-
Notifications
You must be signed in to change notification settings - Fork 1
/
Transactions.scala
1728 lines (1633 loc) · 55.5 KB
/
Transactions.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package scoin.ln.transactions
import java.nio.ByteOrder
import scala.util.Try
import scodec.bits.ByteVector
import scoin._
import scoin.Crypto.{PrivateKey, PublicKey, ripemd160}
import scoin.Script._
import scoin.SigVersion._
import scoin.ln._
import scoin.ln.transactions.CommitmentOutput._
import scoin.ln.transactions.Scripts._
object Transactions {
sealed trait CommitmentFormat {
def commitWeight: Int
def htlcOutputWeight: Int
def htlcTimeoutWeight: Int
def htlcSuccessWeight: Int
}
/** Commitment format as defined in the v1.0 specification
* (https://github.com/lightningnetwork/lightning-rfc/tree/v1.0).
*/
case object DefaultCommitmentFormat extends CommitmentFormat {
override val commitWeight = 724
override val htlcOutputWeight = 172
override val htlcTimeoutWeight = 663
override val htlcSuccessWeight = 703
}
/** Commitment format that adds anchor outputs to the commitment transaction
* and uses custom sighash flags for HTLC transactions to allow unilateral
* fee bumping (https://github.com/lightningnetwork/lightning-rfc/pull/688).
*/
sealed trait AnchorOutputsCommitmentFormat extends CommitmentFormat {
override val commitWeight = 1124
override val htlcOutputWeight = 172
override val htlcTimeoutWeight = 666
override val htlcSuccessWeight = 706
}
object AnchorOutputsCommitmentFormat {
val anchorAmount = Satoshi(330)
}
/** This commitment format may be unsafe where you're fundee, as it exposes
* you to a fee inflating attack. Don't use this commitment format unless you
* know what you're doing! See
* https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-September/002796.html
* for details.
*/
case object UnsafeLegacyAnchorOutputsCommitmentFormat
extends AnchorOutputsCommitmentFormat
/** This commitment format removes the fees from the pre-signed 2nd-stage htlc
* transactions to fix the fee inflating attack against
* [[UnsafeLegacyAnchorOutputsCommitmentFormat]].
*/
case object ZeroFeeHtlcTxAnchorOutputsCommitmentFormat
extends AnchorOutputsCommitmentFormat
case class OutputInfo(
index: Long,
amount: Satoshi,
publicKeyScript: ByteVector
)
case class InputInfo(
outPoint: OutPoint,
txOut: TxOut,
redeemScript: ByteVector
)
object InputInfo {
def apply(outPoint: OutPoint, txOut: TxOut, redeemScript: Seq[ScriptElt]) =
new InputInfo(outPoint, txOut, Script.write(redeemScript))
}
/** Owner of a given transaction (local/remote). */
sealed trait TxOwner
object TxOwner {
case object Local extends TxOwner
case object Remote extends TxOwner
}
sealed trait TransactionWithInputInfo {
def input: InputInfo
def desc: String
def tx: Transaction
def amountIn: Satoshi = input.txOut.amount
def fee: Satoshi = amountIn - tx.txOut.map(_.amount).sum
def minRelayFee: Satoshi = {
val vsize = (tx.weight() + 3) / 4
Satoshi(FeeratePerKw.MinimumRelayFeeRate * vsize / 1000)
}
/** Sighash flags to use when signing the transaction. */
def sighash(txOwner: TxOwner, commitmentFormat: CommitmentFormat): Int =
SIGHASH_ALL
}
sealed trait ReplaceableTransactionWithInputInfo
extends TransactionWithInputInfo {
/** Block before which the transaction must be confirmed. */
def confirmBefore: BlockHeight
}
case class CommitTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "commit-tx"
}
/** It's important to note that htlc transactions with the default commitment
* format are not actually replaceable: only anchor outputs htlc transactions
* are replaceable. We should have used different types for these different
* kinds of htlc transactions, but we introduced that before implementing the
* replacement strategy. Unfortunately, if we wanted to change that, we would
* have to update the codecs and implement a migration of channel data, which
* isn't trivial, so we chose to temporarily live with that inconsistency
* (and have the transaction replacement logic abort when non-anchor outputs
* htlc transactions are provided). Ideally, we'd like to implement a dynamic
* commitment format upgrade mechanism and depreciate the pre-anchor outputs
* format soon, which will get rid of this inconsistency. The next time we
* introduce a new type of commitment, we should avoid repeating that mistake
* and define separate types right from the start.
*/
sealed trait HtlcTx extends ReplaceableTransactionWithInputInfo {
def htlcId: Long
override def sighash(
txOwner: TxOwner,
commitmentFormat: CommitmentFormat
): Int = commitmentFormat match {
case DefaultCommitmentFormat => SIGHASH_ALL
case _: AnchorOutputsCommitmentFormat =>
txOwner match {
case TxOwner.Local => SIGHASH_ALL
case TxOwner.Remote => SIGHASH_SINGLE | SIGHASH_ANYONECANPAY
}
}
}
case class HtlcSuccessTx(
input: InputInfo,
tx: Transaction,
paymentHash: ByteVector32,
htlcId: Long,
confirmBefore: BlockHeight
) extends HtlcTx { override def desc: String = "htlc-success" }
case class HtlcTimeoutTx(
input: InputInfo,
tx: Transaction,
htlcId: Long,
confirmBefore: BlockHeight
) extends HtlcTx { override def desc: String = "htlc-timeout" }
case class HtlcDelayedTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "htlc-delayed"
}
sealed trait ClaimHtlcTx extends ReplaceableTransactionWithInputInfo {
def htlcId: Long
}
case class LegacyClaimHtlcSuccessTx(
input: InputInfo,
tx: Transaction,
htlcId: Long,
confirmBefore: BlockHeight
) extends ClaimHtlcTx { override def desc: String = "claim-htlc-success" }
case class ClaimHtlcSuccessTx(
input: InputInfo,
tx: Transaction,
paymentHash: ByteVector32,
htlcId: Long,
confirmBefore: BlockHeight
) extends ClaimHtlcTx { override def desc: String = "claim-htlc-success" }
case class ClaimHtlcTimeoutTx(
input: InputInfo,
tx: Transaction,
htlcId: Long,
confirmBefore: BlockHeight
) extends ClaimHtlcTx { override def desc: String = "claim-htlc-timeout" }
sealed trait ClaimAnchorOutputTx extends TransactionWithInputInfo
case class ClaimLocalAnchorOutputTx(
input: InputInfo,
tx: Transaction,
confirmBefore: BlockHeight
) extends ClaimAnchorOutputTx
with ReplaceableTransactionWithInputInfo {
override def desc: String = "local-anchor"
}
case class ClaimRemoteAnchorOutputTx(input: InputInfo, tx: Transaction)
extends ClaimAnchorOutputTx {
override def desc: String = "remote-anchor"
}
sealed trait ClaimRemoteCommitMainOutputTx extends TransactionWithInputInfo
case class ClaimP2WPKHOutputTx(input: InputInfo, tx: Transaction)
extends ClaimRemoteCommitMainOutputTx {
override def desc: String = "remote-main"
}
case class ClaimRemoteDelayedOutputTx(input: InputInfo, tx: Transaction)
extends ClaimRemoteCommitMainOutputTx {
override def desc: String = "remote-main-delayed"
}
case class ClaimLocalDelayedOutputTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "local-main-delayed"
}
case class MainPenaltyTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "main-penalty"
}
case class HtlcPenaltyTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "htlc-penalty"
}
case class ClaimHtlcDelayedOutputPenaltyTx(input: InputInfo, tx: Transaction)
extends TransactionWithInputInfo {
override def desc: String = "htlc-delayed-penalty"
}
case class ClosingTx(
input: InputInfo,
tx: Transaction,
toLocalOutput: Option[OutputInfo]
) extends TransactionWithInputInfo { override def desc: String = "closing" }
sealed trait TxGenerationSkipped
case object OutputNotFound extends TxGenerationSkipped {
override def toString = "output not found (probably trimmed)"
}
case object AmountBelowDustLimit extends TxGenerationSkipped {
override def toString = "amount is below dust limit"
}
// @formatter:on
/** When *local* *current* [[CommitTx]] is published:
* - [[ClaimLocalDelayedOutputTx]] spends to-local output of [[CommitTx]]
* after a delay
* - When using anchor outputs, [[ClaimLocalAnchorOutputTx]] spends
* to-local anchor of [[CommitTx]]
* - [[HtlcSuccessTx]] spends htlc-received outputs of [[CommitTx]] for
* which we have the preimage
* - [[HtlcDelayedTx]] spends [[HtlcSuccessTx]] after a delay
* - [[HtlcTimeoutTx]] spends htlc-sent outputs of [[CommitTx]] after a
* timeout
* - [[HtlcDelayedTx]] spends [[HtlcTimeoutTx]] after a delay
*
* When *remote* *current* [[CommitTx]] is published:
* - When using the default commitment format, [[ClaimP2WPKHOutputTx]]
* spends to-local output of [[CommitTx]]
* - When using anchor outputs, [[ClaimRemoteDelayedOutputTx]] spends
* to-local output of [[CommitTx]]
* - When using anchor outputs, [[ClaimLocalAnchorOutputTx]] spends
* to-local anchor of [[CommitTx]]
* - [[ClaimHtlcSuccessTx]] spends htlc-received outputs of [[CommitTx]]
* for which we have the preimage
* - [[ClaimHtlcTimeoutTx]] spends htlc-sent outputs of [[CommitTx]] after
* a timeout
*
* When *remote* *revoked* [[CommitTx]] is published:
* - When using the default commitment format, [[ClaimP2WPKHOutputTx]]
* spends to-local output of [[CommitTx]]
* - When using anchor outputs, [[ClaimRemoteDelayedOutputTx]] spends
* to-local output of [[CommitTx]]
* - When using anchor outputs, [[ClaimLocalAnchorOutputTx]] spends
* to-local anchor of [[CommitTx]]
* - [[MainPenaltyTx]] spends remote main output using the per-commitment
* secret
* - [[HtlcSuccessTx]] spends htlc-sent outputs of [[CommitTx]] for which
* they have the preimage (published by remote)
* - [[ClaimHtlcDelayedOutputPenaltyTx]] spends [[HtlcSuccessTx]] using
* the revocation secret (published by local)
* - [[HtlcTimeoutTx]] spends htlc-received outputs of [[CommitTx]] after a
* timeout (published by remote)
* - [[ClaimHtlcDelayedOutputPenaltyTx]] spends [[HtlcTimeoutTx]] using
* the revocation secret (published by local)
* - [[HtlcPenaltyTx]] spends competes with [[HtlcSuccessTx]] and
* [[HtlcTimeoutTx]] for the same outputs (published by local)
*/
/** these values are specific to us (not defined in the specification) and
* used to estimate fees
*/
val claimP2WPKHOutputWitnessWeight = 109
val claimP2WPKHOutputWeight = 438
// The smallest transaction that spends an anchor contains 2 inputs (the commit tx output and a wallet input to set the feerate)
// and 1 output (change). If we're using P2WPKH wallet inputs/outputs with 72 bytes signatures, this results in a weight of 717.
// We round it down to 700 to allow for some error margin (e.g. signatures smaller than 72 bytes).
val claimAnchorOutputMinWeight = 700
// The biggest htlc input is an HTLC-success with anchor outputs:
// 143 bytes (accepted_htlc_script) + 327 bytes (success_witness) + 41 bytes (commitment_input) = 511 bytes
// See https://github.com/lightningnetwork/lightning-rfc/blob/master/03-transactions.md#expected-weight-of-htlc-timeout-and-htlc-success-transactions
val htlcInputMaxWeight = 511
val htlcDelayedWeight = 483
val claimHtlcSuccessWeight = 571
val claimHtlcTimeoutWeight = 545
val mainPenaltyWeight = 484
val htlcPenaltyWeight =
578 // based on spending an HTLC-Success output (would be 571 with HTLC-Timeout)
def weight2feeMsat(feeratePerKw: FeeratePerKw, weight: Int): MilliSatoshi =
MilliSatoshi(feeratePerKw.toLong * weight)
def weight2fee(feeratePerKw: FeeratePerKw, weight: Int): Satoshi =
weight2feeMsat(feeratePerKw, weight).truncateToSatoshi
/** @param fee
* tx fee
* @param weight
* tx weight
* @return
* the fee rate (in Satoshi/Kw) for this tx
*/
def fee2rate(fee: Satoshi, weight: Int): FeeratePerKw = FeeratePerKw(
(fee * 1000L) / weight
)
/** Offered HTLCs below this amount will be trimmed. */
def offeredHtlcTrimThreshold(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): Satoshi =
dustLimit + weight2fee(
spec.htlcTxFeerate(commitmentFormat),
commitmentFormat.htlcTimeoutWeight
)
def offeredHtlcTrimThreshold(
dustLimit: Satoshi,
feerate: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Satoshi = {
commitmentFormat match {
case ZeroFeeHtlcTxAnchorOutputsCommitmentFormat => dustLimit
case _ =>
dustLimit + weight2fee(feerate, commitmentFormat.htlcTimeoutWeight)
}
}
def trimOfferedHtlcs(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): Seq[OutgoingHtlc] = {
val threshold = offeredHtlcTrimThreshold(dustLimit, spec, commitmentFormat)
spec.htlcs.collect {
case o: OutgoingHtlc if o.add.amountMsat >= threshold => o
}.toSeq
}
/** Received HTLCs below this amount will be trimmed. */
def receivedHtlcTrimThreshold(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): Satoshi =
dustLimit + weight2fee(
spec.htlcTxFeerate(commitmentFormat),
commitmentFormat.htlcSuccessWeight
)
def receivedHtlcTrimThreshold(
dustLimit: Satoshi,
feerate: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Satoshi = {
commitmentFormat match {
case ZeroFeeHtlcTxAnchorOutputsCommitmentFormat => dustLimit
case _ =>
dustLimit + weight2fee(feerate, commitmentFormat.htlcSuccessWeight)
}
}
def trimReceivedHtlcs(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): Seq[IncomingHtlc] = {
val threshold = receivedHtlcTrimThreshold(dustLimit, spec, commitmentFormat)
spec.htlcs.collect {
case i: IncomingHtlc if i.add.amountMsat >= threshold => i
}.toSeq
}
/** Fee for an un-trimmed HTLC. */
def htlcOutputFee(
feeratePerKw: FeeratePerKw,
commitmentFormat: CommitmentFormat
): MilliSatoshi =
weight2feeMsat(feeratePerKw, commitmentFormat.htlcOutputWeight)
/** Fee paid by the commit tx (depends on which HTLCs will be trimmed). */
def commitTxFeeMsat(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): MilliSatoshi = {
val trimmedOfferedHtlcs =
trimOfferedHtlcs(dustLimit, spec, commitmentFormat)
val trimmedReceivedHtlcs =
trimReceivedHtlcs(dustLimit, spec, commitmentFormat)
val weight =
commitmentFormat.commitWeight + commitmentFormat.htlcOutputWeight * (trimmedOfferedHtlcs.size + trimmedReceivedHtlcs.size)
weight2feeMsat(spec.commitTxFeerate, weight)
}
/** While on-chain amounts are generally computed in Satoshis (since this is
* the smallest on-chain unit), it may be useful in some cases to calculate
* it in MilliSatoshi to avoid rounding issues. If you are adding multiple
* fees together for example, you should always add them in MilliSatoshi and
* then round down to Satoshi.
*/
def commitTxTotalCostMsat(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): MilliSatoshi = {
// The channel initiator pays the on-chain fee by deducing it from its main output.
val txFee = commitTxFeeMsat(dustLimit, spec, commitmentFormat)
// When using anchor outputs, the channel initiator pays for *both* anchors all the time, even if only one anchor is present.
// This is not technically a fee (it doesn't go to miners) but it also has to be deduced from the channel initiator's main output.
val anchorsCost = commitmentFormat match {
case DefaultCommitmentFormat => Satoshi(0)
case _: AnchorOutputsCommitmentFormat =>
AnchorOutputsCommitmentFormat.anchorAmount * 2
}
txFee + anchorsCost
}
def commitTxTotalCost(
dustLimit: Satoshi,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): Satoshi =
commitTxTotalCostMsat(dustLimit, spec, commitmentFormat).truncateToSatoshi
/** @param commitTxNumber
* commit tx number
* @param isInitiator
* true if local node initiated the channel open
* @param localPaymentBasePoint
* local payment base point
* @param remotePaymentBasePoint
* remote payment base point
* @return
* the obscured tx number as defined in BOLT #3 (a 48 bits integer)
*/
def obscuredCommitTxNumber(
commitTxNumber: Long,
isInitiator: Boolean,
localPaymentBasePoint: PublicKey,
remotePaymentBasePoint: PublicKey
): Long = {
// from BOLT 3: SHA256(payment-basepoint from open_channel || payment-basepoint from accept_channel)
val h = if (isInitiator) {
Crypto.sha256(localPaymentBasePoint.value ++ remotePaymentBasePoint.value)
} else {
Crypto.sha256(remotePaymentBasePoint.value ++ localPaymentBasePoint.value)
}
val blind = Protocol.uint64(
(h.takeRight(6).reverse ++ ByteVector.fromValidHex("0000")).toArray,
ByteOrder.LITTLE_ENDIAN
)
commitTxNumber ^ blind
}
/** @param commitTx
* commit tx
* @param isInitiator
* true if local node initiated the channel open
* @param localPaymentBasePoint
* local payment base point
* @param remotePaymentBasePoint
* remote payment base point
* @return
* the actual commit tx number that was blinded and stored in locktime and
* sequence fields
*/
def getCommitTxNumber(
commitTx: Transaction,
isInitiator: Boolean,
localPaymentBasePoint: PublicKey,
remotePaymentBasePoint: PublicKey
): Long = {
require(commitTx.txIn.size == 1, "commitment tx should have 1 input")
val blind = obscuredCommitTxNumber(
0,
isInitiator,
localPaymentBasePoint,
remotePaymentBasePoint
)
val obscured =
decodeTxNumber(commitTx.txIn.head.sequence, commitTx.lockTime)
obscured ^ blind
}
/** This is a trick to split and encode a 48-bit txnumber into the sequence
* and locktime fields of a tx
*
* @param txnumber
* commitment number
* @return
* (sequence, locktime)
*/
def encodeTxNumber(txnumber: Long): (Long, Long) = {
require(
txnumber <= 0xffffffffffffL,
"txnumber must be lesser than 48 bits long"
)
(0x80000000L | (txnumber >> 24), (txnumber & 0xffffffL) | 0x20000000)
}
def decodeTxNumber(sequence: Long, locktime: Long): Long =
((sequence & 0xffffffL) << 24) + (locktime & 0xffffffL)
def getHtlcTxInputSequence(commitmentFormat: CommitmentFormat): Long =
commitmentFormat match {
case DefaultCommitmentFormat =>
0 // htlc txs immediately spend the commit tx
case _: AnchorOutputsCommitmentFormat =>
1 // htlc txs have a 1-block delay to allow CPFP carve-out on anchors
}
/** Represent a link between a commitment spec item (to-local, to-remote,
* anchors, htlc) and the actual output in the commit tx
*
* @param output
* transaction output
* @param redeemScript
* redeem script that matches this output (most of them are p2wsh)
* @param commitmentOutput
* commitment spec item this output is built from
*/
case class CommitmentOutputLink[T <: CommitmentOutput](
output: TxOut,
redeemScript: Seq[ScriptElt],
commitmentOutput: T
)
/** Type alias for a collection of commitment output links */
type CommitmentOutputs = Seq[CommitmentOutputLink[CommitmentOutput]]
object CommitmentOutputLink {
/** We sort HTLC outputs according to BIP69 + CLTV as tie-breaker for
* offered HTLC, we do this only for the outgoing HTLC because we must
* agree with the remote on the order of HTLC-Timeout transactions even for
* identical HTLC outputs. See
* https://github.com/lightningnetwork/lightning-rfc/issues/448#issuecomment-432074187.
*/
def sort(
a: CommitmentOutputLink[CommitmentOutput],
b: CommitmentOutputLink[CommitmentOutput]
): Boolean = (a.commitmentOutput, b.commitmentOutput) match {
case (OutHtlc(OutgoingHtlc(htlcA)), OutHtlc(OutgoingHtlc(htlcB)))
if htlcA.paymentHash == htlcB.paymentHash && htlcA.amountMsat.truncateToSatoshi == htlcB.amountMsat.truncateToSatoshi =>
htlcA.cltvExpiry <= htlcB.cltvExpiry
case _ => LexicographicalOrdering.isLessThan(a.output, b.output)
}
}
def makeCommitTxOutputs(
localIsInitiator: Boolean,
localDustLimit: Satoshi,
localRevocationPubkey: PublicKey,
toLocalDelay: CltvExpiryDelta,
localDelayedPaymentPubkey: PublicKey,
remotePaymentPubkey: PublicKey,
localHtlcPubkey: PublicKey,
remoteHtlcPubkey: PublicKey,
localFundingPubkey: PublicKey,
remoteFundingPubkey: PublicKey,
spec: CommitmentSpec,
commitmentFormat: CommitmentFormat
): CommitmentOutputs = {
val outputs = collection.mutable.ArrayBuffer
.empty[CommitmentOutputLink[CommitmentOutput]]
trimOfferedHtlcs(localDustLimit, spec, commitmentFormat).foreach { htlc =>
val redeemScript = htlcOffered(
localHtlcPubkey,
remoteHtlcPubkey,
localRevocationPubkey,
ripemd160(htlc.add.paymentHash.bytes),
commitmentFormat
)
outputs.append(
CommitmentOutputLink(
TxOut(htlc.add.amountMsat.truncateToSatoshi, pay2wsh(redeemScript)),
redeemScript,
OutHtlc(htlc)
)
)
}
trimReceivedHtlcs(localDustLimit, spec, commitmentFormat).foreach { htlc =>
val redeemScript = htlcReceived(
localHtlcPubkey,
remoteHtlcPubkey,
localRevocationPubkey,
ripemd160(htlc.add.paymentHash.bytes),
htlc.add.cltvExpiry,
commitmentFormat
)
outputs.append(
CommitmentOutputLink(
TxOut(htlc.add.amountMsat.truncateToSatoshi, pay2wsh(redeemScript)),
redeemScript,
InHtlc(htlc)
)
)
}
val hasHtlcs = outputs.nonEmpty
val (toLocalAmount: Satoshi, toRemoteAmount: Satoshi) =
if (localIsInitiator) {
(
spec.toLocal.truncateToSatoshi - commitTxTotalCost(
localDustLimit,
spec,
commitmentFormat
),
spec.toRemote.truncateToSatoshi
)
} else {
(
spec.toLocal.truncateToSatoshi,
spec.toRemote.truncateToSatoshi - commitTxTotalCost(
localDustLimit,
spec,
commitmentFormat
)
)
} // NB: we don't care if values are < 0, they will be trimmed if they are < dust limit anyway
if (toLocalAmount >= localDustLimit) {
outputs.append(
CommitmentOutputLink(
TxOut(
toLocalAmount,
pay2wsh(
toLocalDelayed(
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey
)
)
),
toLocalDelayed(
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey
),
ToLocal
)
)
}
if (toRemoteAmount >= localDustLimit) {
commitmentFormat match {
case DefaultCommitmentFormat =>
outputs.append(
CommitmentOutputLink(
TxOut(toRemoteAmount, pay2wpkh(remotePaymentPubkey)),
pay2pkh(remotePaymentPubkey),
ToRemote
)
)
case _: AnchorOutputsCommitmentFormat =>
outputs.append(
CommitmentOutputLink(
TxOut(
toRemoteAmount,
pay2wsh(toRemoteDelayed(remotePaymentPubkey))
),
toRemoteDelayed(remotePaymentPubkey),
ToRemote
)
)
}
}
commitmentFormat match {
case _: AnchorOutputsCommitmentFormat =>
if (toLocalAmount >= localDustLimit || hasHtlcs) {
outputs.append(
CommitmentOutputLink(
TxOut(
AnchorOutputsCommitmentFormat.anchorAmount,
pay2wsh(anchor(localFundingPubkey))
),
anchor(localFundingPubkey),
ToLocalAnchor
)
)
}
if (toRemoteAmount >= localDustLimit || hasHtlcs) {
outputs.append(
CommitmentOutputLink(
TxOut(
AnchorOutputsCommitmentFormat.anchorAmount,
pay2wsh(anchor(remoteFundingPubkey))
),
anchor(remoteFundingPubkey),
ToRemoteAnchor
)
)
}
case _ =>
}
outputs.sortWith(CommitmentOutputLink.sort).toSeq
}
def makeCommitTx(
commitTxInput: InputInfo,
commitTxNumber: Long,
localPaymentBasePoint: PublicKey,
remotePaymentBasePoint: PublicKey,
localIsInitiator: Boolean,
outputs: CommitmentOutputs
): CommitTx = {
val txNumber = obscuredCommitTxNumber(
commitTxNumber,
localIsInitiator,
localPaymentBasePoint,
remotePaymentBasePoint
)
val (sequence, lockTime) = encodeTxNumber(txNumber)
val tx = Transaction(
version = 2,
txIn = TxIn(
commitTxInput.outPoint,
ByteVector.empty,
sequence = sequence
) :: Nil,
txOut = outputs.map(_.output),
lockTime = lockTime
)
CommitTx(commitTxInput, tx)
}
def makeHtlcTimeoutTx(
commitTx: Transaction,
output: CommitmentOutputLink[OutHtlc],
outputIndex: Int,
localDustLimit: Satoshi,
localRevocationPubkey: PublicKey,
toLocalDelay: CltvExpiryDelta,
localDelayedPaymentPubkey: PublicKey,
feeratePerKw: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Either[TxGenerationSkipped, HtlcTimeoutTx] = {
val fee = weight2fee(feeratePerKw, commitmentFormat.htlcTimeoutWeight)
val redeemScript = output.redeemScript
val htlc = output.commitmentOutput.outgoingHtlc.add
val amount = htlc.amountMsat.truncateToSatoshi - fee
if (amount < localDustLimit) {
Left(AmountBelowDustLimit)
} else {
val input = InputInfo(
OutPoint(commitTx, outputIndex),
commitTx.txOut(outputIndex),
write(redeemScript)
)
val tx = Transaction(
version = 2,
txIn = TxIn(
input.outPoint,
ByteVector.empty,
getHtlcTxInputSequence(commitmentFormat)
) :: Nil,
txOut = TxOut(
amount,
pay2wsh(
toLocalDelayed(
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey
)
)
) :: Nil,
lockTime = htlc.cltvExpiry.toLong
)
Right(
HtlcTimeoutTx(input, tx, htlc.id, BlockHeight(htlc.cltvExpiry.toLong))
)
}
}
def makeHtlcSuccessTx(
commitTx: Transaction,
output: CommitmentOutputLink[InHtlc],
outputIndex: Int,
localDustLimit: Satoshi,
localRevocationPubkey: PublicKey,
toLocalDelay: CltvExpiryDelta,
localDelayedPaymentPubkey: PublicKey,
feeratePerKw: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Either[TxGenerationSkipped, HtlcSuccessTx] = {
val fee = weight2fee(feeratePerKw, commitmentFormat.htlcSuccessWeight)
val redeemScript = output.redeemScript
val htlc = output.commitmentOutput.incomingHtlc.add
val amount = htlc.amountMsat.truncateToSatoshi - fee
if (amount < localDustLimit) {
Left(AmountBelowDustLimit)
} else {
val input = InputInfo(
OutPoint(commitTx, outputIndex),
commitTx.txOut(outputIndex),
write(redeemScript)
)
val tx = Transaction(
version = 2,
txIn = TxIn(
input.outPoint,
ByteVector.empty,
getHtlcTxInputSequence(commitmentFormat)
) :: Nil,
txOut = TxOut(
amount,
pay2wsh(
toLocalDelayed(
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey
)
)
) :: Nil,
lockTime = 0
)
Right(
HtlcSuccessTx(
input,
tx,
htlc.paymentHash,
htlc.id,
BlockHeight(htlc.cltvExpiry.toLong)
)
)
}
}
def makeHtlcTxs(
commitTx: Transaction,
localDustLimit: Satoshi,
localRevocationPubkey: PublicKey,
toLocalDelay: CltvExpiryDelta,
localDelayedPaymentPubkey: PublicKey,
feeratePerKw: FeeratePerKw,
outputs: CommitmentOutputs,
commitmentFormat: CommitmentFormat
): Seq[HtlcTx] = {
val htlcTimeoutTxs = outputs.zipWithIndex
.collect { case (CommitmentOutputLink(o, s, OutHtlc(ou)), outputIndex) =>
val co = CommitmentOutputLink(o, s, OutHtlc(ou))
makeHtlcTimeoutTx(
commitTx,
co,
outputIndex,
localDustLimit,
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey,
feeratePerKw,
commitmentFormat
)
}
.collect { case Right(htlcTimeoutTx) => htlcTimeoutTx }
val htlcSuccessTxs = outputs.zipWithIndex
.collect { case (CommitmentOutputLink(o, s, InHtlc(in)), outputIndex) =>
val co = CommitmentOutputLink(o, s, InHtlc(in))
makeHtlcSuccessTx(
commitTx,
co,
outputIndex,
localDustLimit,
localRevocationPubkey,
toLocalDelay,
localDelayedPaymentPubkey,
feeratePerKw,
commitmentFormat
)
}
.collect { case Right(htlcSuccessTx) => htlcSuccessTx }
htlcTimeoutTxs ++ htlcSuccessTxs
}
def makeClaimHtlcSuccessTx(
commitTx: Transaction,
outputs: CommitmentOutputs,
localDustLimit: Satoshi,
localHtlcPubkey: PublicKey,
remoteHtlcPubkey: PublicKey,
remoteRevocationPubkey: PublicKey,
localFinalScriptPubKey: ByteVector,
htlc: UpdateAddHtlc,
feeratePerKw: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Either[TxGenerationSkipped, ClaimHtlcSuccessTx] = {
val redeemScript = htlcOffered(
remoteHtlcPubkey,
localHtlcPubkey,
remoteRevocationPubkey,
ripemd160(htlc.paymentHash.bytes),
commitmentFormat
)
outputs.zipWithIndex.collectFirst {
case (
CommitmentOutputLink(_, _, OutHtlc(OutgoingHtlc(outgoingHtlc))),
outIndex
) if outgoingHtlc.id == htlc.id =>
outIndex
} match {
case Some(outputIndex) =>
val input = InputInfo(
OutPoint(commitTx, outputIndex),
commitTx.txOut(outputIndex),
write(redeemScript)
)
// unsigned tx
val tx = Transaction(
version = 2,
txIn = TxIn(
input.outPoint,
ByteVector.empty,
getHtlcTxInputSequence(commitmentFormat)
) :: Nil,
txOut = TxOut(Satoshi(0), localFinalScriptPubKey) :: Nil,
lockTime = 0
)
val weight = addSigs(
ClaimHtlcSuccessTx(
input,
tx,
htlc.paymentHash,
htlc.id,
BlockHeight(htlc.cltvExpiry.toLong)
),
PlaceHolderSig,
ByteVector32.Zeroes
).tx.weight()
val fee = weight2fee(feeratePerKw, weight)
val amount = input.txOut.amount - fee
if (amount < localDustLimit) {
Left(AmountBelowDustLimit)
} else {
val tx1 = tx.copy(txOut = tx.txOut.head.copy(amount = amount) :: Nil)
Right(
ClaimHtlcSuccessTx(
input,
tx1,
htlc.paymentHash,
htlc.id,
BlockHeight(htlc.cltvExpiry.toLong)
)
)
}
case None => Left(OutputNotFound)
}
}
def makeClaimHtlcTimeoutTx(
commitTx: Transaction,
outputs: CommitmentOutputs,
localDustLimit: Satoshi,
localHtlcPubkey: PublicKey,
remoteHtlcPubkey: PublicKey,
remoteRevocationPubkey: PublicKey,
localFinalScriptPubKey: ByteVector,
htlc: UpdateAddHtlc,
feeratePerKw: FeeratePerKw,
commitmentFormat: CommitmentFormat
): Either[TxGenerationSkipped, ClaimHtlcTimeoutTx] = {
val redeemScript = htlcReceived(
remoteHtlcPubkey,
localHtlcPubkey,
remoteRevocationPubkey,
ripemd160(htlc.paymentHash.bytes),
htlc.cltvExpiry,
commitmentFormat
)
outputs.zipWithIndex.collectFirst {
case (
CommitmentOutputLink(_, _, InHtlc(IncomingHtlc(incomingHtlc))),
outIndex
) if incomingHtlc.id == htlc.id =>
outIndex
} match {
case Some(outputIndex) =>
val input = InputInfo(
OutPoint(commitTx, outputIndex),
commitTx.txOut(outputIndex),
write(redeemScript)
)
// unsigned tx
val tx = Transaction(
version = 2,
txIn = TxIn(