-
Notifications
You must be signed in to change notification settings - Fork 22
/
Channel.kt
2934 lines (2783 loc) · 186 KB
/
Channel.kt
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 fr.acinq.eclair.channel
import fr.acinq.bitcoin.*
import fr.acinq.eclair.*
import fr.acinq.eclair.blockchain.*
import fr.acinq.eclair.blockchain.fee.FeeratePerKw
import fr.acinq.eclair.blockchain.fee.OnChainFeerates
import fr.acinq.eclair.channel.Channel.ANNOUNCEMENTS_MINCONF
import fr.acinq.eclair.channel.Channel.FUNDING_TIMEOUT_FUNDEE_BLOCK
import fr.acinq.eclair.channel.Channel.MAX_NEGOTIATION_ITERATIONS
import fr.acinq.eclair.channel.Channel.handleSync
import fr.acinq.eclair.channel.Helpers.Closing.extractPreimages
import fr.acinq.eclair.channel.Helpers.Closing.onChainOutgoingHtlcs
import fr.acinq.eclair.channel.Helpers.Closing.overriddenOutgoingHtlcs
import fr.acinq.eclair.channel.Helpers.Closing.timedOutHtlcs
import fr.acinq.eclair.crypto.KeyManager
import fr.acinq.eclair.crypto.ShaChain
import fr.acinq.eclair.io.*
import fr.acinq.eclair.router.Announcements
import fr.acinq.eclair.transactions.CommitmentSpec
import fr.acinq.eclair.transactions.Scripts
import fr.acinq.eclair.transactions.Transactions
import fr.acinq.eclair.transactions.outgoings
import fr.acinq.eclair.utils.*
import fr.acinq.eclair.wire.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
import org.kodein.log.Logger
/*
* Channel is implemented as a finite state machine
* Its main method is (State, Event) -> (State, List<Action>)
*/
/** Channel Events (inputs to be fed to the state machine). */
@Serializable
sealed class ChannelEvent {
@Serializable
data class InitFunder(
@Serializable(with = ByteVector32KSerializer::class) val temporaryChannelId: ByteVector32,
@Serializable(with = SatoshiKSerializer::class) val fundingAmount: Satoshi,
val pushAmount: MilliSatoshi,
val initialFeerate: FeeratePerKw,
val fundingTxFeerate: FeeratePerKw,
val localParams: LocalParams,
val remoteInit: Init,
val channelFlags: Byte,
val channelVersion: ChannelVersion
) : ChannelEvent() {
init {
require(channelVersion.hasStaticRemotekey) { "channel version $channelVersion is invalid (static_remote_key is not set)" }
require(channelVersion.hasAnchorOutputs) { "invalid channel version $channelVersion (anchor_outputs is not set)" }
}
}
data class InitFundee(val temporaryChannelId: ByteVector32, val localParams: LocalParams, val remoteInit: Init) : ChannelEvent()
data class Restore(val state: ChannelState) : ChannelEvent()
object CheckHtlcTimeout : ChannelEvent()
data class MessageReceived(val message: LightningMessage) : ChannelEvent()
data class WatchReceived(val watch: WatchEvent) : ChannelEvent()
data class ExecuteCommand(val command: Command) : ChannelEvent()
data class MakeFundingTxResponse(val fundingTx: Transaction, val fundingTxOutputIndex: Int, val fee: Satoshi) : ChannelEvent()
data class GetFundingTxResponse(val getTxResponse: GetTxWithMetaResponse) : ChannelEvent()
data class GetHtlcInfosResponse(val revokedCommitTxId: ByteVector32, val htlcInfos: List<ChannelAction.Storage.HtlcInfo>) : ChannelEvent()
data class NewBlock(val height: Int, val Header: BlockHeader) : ChannelEvent()
data class SetOnChainFeerates(val feerates: OnChainFeerates) : ChannelEvent()
object Disconnected : ChannelEvent()
data class Connected(val localInit: Init, val remoteInit: Init) : ChannelEvent()
}
/** Channel Actions (outputs produced by the state machine). */
sealed class ChannelAction {
data class ProcessLocalError(val error: Throwable, val trigger: ChannelEvent) : ChannelAction()
sealed class Message : ChannelAction() {
data class Send(val message: LightningMessage) : Message()
data class SendToSelf(val command: Command) : Message()
}
sealed class ChannelId : ChannelAction() {
data class IdAssigned(val remoteNodeId: PublicKey, val temporaryChannelId: ByteVector32, val channelId: ByteVector32) : ChannelId()
data class IdSwitch(val oldChannelId: ByteVector32, val newChannelId: ByteVector32) : ChannelId()
}
sealed class Blockchain : ChannelAction() {
data class MakeFundingTx(val pubkeyScript: ByteVector, val amount: Satoshi, val feerate: FeeratePerKw) : Blockchain()
data class SendWatch(val watch: Watch) : Blockchain()
data class PublishTx(val tx: Transaction) : Blockchain()
data class GetFundingTx(val txid: ByteVector32) : Blockchain()
}
sealed class Storage : ChannelAction() {
data class StoreState(val data: ChannelStateWithCommitments) : Storage()
data class HtlcInfo(val channelId: ByteVector32, val commitmentNumber: Long, val paymentHash: ByteVector32, val cltvExpiry: CltvExpiry)
data class StoreHtlcInfos(val htlcs: List<HtlcInfo>) : Storage()
data class GetHtlcInfos(val revokedCommitTxId: ByteVector32, val commitmentNumber: Long) : Storage()
}
data class ProcessIncomingHtlc(val add: UpdateAddHtlc) : ChannelAction()
/**
* Process the result of executing a given command.
* [[CMD_ADD_HTLC]] has a special treatment: there are two response patterns for this command:
* - either [[ProcessCmdRes.AddFailed]] immediately
* - or [[ProcessCmdRes.AddSettledFail]] / [[ProcessCmdRes.AddSettledFulfill]] (usually a while later)
*/
sealed class ProcessCmdRes : ChannelAction() {
data class NotExecuted(val cmd: Command, val t: ChannelException) : ProcessCmdRes()
data class AddSettledFulfill(val paymentId: UUID, val htlc: UpdateAddHtlc, val result: HtlcResult.Fulfill) : ProcessCmdRes()
data class AddSettledFail(val paymentId: UUID, val htlc: UpdateAddHtlc, val result: HtlcResult.Fail) : ProcessCmdRes()
data class AddFailed(val cmd: CMD_ADD_HTLC, val error: ChannelException, val channelUpdate: ChannelUpdate?) : ProcessCmdRes() {
override fun toString() = "cannot add htlc with paymentId=${cmd.paymentId} reason=${error.message}"
}
}
sealed class HtlcResult {
sealed class Fulfill : HtlcResult() {
abstract val paymentPreimage: ByteVector32
data class OnChainFulfill(override val paymentPreimage: ByteVector32) : Fulfill()
data class RemoteFulfill(val fulfill: UpdateFulfillHtlc) : Fulfill() {
override val paymentPreimage = fulfill.paymentPreimage
}
}
sealed class Fail : HtlcResult() {
data class RemoteFail(val fail: UpdateFailHtlc) : Fail()
data class RemoteFailMalformed(val fail: UpdateFailMalformedHtlc) : Fail()
data class OnChainFail(val cause: ChannelException) : Fail()
data class Disconnected(val channelUpdate: ChannelUpdate) : Fail()
}
}
}
/** Channel static parameters. */
@Serializable
data class StaticParams(val nodeParams: NodeParams, @Serializable(with = PublicKeyKSerializer::class) val remoteNodeId: PublicKey)
/** Channel state. */
@Serializable
sealed class ChannelState {
abstract val staticParams: StaticParams
abstract val currentTip: Pair<Int, BlockHeader>
abstract val currentOnChainFeerates: OnChainFeerates
val currentBlockHeight: Int get() = currentTip.first
val keyManager: KeyManager get() = staticParams.nodeParams.keyManager
val privateKey: PrivateKey get() = staticParams.nodeParams.nodePrivateKey
val logger by eclairLogger()
/**
* @param event input event (for example, a message was received, a command was sent by the GUI/API, etc)
* @return a (new state, list of actions) pair
*/
abstract fun processInternal(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>>
fun process(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>> {
return try {
val (newState, actions) = processInternal(event)
Pair(newState, newState.updateActions(actions))
} catch (t: Throwable) {
handleLocalError(event, t)
}
}
abstract fun handleLocalError(event: ChannelEvent, t: Throwable): Pair<ChannelState, List<ChannelAction>>
internal fun unhandled(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>> {
logger.warning { "unhandled event ${event::class} in state ${this::class}" }
return Pair(this, listOf())
}
/** Update outgoing messages to include an encrypted backup when necessary. */
private fun updateActions(actions: List<ChannelAction>): List<ChannelAction> = when {
this is ChannelStateWithCommitments && this.isZeroReserve -> actions.map {
when {
it is ChannelAction.Message.Send && it.message is FundingSigned -> it.copy(message = it.message.copy(channelData = Helpers.encrypt(privateKey.value, this).toByteVector()))
it is ChannelAction.Message.Send && it.message is CommitSig -> it.copy(message = it.message.copy(channelData = Helpers.encrypt(privateKey.value, this).toByteVector()))
it is ChannelAction.Message.Send && it.message is RevokeAndAck -> it.copy(message = it.message.copy(channelData = Helpers.encrypt(privateKey.value, this).toByteVector()))
it is ChannelAction.Message.Send && it.message is ClosingSigned -> it.copy(message = it.message.copy(channelData = Helpers.encrypt(privateKey.value, this).toByteVector()))
else -> it
}
}
else -> actions
}
internal fun handleCommandError(cmd: Command, error: ChannelException, channelUpdate: ChannelUpdate? = null): Pair<ChannelState, List<ChannelAction>> {
logger.warning(error) { "c:${error.channelId} processing ${cmd::class} in state ${this::class} failed" }
return when (cmd) {
is CMD_ADD_HTLC -> Pair(this, listOf(ChannelAction.ProcessCmdRes.AddFailed(cmd, error, channelUpdate)))
else -> Pair(this, listOf(ChannelAction.ProcessCmdRes.NotExecuted(cmd, error)))
}
}
internal fun handleGetFundingTx(getTxResponse: GetTxWithMetaResponse, waitingSinceBlock: Long, fundingTx_opt: Transaction?): Pair<ChannelState, List<ChannelAction>> = when {
getTxResponse.tx_opt != null -> Pair(this, emptyList()) // the funding tx exists, nothing to do
fundingTx_opt != null -> {
// if we are funder, we never give up
logger.info { "republishing the funding tx..." }
// TODO we should also check if the funding tx has been double-spent
// see eclair-2.13 -> Channel.scala -> checkDoubleSpent(fundingTx)
this to listOf(ChannelAction.Blockchain.PublishTx(fundingTx_opt))
}
(currentTip.first - waitingSinceBlock) > FUNDING_TIMEOUT_FUNDEE_BLOCK -> {
// if we are fundee, we give up after some time
handleFundingTimeout()
}
else -> {
// let's wait a little longer
logger.info { "funding tx still hasn't been published in ${currentTip.first - waitingSinceBlock} blocks, will wait ${(FUNDING_TIMEOUT_FUNDEE_BLOCK - currentTip.first + waitingSinceBlock)} more blocks..." }
Pair(this, emptyList())
}
}
internal fun handleFundingPublishFailed(): Pair<ChannelState, List<ChannelAction.Message.Send>> {
require(this is ChannelStateWithCommitments) { "${this::class} must be of type HasCommitments" }
logger.error { "c:$channelId failed to publish funding tx" }
val exc = ChannelFundingError(channelId)
val error = Error(channelId, exc.message)
// NB: we don't use the handleLocalError handler because it would result in the commit tx being published, which we don't want:
// implementation *guarantees* that in case of BITCOIN_FUNDING_PUBLISH_FAILED, the funding tx hasn't and will never be published, so we can close the channel right away
return Pair(Aborted(staticParams, currentTip, currentOnChainFeerates), listOf(ChannelAction.Message.Send(error)))
}
internal fun handleFundingTimeout(): Pair<ChannelState, List<ChannelAction.Message.Send>> {
require(this is ChannelStateWithCommitments) { "${this::class} must be of type HasCommitments" }
logger.warning { "c:$channelId funding tx hasn't been confirmed in time, cancelling channel delay=$FUNDING_TIMEOUT_FUNDEE_BLOCK blocks" }
val exc = FundingTxTimedout(channelId)
val error = Error(channelId, exc.message)
return Pair(Aborted(staticParams, currentTip, currentOnChainFeerates), listOf(ChannelAction.Message.Send(error)))
}
internal fun doPublish(tx: Transaction, channelId: ByteVector32): List<ChannelAction.Blockchain> = listOf(
ChannelAction.Blockchain.PublishTx(tx),
ChannelAction.Blockchain.SendWatch(WatchConfirmed(channelId, tx, staticParams.nodeParams.minDepthBlocks.toLong(), BITCOIN_TX_CONFIRMED(tx)))
)
fun handleRemoteError(e: Error): Pair<ChannelState, List<ChannelAction>> {
// see BOLT 1: only print out data verbatim if is composed of printable ASCII characters
logger.error { "c:${e.channelId} peer sent error: ascii='${e.toAscii()}' bin=${e.data.toHex()}" }
return when {
this is Closing -> Pair(this, listOf()) // nothing to do, there is already a spending tx published
this is Negotiating && this.bestUnpublishedClosingTx != null -> {
val nexState = Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
mutualClosePublished = listOfNotNull(bestUnpublishedClosingTx)
)
Pair(nexState, buildList {
add(ChannelAction.Storage.StoreState(nexState))
addAll(doPublish(bestUnpublishedClosingTx, nexState.channelId))
})
}
// NB: we publish the commitment even if we have nothing at stake (in a dataloss situation our peer will send us an error just for that)
this is ChannelStateWithCommitments -> this.spendLocalCurrent()
// when there is no commitment yet, we just go to CLOSED state in case an error occurs
else -> Pair(Aborted(staticParams, currentTip, currentOnChainFeerates), listOf())
}
}
}
@Serializable
sealed class ChannelStateWithCommitments : ChannelState() {
abstract val commitments: Commitments
val channelId: ByteVector32 get() = commitments.channelId
val isFunder: Boolean get() = commitments.localParams.isFunder
val isZeroReserve: Boolean get() = commitments.isZeroReserve
abstract fun updateCommitments(input: Commitments): ChannelStateWithCommitments
internal fun handleRemoteSpentCurrent(commitTx: Transaction): Pair<Closing, List<ChannelAction>> {
logger.warning { "c:$channelId they published their current commit in txid=${commitTx.txid}" }
require(commitTx.txid == commitments.remoteCommit.txid) { "txid mismatch" }
val remoteCommitPublished = Helpers.Closing.claimRemoteCommitTxOutputs(keyManager, commitments, commitments.remoteCommit, commitTx, currentOnChainFeerates)
val nextState = when (this) {
is Closing -> this.copy(remoteCommitPublished = remoteCommitPublished)
is Negotiating -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
remoteCommitPublished = remoteCommitPublished
)
is WaitForFundingConfirmed -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = fundingTx,
waitingSinceBlock = currentBlockHeight.toLong(),
remoteCommitPublished = remoteCommitPublished
)
else -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
remoteCommitPublished = remoteCommitPublished
)
}
return Pair(nextState, buildList {
add(ChannelAction.Storage.StoreState(nextState))
addAll(remoteCommitPublished.doPublish(channelId, staticParams.nodeParams.minDepthBlocks.toLong()))
})
}
internal fun handleRemoteSpentNext(commitTx: Transaction): Pair<ChannelState, List<ChannelAction>> {
logger.warning { "c:$channelId they published their next commit in txid=${commitTx.txid}" }
require(commitments.remoteNextCommitInfo.isLeft) { "next remote commit must be defined" }
val remoteCommit = commitments.remoteNextCommitInfo.left?.nextRemoteCommit
require(remoteCommit != null) { "remote commit must not be null" }
require(commitTx.txid == remoteCommit.txid) { "txid mismatch" }
val remoteCommitPublished = Helpers.Closing.claimRemoteCommitTxOutputs(keyManager, commitments, remoteCommit, commitTx, currentOnChainFeerates)
val nextState = when (this) {
is Closing -> copy(nextRemoteCommitPublished = remoteCommitPublished)
is Negotiating -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
nextRemoteCommitPublished = remoteCommitPublished
)
// NB: if there is a next commitment, we can't be in WaitForFundingConfirmed so we don't have the case where fundingTx is defined
else -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
nextRemoteCommitPublished = remoteCommitPublished
)
}
return Pair(nextState, buildList {
add(ChannelAction.Storage.StoreState(nextState))
addAll(remoteCommitPublished.doPublish(channelId, staticParams.nodeParams.minDepthBlocks.toLong()))
})
}
internal fun handleRemoteSpentOther(tx: Transaction): Pair<ChannelState, List<ChannelAction>> {
logger.warning { "c:$channelId funding tx spent in txid=${tx.txid}" }
return Helpers.Closing.claimRevokedRemoteCommitTxOutputs(keyManager, commitments, tx, currentOnChainFeerates)?.let { (revokedCommitPublished, txNumber) ->
logger.warning { "c:$channelId txid=${tx.txid} was a revoked commitment, publishing the penalty tx" }
val ex = FundingTxSpent(channelId, tx)
val error = Error(channelId, ex.message)
val nextState = when (this) {
is Closing -> if (this.revokedCommitPublished.contains(revokedCommitPublished)) {
this
} else {
this.copy(revokedCommitPublished = this.revokedCommitPublished + revokedCommitPublished)
}
is Negotiating -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
revokedCommitPublished = listOf(revokedCommitPublished)
)
// NB: if there is a next commitment, we can't be in WaitForFundingConfirmed so we don't have the case where fundingTx is defined
else -> Closing(
staticParams = staticParams,
currentTip = currentTip,
commitments = commitments,
currentOnChainFeerates = currentOnChainFeerates,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
revokedCommitPublished = listOf(revokedCommitPublished)
)
}
return Pair(nextState, buildList {
add(ChannelAction.Storage.StoreState(nextState))
addAll(revokedCommitPublished.doPublish(channelId, staticParams.nodeParams.minDepthBlocks.toLong()))
add(ChannelAction.Message.Send(error))
add(ChannelAction.Storage.GetHtlcInfos(revokedCommitPublished.commitTx.txid, txNumber))
})
} ?: run {
// the published tx was neither their current commitment nor a revoked one
logger.error { "c:$channelId couldn't identify txid=${tx.txid}, something very bad is going on!!!" }
Pair(ErrorInformationLeak(staticParams, currentTip, currentOnChainFeerates, commitments), listOf())
}
}
internal fun spendLocalCurrent(): Pair<ChannelState, List<ChannelAction>> {
val outdatedCommitment = when (this) {
is WaitForRemotePublishFutureCommitment -> true
is Closing -> this.futureRemoteCommitPublished != null
else -> false
}
return if (outdatedCommitment) {
logger.warning { "c:$channelId we have an outdated commitment: will not publish our local tx" }
Pair(this as ChannelState, listOf())
} else {
val commitTx = commitments.localCommit.publishableTxs.commitTx.tx
val localCommitPublished = Helpers.Closing.claimCurrentLocalCommitTxOutputs(
keyManager,
commitments,
commitTx,
currentOnChainFeerates
)
val nextState = when (this) {
is Closing -> copy(localCommitPublished = localCommitPublished)
is Negotiating -> Closing(
staticParams = staticParams,
currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
localCommitPublished = localCommitPublished
)
is WaitForFundingConfirmed -> Closing(
staticParams = staticParams, currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = fundingTx,
waitingSinceBlock = currentBlockHeight.toLong(),
localCommitPublished = localCommitPublished
)
else -> Closing(
staticParams = staticParams, currentTip = currentTip,
currentOnChainFeerates = currentOnChainFeerates,
commitments = commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
localCommitPublished = localCommitPublished
)
}
Pair(nextState, buildList {
add(ChannelAction.Storage.StoreState(nextState))
addAll(localCommitPublished.doPublish(channelId, staticParams.nodeParams.minDepthBlocks.toLong()))
})
}
}
/**
* Check HTLC timeout in our commitment and our remote's.
* If HTLCs are at risk, we will publish our local commitment and close the channel.
*/
internal fun checkHtlcTimeout(): Pair<ChannelState, List<ChannelAction>> {
val timedOutOutgoing = commitments.timedOutOutgoingHtlcs(currentBlockHeight.toLong())
val almostTimedOutIncoming = commitments.almostTimedOutIncomingHtlcs(currentBlockHeight.toLong(), staticParams.nodeParams.fulfillSafetyBeforeTimeoutBlocks)
val channelEx: ChannelException? = when {
timedOutOutgoing.isNotEmpty() -> HtlcsTimedOutDownstream(channelId, timedOutOutgoing)
almostTimedOutIncoming.isNotEmpty() -> FulfilledHtlcsWillTimeout(channelId, almostTimedOutIncoming)
else -> null
}
return when (channelEx) {
null -> Pair(this, listOf())
else -> {
logger.error { "c:$channelId ${channelEx.message}" }
when {
this is Closing -> Pair(this, listOf()) // nothing to do, there is already a spending tx published
this is Negotiating && this.bestUnpublishedClosingTx != null -> {
val nexState = Closing(
staticParams,
currentTip,
currentOnChainFeerates,
commitments,
fundingTx = null,
waitingSinceBlock = currentBlockHeight.toLong(),
mutualCloseProposed = closingTxProposed.flatten().map { it.unsignedTx },
mutualClosePublished = listOfNotNull(bestUnpublishedClosingTx)
)
Pair(nexState, buildList {
add(ChannelAction.Storage.StoreState(nexState))
addAll(doPublish(bestUnpublishedClosingTx, nexState.channelId))
})
}
else -> {
val error = Error(channelId, channelEx.message)
val (nextState, actions) = spendLocalCurrent()
Pair(nextState, buildList {
addAll(actions)
add(ChannelAction.Message.Send(error))
})
}
}
}
}
}
companion object {
val serializersModule = SerializersModule {
polymorphic(ChannelStateWithCommitments::class) {
subclass(Normal::class)
subclass(WaitForFundingConfirmed::class)
subclass(WaitForFundingLocked::class)
subclass(WaitForRemotePublishFutureCommitment::class)
subclass(ShuttingDown::class)
subclass(Negotiating::class)
subclass(Closing::class)
}
}
private val serializationModules = SerializersModule {
include(Tlv.serializersModule)
include(KeyManager.serializersModule)
include(UpdateMessage.serializersModule)
}
@OptIn(ExperimentalSerializationApi::class)
private val cbor = Cbor {
serializersModule = serializationModules
}
@OptIn(ExperimentalSerializationApi::class)
fun serialize(state: ChannelStateWithCommitments): ByteArray {
return cbor.encodeToByteArray(serializer(), state)
}
@OptIn(ExperimentalSerializationApi::class)
fun deserialize(bin: ByteArray): ChannelStateWithCommitments {
return cbor.decodeFromByteArray(serializer(), bin)
}
@OptIn(ExperimentalSerializationApi::class)
fun deserialize(bin: ByteVector): ChannelStateWithCommitments = deserialize(bin.toByteArray())
}
}
@Serializable
data class WaitForInit(override val staticParams: StaticParams, override val currentTip: Pair<Int, @Serializable(with = BlockHeaderKSerializer::class) BlockHeader>, override val currentOnChainFeerates: OnChainFeerates) : ChannelState() {
override fun processInternal(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>> {
return when {
event is ChannelEvent.InitFundee -> {
val nextState = WaitForOpenChannel(staticParams, currentTip, currentOnChainFeerates, event.temporaryChannelId, event.localParams, event.remoteInit)
Pair(nextState, listOf())
}
event is ChannelEvent.InitFunder -> {
val fundingPubKey = keyManager.fundingPublicKey(event.localParams.fundingKeyPath).publicKey
val channelKeyPath = keyManager.channelKeyPath(event.localParams, event.channelVersion)
val paymentBasepoint = keyManager.paymentPoint(channelKeyPath)
val open = OpenChannel(
staticParams.nodeParams.chainHash,
temporaryChannelId = event.temporaryChannelId,
fundingSatoshis = event.fundingAmount,
pushMsat = event.pushAmount,
dustLimitSatoshis = event.localParams.dustLimit,
maxHtlcValueInFlightMsat = event.localParams.maxHtlcValueInFlightMsat,
channelReserveSatoshis = event.localParams.channelReserve,
htlcMinimumMsat = event.localParams.htlcMinimum,
feeratePerKw = event.initialFeerate,
toSelfDelay = event.localParams.toSelfDelay,
maxAcceptedHtlcs = event.localParams.maxAcceptedHtlcs,
fundingPubkey = fundingPubKey,
revocationBasepoint = keyManager.revocationPoint(channelKeyPath).publicKey,
paymentBasepoint = paymentBasepoint.publicKey,
delayedPaymentBasepoint = keyManager.delayedPaymentPoint(channelKeyPath).publicKey,
htlcBasepoint = keyManager.htlcPoint(channelKeyPath).publicKey,
firstPerCommitmentPoint = keyManager.commitmentPoint(channelKeyPath, 0),
channelFlags = event.channelFlags,
// In order to allow TLV extensions and keep backwards-compatibility, we include an empty upfront_shutdown_script.
// See https://github.com/lightningnetwork/lightning-rfc/pull/714.
tlvStream = TlvStream(
if (event.channelVersion.isSet(ChannelVersion.ZERO_RESERVE_BIT)) {
listOf(ChannelTlv.UpfrontShutdownScript(ByteVector.empty), ChannelTlv.ChannelVersionTlv(event.channelVersion))
} else {
listOf(ChannelTlv.UpfrontShutdownScript(ByteVector.empty))
}
)
)
val nextState = WaitForAcceptChannel(staticParams, currentTip, currentOnChainFeerates, event, open)
Pair(nextState, listOf(ChannelAction.Message.Send(open)))
}
event is ChannelEvent.Restore && event.state is Closing && event.state.commitments.nothingAtStake() -> {
logger.info { "c:${event.state.channelId} we have nothing at stake, going straight to CLOSED" }
Pair(Closed(event.state), listOf())
}
event is ChannelEvent.Restore && event.state is Closing -> {
val closingType = event.state.closingTypeAlreadyKnown()
logger.info { "c:${event.state.channelId} channel is closing (closing type = ${closingType?.let { it::class } ?: "unknown yet"}" }
// if the closing type is known:
// - there is no need to watch the funding tx because it has already been spent and the spending tx has
// already reached mindepth
// - there is no need to attempt to publish transactions for other type of closes
when (closingType) {
is MutualClose -> {
Pair(event.state, doPublish(closingType.tx, event.state.channelId))
}
is LocalClose -> {
val actions = closingType.localCommitPublished.doPublish(event.state.channelId, event.state.staticParams.nodeParams.minDepthBlocks.toLong())
Pair(event.state, actions)
}
is RemoteClose -> {
val actions = closingType.remoteCommitPublished.doPublish(event.state.channelId, event.state.staticParams.nodeParams.minDepthBlocks.toLong())
Pair(event.state, actions)
}
is RevokedClose -> {
val actions = closingType.revokedCommitPublished.doPublish(event.state.channelId, event.state.staticParams.nodeParams.minDepthBlocks.toLong())
Pair(event.state, actions)
}
is RecoveryClose -> {
val actions = closingType.remoteCommitPublished.doPublish(event.state.channelId, event.state.staticParams.nodeParams.minDepthBlocks.toLong())
Pair(event.state, actions)
}
null -> {
// in all other cases we need to be ready for any type of closing
val commitments = event.state.commitments
val actions = mutableListOf<ChannelAction>(
ChannelAction.Blockchain.SendWatch(
WatchSpent(
event.state.channelId,
commitments.commitInput.outPoint.txid,
commitments.commitInput.outPoint.index.toInt(),
commitments.commitInput.txOut.publicKeyScript,
BITCOIN_FUNDING_SPENT
)
),
//SendWatch(WatchLost(event.state.channelId, commitments.commitInput.outPoint.txid, event.state.staticParams.nodeParams.minDepthBlocks.toLong(), BITCOIN_FUNDING_LOST))
)
val minDepth = event.state.staticParams.nodeParams.minDepthBlocks.toLong()
event.state.mutualClosePublished.forEach { actions.addAll(doPublish(it, event.state.channelId)) }
event.state.localCommitPublished?.run { actions.addAll(doPublish(event.state.channelId, minDepth)) }
event.state.remoteCommitPublished?.run { actions.addAll(doPublish(event.state.channelId, minDepth)) }
event.state.nextRemoteCommitPublished?.run { actions.addAll(doPublish(event.state.channelId, minDepth)) }
event.state.revokedCommitPublished.forEach { actions.addAll(it.doPublish(event.state.channelId, minDepth)) }
event.state.futureRemoteCommitPublished?.run { actions.addAll(doPublish(event.state.channelId, minDepth)) }
// if commitment number is zero, we also need to make sure that the funding tx has been published
if (commitments.localCommit.index == 0L && commitments.remoteCommit.index == 0L) {
actions.add(ChannelAction.Blockchain.GetFundingTx(commitments.commitInput.outPoint.txid))
}
Pair(event.state, actions)
}
}
}
event is ChannelEvent.Restore && event.state is ChannelStateWithCommitments -> {
logger.info { "c:${event.state.channelId} restoring channel" }
val watchSpent = WatchSpent(
event.state.channelId,
event.state.commitments.commitInput.outPoint.txid,
event.state.commitments.commitInput.outPoint.index.toInt(),
event.state.commitments.commitInput.txOut.publicKeyScript,
BITCOIN_FUNDING_SPENT
)
val watchConfirmed = WatchConfirmed(
event.state.channelId,
event.state.commitments.commitInput.outPoint.txid,
event.state.commitments.commitInput.txOut.publicKeyScript,
staticParams.nodeParams.minDepthBlocks.toLong(),
BITCOIN_FUNDING_DEPTHOK
)
val actions = listOf(
ChannelAction.Blockchain.SendWatch(watchSpent),
ChannelAction.Blockchain.SendWatch(watchConfirmed),
ChannelAction.Blockchain.GetFundingTx(event.state.commitments.commitInput.outPoint.txid)
)
Pair(Offline(event.state), actions)
}
event is ChannelEvent.NewBlock -> Pair(this.copy(currentTip = Pair(event.height, event.Header)), listOf())
event is ChannelEvent.SetOnChainFeerates -> Pair(this.copy(currentOnChainFeerates = event.feerates), listOf())
event is ChannelEvent.ExecuteCommand && event.command is CloseCommand -> Pair(Aborted(staticParams, currentTip, currentOnChainFeerates), listOf())
else -> unhandled(event)
}
}
override fun handleLocalError(event: ChannelEvent, t: Throwable): Pair<ChannelState, List<ChannelAction>> {
logger.error(t) { "error on event ${event::class} in state ${this::class}" }
return Pair(this, listOf(ChannelAction.ProcessLocalError(t, event)))
}
}
@Serializable
data class Offline(val state: ChannelStateWithCommitments) : ChannelStateWithCommitments() {
override val staticParams: StaticParams get() = state.staticParams
override val currentTip: Pair<Int, BlockHeader> get() = state.currentTip
override val currentOnChainFeerates: OnChainFeerates get() = state.currentOnChainFeerates
override val commitments: Commitments get() = state.commitments
override fun updateCommitments(input: Commitments): ChannelStateWithCommitments {
return Offline(state.updateCommitments(input))
}
override fun processInternal(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>> {
logger.warning { "c:${state.channelId} offline processing ${event::class}" }
return when {
event is ChannelEvent.Connected -> {
when {
state is WaitForRemotePublishFutureCommitment -> {
// they already proved that we have an outdated commitment
// there isn't much to do except asking them again to publish their current commitment by sending an error
val exc = PleasePublishYourCommitment(state.channelId)
val error = Error(state.channelId, exc.message)
val nextState = state.updateCommitments(state.commitments.updateFeatures(event.localInit, event.remoteInit))
Pair(nextState, listOf(ChannelAction.Message.Send(error)))
}
state.isZeroReserve -> {
logger.info { "c:${state.channelId} syncing ${state::class}, waiting fo their channelReestablish message" }
val nextState = state.updateCommitments(state.commitments.updateFeatures(event.localInit, event.remoteInit))
Pair(Syncing(nextState, true), listOf())
}
else -> {
val yourLastPerCommitmentSecret = state.commitments.remotePerCommitmentSecrets.lastIndex?.let { state.commitments.remotePerCommitmentSecrets.getHash(it) } ?: ByteVector32.Zeroes
val channelKeyPath = keyManager.channelKeyPath(state.commitments.localParams, state.commitments.channelVersion)
val myCurrentPerCommitmentPoint = keyManager.commitmentPoint(channelKeyPath, state.commitments.localCommit.index)
val channelReestablish = ChannelReestablish(
channelId = state.channelId,
nextLocalCommitmentNumber = state.commitments.localCommit.index + 1,
nextRemoteRevocationNumber = state.commitments.remoteCommit.index,
yourLastCommitmentSecret = PrivateKey(yourLastPerCommitmentSecret),
myCurrentPerCommitmentPoint = myCurrentPerCommitmentPoint,
state.commitments.remoteChannelData
)
logger.info { "c:${state.channelId} syncing ${state::class}" }
val nextState = state.updateCommitments(state.commitments.updateFeatures(event.localInit, event.remoteInit))
Pair(Syncing(nextState, false), listOf(ChannelAction.Message.Send(channelReestablish)))
}
}
}
event is ChannelEvent.WatchReceived -> {
val watch = event.watch
when {
watch is WatchEventSpent -> when {
state is Negotiating && state.closingTxProposed.flatten().map { it.unsignedTx.txid }.contains(watch.tx.txid) -> {
logger.info { "c:${state.channelId} closing tx published: closingTxId=${watch.tx.txid}" }
val nextState = Closing(
staticParams,
currentTip,
currentOnChainFeerates,
state.commitments,
null,
currentTimestampMillis(),
state.closingTxProposed.flatten().map { it.unsignedTx },
listOf(watch.tx)
)
val actions = listOf(
ChannelAction.Storage.StoreState(nextState),
ChannelAction.Blockchain.PublishTx(watch.tx),
ChannelAction.Blockchain.SendWatch(WatchConfirmed(state.channelId, watch.tx, staticParams.nodeParams.minDepthBlocks.toLong(), BITCOIN_TX_CONFIRMED(watch.tx)))
)
Pair(nextState, actions)
}
watch.tx.txid == state.commitments.remoteCommit.txid -> state.handleRemoteSpentCurrent(watch.tx)
watch.tx.txid == state.commitments.remoteNextCommitInfo.left?.nextRemoteCommit?.txid -> state.handleRemoteSpentNext(watch.tx)
state is WaitForRemotePublishFutureCommitment -> state.handleRemoteSpentFuture(watch.tx)
else -> state.handleRemoteSpentOther(watch.tx)
}
watch is WatchEventConfirmed && (watch.event is BITCOIN_FUNDING_DEPTHOK || watch.event is BITCOIN_FUNDING_DEEPLYBURIED) -> {
// just ignore this, we will put a new watch when we reconnect, and we'll be notified again
Pair(this, listOf())
}
else -> unhandled(event)
}
}
event is ChannelEvent.GetFundingTxResponse && state is WaitForFundingConfirmed && event.getTxResponse.txid == commitments.commitInput.outPoint.txid -> handleGetFundingTx(
event.getTxResponse,
state.waitingSinceBlock,
state.fundingTx
)
event is ChannelEvent.CheckHtlcTimeout -> {
val (newState, actions) = state.checkHtlcTimeout()
when (newState) {
is Closing -> Pair(newState, actions)
is Closed -> Pair(newState, actions)
else -> Pair(Offline(newState as ChannelStateWithCommitments), actions)
}
}
event is ChannelEvent.NewBlock -> {
val (newState, actions) = state.process(event)
when (newState) {
is Closing -> Pair(newState, actions)
is Closed -> Pair(newState, actions)
else -> Pair(Offline(newState as ChannelStateWithCommitments), actions)
}
}
else -> unhandled(event)
}
}
override fun handleLocalError(event: ChannelEvent, t: Throwable): Pair<ChannelState, List<ChannelAction>> {
logger.error(t) { "c:${state.channelId} error on event ${event::class} in state ${this::class}" }
return Pair(this, listOf(ChannelAction.ProcessLocalError(t, event)))
}
}
/**
* waitForTheirReestablishMessage == true means that we want to wait until we've received their channel_reestablish message before
* we send ours (for example, to extract encrypted backup data from extra fields)
* waitForTheirReestablishMessage == false means that we've already sent our channel_reestablish message
*/
@Serializable
data class Syncing(val state: ChannelStateWithCommitments, val waitForTheirReestablishMessage: Boolean) : ChannelStateWithCommitments() {
override val staticParams: StaticParams get() = state.staticParams
override val currentTip: Pair<Int, BlockHeader> get() = state.currentTip
override val currentOnChainFeerates: OnChainFeerates get() = state.currentOnChainFeerates
override val commitments: Commitments get() = state.commitments
override fun updateCommitments(input: Commitments): ChannelStateWithCommitments {
return Syncing(state.updateCommitments(input), waitForTheirReestablishMessage)
}
override fun processInternal(event: ChannelEvent): Pair<ChannelState, List<ChannelAction>> {
logger.warning { "c:${state.channelId} syncing processing ${event::class}" }
return when {
event is ChannelEvent.MessageReceived && event.message is ChannelReestablish ->
when {
waitForTheirReestablishMessage -> {
val nextState = if (!event.message.channelData.isEmpty()) {
logger.info { "c:${state.channelId} channel_reestablish includes a peer backup" }
when (val decrypted = runTrying { Helpers.decrypt(state.staticParams.nodeParams.nodePrivateKey, event.message.channelData) }) {
is Try.Success -> {
if (decrypted.get().commitments.isMoreRecent(state.commitments)) {
logger.warning { "c:${state.channelId} they have a more recent commitment, using it instead" }
decrypted.get()
} else {
logger.info { "c:${state.channelId} ignoring their older backup" }
state
}
}
is Try.Failure -> {
logger.error(decrypted.error) { "c:${state.channelId} ignoring unreadable channel data" }
state
}
}
} else state
val yourLastPerCommitmentSecret = nextState.commitments.remotePerCommitmentSecrets.lastIndex?.let { nextState.commitments.remotePerCommitmentSecrets.getHash(it) } ?: ByteVector32.Zeroes
val channelKeyPath = keyManager.channelKeyPath(state.commitments.localParams, nextState.commitments.channelVersion)
val myCurrentPerCommitmentPoint = keyManager.commitmentPoint(channelKeyPath, nextState.commitments.localCommit.index)
val channelReestablish = ChannelReestablish(
channelId = nextState.channelId,
nextLocalCommitmentNumber = nextState.commitments.localCommit.index + 1,
nextRemoteRevocationNumber = nextState.commitments.remoteCommit.index,
yourLastCommitmentSecret = PrivateKey(yourLastPerCommitmentSecret),
myCurrentPerCommitmentPoint = myCurrentPerCommitmentPoint,
nextState.commitments.remoteChannelData
)
val actions = listOf<ChannelAction>(ChannelAction.Message.Send(channelReestablish))
// now apply their reestablish message to the restored state
val (nextState1, actions1) = Syncing(nextState, waitForTheirReestablishMessage = false).processInternal(event)
Pair(nextState1, actions + actions1)
}
state is WaitForFundingConfirmed -> {
val minDepth = if (state.commitments.localParams.isFunder) {
staticParams.nodeParams.minDepthBlocks
} else {
// when we're fundee we scale the min_depth confirmations depending on the funding amount
if (commitments.isZeroReserve) 0 else Helpers.minDepthForFunding(staticParams.nodeParams, state.commitments.commitInput.txOut.amount)
}
// we put back the watch (operation is idempotent) because the event may have been fired while we were in OFFLINE
val watchConfirmed = WatchConfirmed(
state.channelId,
state.commitments.commitInput.outPoint.txid,
state.commitments.commitInput.txOut.publicKeyScript,
minDepth.toLong(),
BITCOIN_FUNDING_DEPTHOK
)
val actions = listOf(ChannelAction.Blockchain.SendWatch(watchConfirmed))
Pair(state, actions)
}
state is WaitForFundingLocked -> {
logger.debug { "c:${state.channelId} re-sending fundingLocked" }
val channelKeyPath = keyManager.channelKeyPath(state.commitments.localParams, state.commitments.channelVersion)
val nextPerCommitmentPoint = keyManager.commitmentPoint(channelKeyPath, 1)
val fundingLocked = FundingLocked(state.commitments.channelId, nextPerCommitmentPoint)
val actions = listOf(ChannelAction.Message.Send(fundingLocked))
Pair(state, actions)
}
state is Normal -> {
val channelKeyPath = keyManager.channelKeyPath(state.commitments.localParams, state.commitments.channelVersion)
when {
!Helpers.checkLocalCommit(state.commitments, event.message.nextRemoteRevocationNumber) -> {
// if next_remote_revocation_number is greater than our local commitment index, it means that either we are using an outdated commitment, or they are lying
// but first we need to make sure that the last per_commitment_secret that they claim to have received from us is correct for that next_remote_revocation_number minus 1
if (keyManager.commitmentSecret(channelKeyPath, event.message.nextRemoteRevocationNumber - 1) == event.message.yourLastCommitmentSecret) {
logger.warning { "c:${state.channelId} counterparty proved that we have an outdated (revoked) local commitment!!! ourCommitmentNumber=${state.commitments.localCommit.index} theirCommitmentNumber=${event.message.nextRemoteRevocationNumber}" }
// their data checks out, we indeed seem to be using an old revoked commitment, and must absolutely *NOT* publish it, because that would be a cheating attempt and they
// would punish us by taking all the funds in the channel
val exc = PleasePublishYourCommitment(state.channelId)
val error = Error(state.channelId, exc.message.encodeToByteArray().toByteVector())
val nextState = WaitForRemotePublishFutureCommitment(staticParams, state.currentTip, state.currentOnChainFeerates, state.commitments, event.message)
val actions = listOf(
ChannelAction.Storage.StoreState(nextState),
ChannelAction.Message.Send(error)
)
Pair(nextState, actions)
} else {
logger.warning { "c:${state.channelId} they lied! the last per_commitment_secret they claimed to have received from us is invalid" }
val exc = InvalidRevokedCommitProof(state.channelId, state.commitments.localCommit.index, event.message.nextRemoteRevocationNumber, event.message.yourLastCommitmentSecret)
val error = Error(state.channelId, exc.message.encodeToByteArray().toByteVector())
val (nextState, spendActions) = state.spendLocalCurrent()
val actions = buildList {
addAll(spendActions)
add(ChannelAction.Message.Send(error))
}
Pair(nextState, actions)
}
}
!Helpers.checkRemoteCommit(state.commitments, event.message.nextLocalCommitmentNumber) -> {
// if next_local_commit_number is more than one more our remote commitment index, it means that either we are using an outdated commitment, or they are lying
logger.warning { "c:${state.channelId} counterparty says that they have a more recent commitment than the one we know of!!! ourCommitmentNumber=${state.commitments.remoteNextCommitInfo.left?.nextRemoteCommit?.index ?: state.commitments.remoteCommit.index} theirCommitmentNumber=${event.message.nextLocalCommitmentNumber}" }
// there is no way to make sure that they are saying the truth, the best thing to do is ask them to publish their commitment right now
// maybe they will publish their commitment, in that case we need to remember their commitment point in order to be able to claim our outputs
// not that if they don't comply, we could publish our own commitment (it is not stale, otherwise we would be in the case above)
val exc = PleasePublishYourCommitment(state.channelId)
val error = Error(state.channelId, exc.message.encodeToByteArray().toByteVector())
val nextState = WaitForRemotePublishFutureCommitment(staticParams, state.currentTip, state.currentOnChainFeerates, state.commitments, event.message)
val actions = listOf(
ChannelAction.Storage.StoreState(nextState),
ChannelAction.Message.Send(error)
)
Pair(nextState, actions)
}
else -> {
// normal case, our data is up-to-date
val actions = ArrayList<ChannelAction>()
if (event.message.nextLocalCommitmentNumber == 1L && state.commitments.localCommit.index == 0L) {
// If next_local_commitment_number is 1 in both the channel_reestablish it sent and received, then the node MUST retransmit funding_locked, otherwise it MUST NOT
logger.debug { "c:${state.channelId} re-sending fundingLocked" }
val nextPerCommitmentPoint = keyManager.commitmentPoint(channelKeyPath, 1)
val fundingLocked = FundingLocked(state.commitments.channelId, nextPerCommitmentPoint)
actions.add(ChannelAction.Message.Send(fundingLocked))
}
val (commitments1, sendQueue1) = handleSync(event.message, state, keyManager, logger)
actions.addAll(sendQueue1)
// BOLT 2: A node if it has sent a previous shutdown MUST retransmit shutdown.
state.localShutdown?.let {
logger.debug { "c:${state.channelId} re-sending local shutdown" }
actions.add(ChannelAction.Message.Send(it))
}
if (!state.buried) {
// even if we were just disconnected/reconnected, we need to put back the watch because the event may have been
// fired while we were in OFFLINE (if not, the operation is idempotent anyway)
val watchConfirmed = WatchConfirmed(
state.channelId,
state.commitments.commitInput.outPoint.txid,
state.commitments.commitInput.txOut.publicKeyScript,
ANNOUNCEMENTS_MINCONF.toLong(),
BITCOIN_FUNDING_DEEPLYBURIED
)
actions.add(ChannelAction.Blockchain.SendWatch(watchConfirmed))
}
logger.info { "c:${state.channelId} switching to ${state::class}" }
Pair(state.copy(commitments = commitments1), actions)
}
}
}
// BOLT 2: A node if it has sent a previous shutdown MUST retransmit shutdown.
// negotiation restarts from the beginning, and is initialized by the funder
// note: in any case we still need to keep all previously sent closing_signed, because they may publish one of them
state is Negotiating && state.commitments.localParams.isFunder -> {
// we could use the last closing_signed we sent, but network fees may have changed while we were offline so it is better to restart from scratch
val (closingTx, closingSigned) = Helpers.Closing.makeFirstClosingTx(
keyManager,
state.commitments,
state.localShutdown.scriptPubKey.toByteArray(),
state.remoteShutdown.scriptPubKey.toByteArray(),
currentOnChainFeerates.mutualCloseFeerate
)
val closingTxProposed1 = state.closingTxProposed + listOf(listOf(ClosingTxProposed(closingTx.tx, closingSigned)))
val nextState = state.copy(closingTxProposed = closingTxProposed1)
val actions = listOf(
ChannelAction.Storage.StoreState(nextState),
ChannelAction.Message.Send(state.localShutdown),
ChannelAction.Message.Send(closingSigned)
)
return Pair(nextState, actions)
}
state is Negotiating -> {
// we start a new round of negotiation
val closingTxProposed1 = if (state.closingTxProposed.last().isEmpty()) state.closingTxProposed else state.closingTxProposed + listOf(listOf())
val nextState = state.copy(closingTxProposed = closingTxProposed1)