-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathChannelError.fs
More file actions
927 lines (809 loc) · 31.8 KB
/
Copy pathChannelError.fs
File metadata and controls
927 lines (809 loc) · 31.8 KB
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
namespace DotNetLightning.Channel
open DotNetLightning.Utils
open NBitcoinExtensions
open DotNetLightning.Utils.OnionError
open DotNetLightning.Chain
open DotNetLightning.Crypto
open DotNetLightning.Serialization
open DotNetLightning.Serialization.Msgs
open DotNetLightning.Transactions
open NBitcoin
open ResultUtils
open ResultUtils.Portability
type ChannelError =
| CryptoError of CryptoError
| TransactionRelatedErrors of list<TransactionError>
| HTLCAlreadySent of HTLCId
| InvalidPaymentPreimage of
expectedHash: PaymentHash *
actualPreimage: PaymentPreimage
| UnknownHTLCId of HTLCId
| HTLCOriginNotKnown of HTLCId
| InvalidFailureCode of FailureCode
| APIMisuse of string
| WeCannotAffordFee of
localChannelReserve: Money *
requiredFee: Money *
missingAmount: Money
| CanNotSignBeforeRevocation
| ReceivedCommitmentSignedWhenWeHaveNoPendingChanges
| SignatureCountMismatch of expected: int * actual: int
/// protocol violation defined in BOLT 02
| ReceivedShutdownWhenRemoteHasUnsignedOutgoingHTLCs of msg: ShutdownMsg
/// When we create the first commitment txs as fundee,
/// There might be a case that their initial funding amount is too low that it
/// cannot afford fee
| TheyCannotAffordFee of
toRemote: LNMoney *
fee: Money *
channelReserve: Money
// --- case they sent unacceptable msg ---
| InvalidFundingLocked of InvalidFundingLockedError
| InvalidOpenChannel of InvalidOpenChannelError
| InvalidAcceptChannel of InvalidAcceptChannelError
| InvalidUpdateAddHTLC of InvalidUpdateAddHTLCError
| InvalidRevokeAndACK of InvalidRevokeAndACKError
| InvalidUpdateFee of InvalidUpdateFeeError
// ------------------
/// Consumer of the api (usually, that is wallet) failed to give an funding tx
| ReceivedClosingSignedBeforeReceivingShutdown
| ReceivedClosingSignedBeforeSendingShutdown
| ReceivedClosingSignedBeforeSendingOrReceivingShutdown
| FundingTxNotGiven of msg: string
| OnceConfirmedFundingTxHasBecomeUnconfirmed of
height: BlockHeight *
depth: BlockHeightOffset32
| CannotCloseChannel of msg: string
| RemoteProposedFeeOutOfNegotiatedRange of
ourPreviousFee: Money *
theirPreviousFee: Money *
theirNextFee: Money
| ProposalExceedsMaxFee of proposalFee: Money * maxFee: Money
| NoUpdatesToSign
| CannotSignCommitmentBeforeRevocation
| InsufficientConfirmations of
requiredDepth: BlockHeightOffset32 *
currentDepth: BlockHeightOffset32
// ---- invalid command ----
| InvalidOperationAddHTLC of InvalidOperationAddHTLCError
// -------------------------
member this.RecommendedAction =
match this with
| CryptoError _ -> ReportAndCrash
| TransactionRelatedErrors _ -> Close
| HTLCAlreadySent _ -> Ignore
| InvalidPaymentPreimage(_, _) -> Close
| UnknownHTLCId _ -> Close
| HTLCOriginNotKnown _ -> Close
| InvalidFailureCode _ -> Close
| APIMisuse _ -> Ignore
| WeCannotAffordFee _ -> Close
| CanNotSignBeforeRevocation -> Close
| ReceivedCommitmentSignedWhenWeHaveNoPendingChanges -> Close
| ReceivedShutdownWhenRemoteHasUnsignedOutgoingHTLCs _ -> Close
| SignatureCountMismatch(_, _) -> Close
| TheyCannotAffordFee(_, _, _) -> Close
| InvalidFundingLocked _ -> DistrustPeer
| InvalidOpenChannel _ -> DistrustPeer
| InvalidAcceptChannel _ -> DistrustPeer
| InvalidUpdateAddHTLC _ -> Close
| InvalidRevokeAndACK _ -> Close
| InvalidUpdateFee _ -> Close
| ReceivedClosingSignedBeforeReceivingShutdown -> Close
| ReceivedClosingSignedBeforeSendingShutdown -> Close
| ReceivedClosingSignedBeforeSendingOrReceivingShutdown -> Close
| FundingTxNotGiven _ -> Ignore
| OnceConfirmedFundingTxHasBecomeUnconfirmed _ -> Close
| CannotCloseChannel _ -> Ignore
| NoUpdatesToSign -> Ignore
| CannotSignCommitmentBeforeRevocation -> Ignore
| InsufficientConfirmations(_, _) -> Ignore
| InvalidOperationAddHTLC _ -> Ignore
| RemoteProposedFeeOutOfNegotiatedRange(_, _, _) -> Close
| ProposalExceedsMaxFee(_, _) -> Ignore
member this.Message =
match this with
| HTLCAlreadySent htlcId ->
sprintf
"We have already sent a fail/fulfill for htlc id %i"
htlcId.Value
| InvalidPaymentPreimage(e, actual) ->
sprintf
"Invalid HTLC PreImage %A. Hash (%A) does not match the one expected %A"
actual
actual.Hash
e
| InvalidFailureCode errorCode ->
sprintf
"invalid failure code %A"
(errorCode.GetOnionErrorDescription())
| WeCannotAffordFee(channelReserve, fees, missing) ->
sprintf
"Cannot afford fees. Missing Satoshis are: %A . Reserve Satoshis are %A . Fees are %A"
channelReserve
fees
(missing)
| SignatureCountMismatch(expected, actual) ->
sprintf
"Number of signatures went from the remote (%A) does not match the number expected (%A)"
actual
expected
| TheyCannotAffordFee(toRemote, fee, channelReserve) ->
sprintf
"they are funder but cannot afford their fee. to_remote output is: %A; actual fee is %A; channel_reserve_satoshis is: %A"
toRemote
fee
channelReserve
| InvalidFundingLocked invalidFundingLockedError ->
sprintf
"Invalid funding_locked from the peer: %s"
invalidFundingLockedError.Message
| InvalidOpenChannel invalidOpenChannelError ->
sprintf
"Invalid open_channel from the peer.: %s"
invalidOpenChannelError.Message
| OnceConfirmedFundingTxHasBecomeUnconfirmed(height, depth) ->
sprintf
"once confirmed funding tx has become less confirmed than threshold %A! This is probably caused by reorg. current depth is: %A "
height
depth
| ReceivedShutdownWhenRemoteHasUnsignedOutgoingHTLCs msg ->
sprintf
"They sent shutdown msg (%A) while they have pending unsigned HTLCs, this is protocol violation"
msg
| RemoteProposedFeeOutOfNegotiatedRange
(
ourPreviousFee, theirPreviousFee, theirNextFee
) ->
"remote proposed a closing fee which was not strictly between the previous fee that \
we proposed and the previous fee that they proposed. "
+ sprintf
"our previous fee = %A; their previous fee = %A; their next fee = %A"
ourPreviousFee
theirPreviousFee
theirNextFee
| ProposalExceedsMaxFee(proposalFee, maxFee) ->
sprintf
"latest fee proposal (%i) exceeds max fee (%i)"
proposalFee.Satoshi
maxFee.Satoshi
| CryptoError cryptoError ->
sprintf "Crypto error: %s" cryptoError.Message
| TransactionRelatedErrors transactionErrors ->
let getMessage(transactionError: TransactionError) : string =
transactionError.Message
sprintf
"Transaction errors: %s"
(String.concat "; " (Seq.map getMessage transactionErrors))
| UnknownHTLCId htlcId -> sprintf "Unknown HTLC id (%i)" htlcId.Value
| HTLCOriginNotKnown htlcId ->
sprintf "Origin of HTLC %i not known" htlcId.Value
| APIMisuse error -> sprintf "Internal error (API misuse): %s" error
| CanNotSignBeforeRevocation -> "Cannot sign before revocation"
| ReceivedCommitmentSignedWhenWeHaveNoPendingChanges ->
"Received commitment signed when we have not pending changes"
| InvalidAcceptChannel invalidAcceptChannelError ->
sprintf
"Invalid accept_channel msg: %s"
invalidAcceptChannelError.Message
| InvalidUpdateAddHTLC invalidUpdateAddHTLCError ->
sprintf
"Invalid udpate_add_htlc msg: %s"
invalidUpdateAddHTLCError.Message
| InvalidRevokeAndACK invalidRevokeAndACKError ->
sprintf
"Invalid revoke_and_ack msg: %s"
invalidRevokeAndACKError.Message
| InvalidUpdateFee invalidUpdateFeeError ->
sprintf "Invalid update_fee msg: %s" invalidUpdateFeeError.Message
| ReceivedClosingSignedBeforeReceivingShutdown ->
sprintf "received closing_signed before receiving shutdown"
| ReceivedClosingSignedBeforeSendingShutdown ->
sprintf "received closing_signed before sending shutdown"
| ReceivedClosingSignedBeforeSendingOrReceivingShutdown ->
sprintf
"received closing_signed before sending or receiving shutdown"
| FundingTxNotGiven msg -> sprintf "Funding tx not given: %s" msg
| CannotCloseChannel msg -> sprintf "Cannot close channel: %s" msg
| NoUpdatesToSign -> "No updates to sign"
| CannotSignCommitmentBeforeRevocation ->
"Cannot sign commitment before previous commitment is revoked"
| InsufficientConfirmations(requiredConfirmations, currentConfirmations) ->
sprintf
"Insufficient confirmations. %i required, only have %i"
requiredConfirmations.Value
currentConfirmations.Value
| InvalidOperationAddHTLC invalidOperationAddHTLCError ->
sprintf
"Invalid operation (add htlc): %s"
invalidOperationAddHTLCError.Message
and ChannelConsumerAction =
/// The error which should never happen.
/// This implies a bug so we must do something on this Library
/// For the sake of saving funds, the API consumer might attempt a channel close.
/// But they cannot be sure that closing will always succeed.
| ReportAndCrash
/// Close channel immediately. The most popular action.
/// Might be good to lower the trust score of the peer.
| Close
/// Same with the `Close` in the sense that the peer did something unacceptable to us.
/// But the channel is not open yet.
| DistrustPeer
/// The error is not critical to the channel operation.
/// But it maybe good to report the log message, or maybe lower the peer score.
| Ignore
and InvalidFundingLockedError =
{
NetworkMsg: FundingLockedMsg
}
member this.Message =
"remote peer sent a second funding_locked message which does not match their first"
and InvalidOpenChannelError =
{
NetworkMsg: OpenChannelMsg
Errors: list<string>
}
static member Create msg e =
{
NetworkMsg = msg
Errors = e
}
member this.Message = String.concat "; " this.Errors
and InvalidAcceptChannelError =
{
NetworkMsg: AcceptChannelMsg
Errors: list<string>
}
static member Create msg e =
{
NetworkMsg = msg
Errors = e
}
member this.Message = String.concat "; " this.Errors
and InvalidUpdateAddHTLCError =
{
NetworkMsg: UpdateAddHTLCMsg
Errors: list<string>
}
static member Create msg e =
{
NetworkMsg = msg
Errors = e
}
member this.Message = String.concat "; " this.Errors
and InvalidRevokeAndACKError =
{
NetworkMsg: RevokeAndACKMsg
Errors: list<string>
}
static member Create msg e =
{
NetworkMsg = msg
Errors = e
}
member this.Message = String.concat "; " this.Errors
and InvalidUpdateFeeError =
{
NetworkMsg: UpdateFeeMsg
Errors: list<string>
}
static member Create msg e =
{
NetworkMsg = msg
Errors = e
}
member this.Message = String.concat "; " this.Errors
and InvalidOperationAddHTLCError =
{
Operation: OperationAddHTLC
Errors: list<string>
}
static member Create op e =
{
Operation = op
Errors = e
}
member this.Message = String.concat "; " this.Errors
[<AutoOpen>]
module private ValidationHelper =
let check left predicate right msg =
if predicate left right then
sprintf msg left right |> Error
else
Ok()
/// Helpers to create channel error
[<AutoOpen>]
module internal ChannelError =
let inline feeDeltaTooHigh msg (actualDelta, maxAccepted) =
InvalidUpdateFeeError.Create
msg
[
sprintf
"delta is %.2f%% . But it must be lower than %.2f%%"
(actualDelta * 100.0)
(maxAccepted * 100.0)
]
|> InvalidUpdateFee
|> Error
let inline htlcAlreadySent htlcId =
htlcId |> HTLCAlreadySent |> Error
let inline invalidPaymentPreimage(e, a) =
(e, a) |> InvalidPaymentPreimage |> Error
let inline unknownHTLCId x =
x |> UnknownHTLCId |> Error
let inline htlcOriginNotKnown x =
x |> HTLCOriginNotKnown |> Error
let inline invalidFailureCode x =
x |> InvalidFailureCode |> Error
let inline apiMisuse x =
x |> APIMisuse |> Error
let inline cannotAffordFee x =
x |> WeCannotAffordFee |> Error
let inline signatureCountMismatch x =
x |> SignatureCountMismatch |> Error
let inline theyCannotAffordFee x =
x |> TheyCannotAffordFee |> Error
let onceConfirmedFundingTxHasBecomeUnconfirmed(height, depth) =
(height, depth) |> OnceConfirmedFundingTxHasBecomeUnconfirmed |> Error
let expectTransactionError result =
Result.mapError (List.singleton >> TransactionRelatedErrors) result
let expectTransactionErrors result =
Result.mapError (TransactionRelatedErrors) result
let expectFundingTxError msg =
Result.mapError (FundingTxNotGiven) msg
let invalidRevokeAndACK msg e =
InvalidRevokeAndACKError.Create msg ([ e ]) |> InvalidRevokeAndACK
let cannotCloseChannel msg =
msg |> CannotCloseChannel
let receivedShutdownWhenRemoteHasUnsignedOutgoingHTLCs msg =
msg |> ReceivedShutdownWhenRemoteHasUnsignedOutgoingHTLCs |> Error
let checkRemoteProposedFeeWithinNegotiatedRange
(ourPreviousFeeOpt: Option<Money>)
(theirPreviousFeeOpt: Option<Money>)
(theirNextFee: Money)
=
match (ourPreviousFeeOpt, theirPreviousFeeOpt) with
| (Some ourPreviousFee, Some theirPreviousFee) ->
let feeWithinRange =
((theirNextFee < theirPreviousFee)
&& (theirNextFee >= ourPreviousFee))
|| ((theirNextFee <= ourPreviousFee)
&& (theirNextFee > theirPreviousFee))
if feeWithinRange then
Ok()
else
RemoteProposedFeeOutOfNegotiatedRange(
ourPreviousFee,
theirPreviousFee,
theirNextFee
)
|> Error
| _ -> Ok()
module internal OpenChannelMsgValidation =
let checkMaxAcceptedHTLCs(msg: OpenChannelMsg) =
if (msg.MaxAcceptedHTLCs < 1us) || (msg.MaxAcceptedHTLCs > 483us) then
sprintf
"max_accepted_htlcs must be in between %i and %i. But it was %i"
1us
483us
msg.MaxAcceptedHTLCs
|> Error
else
Ok()
let checkFundingSatoshisLessThanMax
(localParams: LocalParams)
(isOurOpenChannelMsg: bool)
(msg: OpenChannelMsg)
=
// If we are validating our own open message we make sure we are forcing support for option_support_large_channel on the other peer
let featureType =
match isOurOpenChannelMsg with
| true -> Some FeaturesSupport.Mandatory
| false -> None
if
msg.FundingSatoshis >= ChannelConstants.MAX_FUNDING_SATOSHIS
&& not
(
localParams.Features.HasFeature(
Feature.OptionSupportLargeChannel,
?featureType = featureType
)
)
then
sprintf
"funding_satoshis must be less than %A. It was %A, consider activating option_support_large_channel feature."
ChannelConstants.MAX_FUNDING_SATOSHIS
msg.FundingSatoshis
|> Error
else
Ok()
let checkChannelReserveSatohisLessThanFundingSatoshis(msg: OpenChannelMsg) =
if (msg.ChannelReserveSatoshis > msg.FundingSatoshis) then
sprintf
"Bogus channel_reserve_satoshis (%A). Must be bigger than funding_satoshis(%A)"
msg.ChannelReserveSatoshis
msg.FundingSatoshis
|> Error
else
Ok()
let checkPushMSatLesserThanFundingValue msg =
let fundingValue = (msg.FundingSatoshis - msg.ChannelReserveSatoshis)
if (msg.PushMSat.ToMoney() > fundingValue) then
sprintf
"push_msat(%A) larger than funding value(%A)"
msg.PushMSat
fundingValue
|> Error
else
Ok()
let checkFundingSatoshisLessThanDustLimitSatoshis(msg: OpenChannelMsg) =
if (msg.DustLimitSatoshis > msg.FundingSatoshis) then
sprintf
"The dust limit (%A) is larger than the funding amount (%A)"
msg.FundingSatoshis
msg.DustLimitSatoshis
|> Error
else
Ok()
let checkRemoteFee
(feeEstimator: IFeeEstimator)
(remoteFeeRatePerKw: FeeRatePerKw)
(maxFeeRateMismatchRatio: float)
=
let localFeeRatePerKw =
feeEstimator.GetEstSatPer1000Weight(ConfirmationTarget.Background)
let diff = remoteFeeRatePerKw.MismatchRatio localFeeRatePerKw
if (diff > maxFeeRateMismatchRatio) then
sprintf
"Peer's feerate (%A) was unacceptably far from the estimated fee rate of %A"
remoteFeeRatePerKw
localFeeRatePerKw
|> Error
else
Ok()
let checkConfigPermits
(config: ChannelHandshakeLimits)
(msg: OpenChannelMsg)
=
let check1 =
check
msg.FundingSatoshis
(<)
config.MinFundingSatoshis
"funding satoshis is less than the user specified limit. received: %A; limit: %A"
let check2 =
check
(msg.HTLCMinimumMsat.ToMoney())
(>)
(config.MinFundingSatoshis)
"htlc minimum msat is higher than the users specified limit. received %A; limit: %A"
let check3 =
check
msg.MaxHTLCValueInFlightMsat
(<)
config.MinMaxHTLCValueInFlightMSat
"max htlc value in light msat is less than the user specified limit. received: %A; limit %A"
let check4 =
check
msg.ChannelReserveSatoshis
(>)
config.MaxChannelReserveSatoshis
"channel reserve satoshis is higher than the user specified limit. received %A; limit: %A"
let check5 =
check
msg.MaxAcceptedHTLCs
(<)
config.MinMaxAcceptedHTLCs
"max accepted htlcs is less than the user specified limit. received: %A; limit: %A"
let check6 =
check
msg.DustLimitSatoshis
(<)
config.MinDustLimitSatoshis
"dust_limit_satoshis is less than the user specified limit. received: %A; limit: %A"
let check7 =
check
msg.DustLimitSatoshis
(>)
config.MaxDustLimitSatoshis
"dust_limit_satoshis is greater than the user specified limit. received: %A; limit: %A"
let check8 =
check
msg.ToSelfDelay
(>)
(config.MaxToSelfDelay)
"They wanted our payments to be delayed by a needlessly long period (%A), configured maximum was (%A)"
Validation.ofResult(check1)
*^> check2
*^> check3
*^> check4
*^> check5
*^> check6
*^> check7
*^> check8
let checkChannelAnnouncementPreferenceAcceptable
(channelHandshakeLimits: ChannelHandshakeLimits)
(announceChannel: bool)
(msg: OpenChannelMsg)
=
let theirAnnounce = msg.ChannelFlags.AnnounceChannel
if (channelHandshakeLimits.ForceChannelAnnouncementPreference)
&& announceChannel <> theirAnnounce then
"Peer tried to open channel but their announcement preference is different from ours"
|> Error
else
Ok()
let checkIsAcceptableByCurrentFeeRate (feeEstimator: IFeeEstimator) msg =
let ourDustLimit =
ChannelConstantHelpers.deriveOurDustLimitSatoshis feeEstimator
let ourChannelReserve =
ChannelConstantHelpers.getOurChannelReserve(msg.FundingSatoshis)
let check left predicate right msg =
if predicate left right then
sprintf msg left right |> Error
else
Ok()
let check1 =
check
ourChannelReserve
(<)
ourDustLimit
"Funder's channel reserve (%A, dictated by the fundee) is less than the fundee's dust limit (%A). \
The funder must use a larger amount to open a channel."
let check2 =
check
msg.ChannelReserveSatoshis
(<)
ourDustLimit
"Fundee's channel reserve (%A, dictated by the funder) is less than the fundee's dust limit (%A). \
The funder must use a larger amount to open the channel, or require a smaller channel reserve."
let check3 =
check
ourChannelReserve
(<)
msg.DustLimitSatoshis
"Funder's channel reserve (%A, dictated by the fundee) is less than the funder's dust limit (%A)."
Validation.ofResult(check1) *^> check2 *^> check3
let checkFunderCanAffordFee (feeRate: FeeRatePerKw) (msg: OpenChannelMsg) =
let fundersAmount =
LNMoney.Satoshis(msg.FundingSatoshis.Satoshi) - msg.PushMSat
let fee = feeRate.CalculateFeeFromWeight COMMITMENT_TX_BASE_WEIGHT
if fundersAmount.ToMoney() < fee then
sprintf
"funding amount (%A) minus push amount (%A) does not cover commitment tx fee (%A)"
msg.FundingSatoshis
msg.PushMSat
fee
|> Error
else
Ok()
module internal AcceptChannelMsgValidation =
let private check left predicate right msg =
if predicate left right then
sprintf msg left right |> Error
else
Ok()
let checkMaxAcceptedHTLCs(msg: AcceptChannelMsg) =
if (msg.MaxAcceptedHTLCs < 1us) || (msg.MaxAcceptedHTLCs > 483us) then
sprintf
"max_accepted_htlcs must be in between %i and %i. But it was %i"
1us
483us
msg.MaxAcceptedHTLCs
|> Error
else
Ok()
let checkDustLimit msg =
if msg.DustLimitSatoshis > Money.Satoshis(21000000L * 100000L) then
sprintf
"Peer never wants payout outputs? dust_limit_satoshis was: %A"
msg.DustLimitSatoshis
|> Error
else
Ok()
let checkChannelReserveSatoshis
(fundingAmount: Money)
(channelReserveAmount: Money)
(dustLimit: Money)
(acceptChannelMsg: AcceptChannelMsg)
=
if acceptChannelMsg.ChannelReserveSatoshis > fundingAmount then
sprintf
"bogus channel_reserve_satoshis %A . Must be larger than funding_satoshis %A"
(acceptChannelMsg.ChannelReserveSatoshis)
fundingAmount
|> Error
else if acceptChannelMsg.DustLimitSatoshis > channelReserveAmount then
sprintf
"Bogus channel_reserve and dust_limit. dust_limit: %A; channel_reserve %A"
acceptChannelMsg.DustLimitSatoshis
channelReserveAmount
|> Error
else if acceptChannelMsg.ChannelReserveSatoshis < dustLimit then
sprintf
"Peer never wants payout outputs? channel_reserve_satoshis are %A; dust_limit_satoshis in our last sent msg is %A"
acceptChannelMsg.ChannelReserveSatoshis
dustLimit
|> Error
else
Ok()
let checkDustLimitIsLargerThanOurChannelReserve
(channelReserveAmount: Money)
(acceptChannelMsg: AcceptChannelMsg)
=
check
acceptChannelMsg.DustLimitSatoshis
(>)
channelReserveAmount
"dust limit (%A) is bigger than our channel reserve (%A)"
let checkMinimumHTLCValueIsAcceptable
(fundingAmount: Money)
(acceptChannelMsg: AcceptChannelMsg)
=
if acceptChannelMsg.HTLCMinimumMSat.ToMoney()
>= (fundingAmount - acceptChannelMsg.ChannelReserveSatoshis) then
sprintf
"Minimum HTLC value is greater than full channel value HTLCMinimum %A satoshi; funding_satoshis %A; channel_reserve: %A"
(acceptChannelMsg.HTLCMinimumMSat.ToMoney())
(fundingAmount)
(acceptChannelMsg.ChannelReserveSatoshis)
|> Error
else
Ok()
let checkConfigPermits
(config: ChannelHandshakeLimits)
(msg: AcceptChannelMsg)
=
let check1 =
check
msg.HTLCMinimumMSat
(>)
config.MaxHTLCMinimumMSat
"HTLC Minimum msat in accept_channel (%A) is higher than the user specified limit (%A)"
let check2 =
check
msg.MaxHTLCValueInFlightMsat
(<)
config.MinMaxHTLCValueInFlightMSat
"max htlc value in flight msat (%A) is less than the user specified limit (%A)"
let check3 =
check
msg.ChannelReserveSatoshis
(>)
config.MaxChannelReserveSatoshis
"max reserve_satoshis (%A) is higher than the user specified limit (%A)"
let check4 =
check
msg.MaxAcceptedHTLCs
(<)
config.MinMaxAcceptedHTLCs
"max accepted htlcs (%A) is less than the user specified limit (%A)"
let check5 =
check
msg.DustLimitSatoshis
(<)
config.MinDustLimitSatoshis
"dust limit satoshis (%A) is less then the user specified limit (%A)"
let check6 =
check
msg.DustLimitSatoshis
(>)
config.MaxDustLimitSatoshis
"dust limit satoshis (%A) is greater then the user specified limit (%A)"
let check7 =
check
(msg.MinimumDepth.Value)
(>)
(config.MaxMinimumDepth.Value |> uint32)
"We consider the minimum depth (%A) to be unreasonably large. Our max minimum depth is (%A)"
let check8 =
check
msg.ToSelfDelay
(>)
(config.MaxToSelfDelay)
"They wanted our payments to be delayed by a needlessly long period (%A), configured maximum was (%A)"
(check1 |> Validation.ofResult)
*^> check2
*^> check3
*^> check4
*^> check5
*^> check6
*^> check7
*^> check8
module UpdateAddHTLCValidation =
let internal checkExpiryIsNotPast (current: BlockHeight) expiry =
check
(expiry)
(<=)
(current)
"AddHTLC's Expiry was %A but it must be larger than current height %A"
let internal checkExpiryIsInAcceptableRange (current: BlockHeight) expiry =
let checkIsToSoon =
check
(expiry)
(<=)
(current + MIN_CLTV_EXPIRY)
"Operation_ADD_HTLC.Expiry was %A but it was too close to current height. Minimum is: %A"
let checkIsToFar =
check
(expiry)
(>=)
(current + MAX_CLTV_EXPIRY)
"Operation_ADD_HTLC.Expiry was %A but it was too far from current height. Maximum is: %A"
Validation.ofResult(checkIsToSoon) *^> checkIsToFar
let internal checkAmountIsLargerThanMinimum (htlcMinimum: LNMoney) amount =
check
(amount)
(<)
(htlcMinimum)
"htlc value (%A) is too small. must be greater or equal to %A"
module internal UpdateAddHTLCValidationWithContext =
let checkLessThanHTLCValueInFlightLimit
(currentSpec: CommitmentSpec)
limit
(add: UpdateAddHTLCMsg)
=
let outgoingValue =
currentSpec.OutgoingHTLCs
|> Map.toSeq
|> Seq.sumBy(fun (_, v) -> v.Amount)
let incomingValue =
currentSpec.IncomingHTLCs
|> Map.toSeq
|> Seq.sumBy(fun (_, v) -> v.Amount)
let htlcValueInFlight = outgoingValue + incomingValue
if (htlcValueInFlight > limit) then
sprintf
"Too much HTLC value is in flight. Current: %A. Limit: %A \n Could not add new one with value: %A"
htlcValueInFlight
limit
add.Amount
|> Error
else
Ok()
let checkLessThanMaxAcceptedHTLC
(currentSpec: CommitmentSpec)
(limit: uint16)
=
let acceptedHTLCs = currentSpec.IncomingHTLCs |> Map.count
check
acceptedHTLCs
(>)
(int limit)
"We have much number of HTLCs (%A). Limit specified by remote is (%A). So not going to relay"
let checkWeHaveSufficientFunds
(staticChannelConfig: StaticChannelConfig)
currentSpec
=
let fees =
if staticChannelConfig.IsFunder then
Transactions.commitTxFee
staticChannelConfig.RemoteParams.DustLimitSatoshis
currentSpec
else
Money.Zero
let missing =
currentSpec.ToRemote.ToMoney()
- staticChannelConfig.RemoteParams.ChannelReserveSatoshis
- fees
if (missing < Money.Zero) then
sprintf
"We don't have sufficient funds to send HTLC. current to_remote amount is: %A. Remote Channel Reserve is: %A. and fee is %A"
(currentSpec.ToRemote.ToMoney())
(staticChannelConfig.RemoteParams.ChannelReserveSatoshis)
(fees)
|> Error
else
Ok()
module internal UpdateFeeValidation =
let checkFeeDiffTooHigh
(msg: UpdateFeeMsg)
(localFeeRatePerKw: FeeRatePerKw)
maxFeeRateMismatchRatio
=
let remoteFeeRatePerKw = msg.FeeRatePerKw
let diff = remoteFeeRatePerKw.MismatchRatio localFeeRatePerKw
if (diff > maxFeeRateMismatchRatio) then
(diff, maxFeeRateMismatchRatio) |> feeDeltaTooHigh msg
else
Ok()