forked from nervosnetwork/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.rs
5691 lines (5180 loc) · 225 KB
/
channel.rs
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
use bitflags::bitflags;
use ckb_jsonrpc_types::BlockNumber;
use secp256k1::XOnlyPublicKey;
use tracing::{debug, error, info, trace, warn};
use crate::{
fiber::{network::get_chain_hash, types::ChannelUpdate},
invoice::InvoiceStore,
};
use ckb_hash::{blake2b_256, new_blake2b};
use ckb_sdk::Since;
use ckb_types::{
core::{FeeRate, TransactionBuilder, TransactionView},
packed::{Bytes, CellInput, CellOutput, OutPoint, Script, Transaction},
prelude::{AsTransactionBuilder, IntoTransactionView, Pack, Unpack},
};
use molecule::prelude::{Builder, Entity};
use musig2::{
aggregate_partial_signatures,
errors::{SigningError, VerifyError},
secp::Point,
sign_partial, verify_partial, AggNonce, CompactSignature, KeyAggContext, PartialSignature,
PubNonce, SecNonce,
};
use ractor::{
async_trait as rasync_trait, call, Actor, ActorProcessingErr, ActorRef, OutputPort,
RpcReplyPort, SpawnErr,
};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use tentacle::secio::PeerId;
use thiserror::Error;
use tokio::sync::oneshot;
use std::{
borrow::Borrow,
collections::BTreeMap,
fmt::Debug,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{
ckb::{
contracts::{get_cell_deps, get_script_by_contract, Contract},
FundingRequest,
},
fiber::{
config::{DEFAULT_UDT_MINIMAL_CKB_AMOUNT, MIN_OCCUPIED_CAPACITY},
fee::{calculate_commitment_tx_fee, shutdown_tx_size},
network::{emit_service_event, sign_network_message},
types::{AnnouncementSignatures, Shutdown},
},
NetworkServiceEvent,
};
use super::{
config::{DEFAULT_CHANNEL_MINIMAL_CKB_AMOUNT, MIN_UDT_OCCUPIED_CAPACITY},
fee::{calculate_shutdown_tx_fee, default_minimal_ckb_amount},
hash_algorithm::HashAlgorithm,
key::blake2b_hash_with_salt,
network::FiberMessageWithPeerId,
serde_utils::EntityHex,
types::{
AcceptChannel, AddTlc, ChannelAnnouncement, ChannelReady, ClosingSigned, CommitmentSigned,
EcdsaSignature, FiberChannelMessage, FiberMessage, Hash256, LockTime, OpenChannel, Privkey,
Pubkey, ReestablishChannel, RemoveTlc, RemoveTlcFulfill, RemoveTlcReason, RevokeAndAck,
TxCollaborationMsg, TxComplete, TxUpdate,
},
NetworkActorCommand, NetworkActorEvent, NetworkActorMessage, ASSUME_NETWORK_ACTOR_ALIVE,
};
// - `empty_witness_args`: 16 bytes, fixed to 0x10000000100000001000000010000000, for compatibility with the xudt
// - `pubkey`: 32 bytes, x only aggregated public key
// - `signature`: 64 bytes, aggregated signature
pub const FUNDING_CELL_WITNESS_LEN: usize = 16 + 32 + 64;
// Some part of the code liberally gets previous commitment number, which is
// the current commitment number minus 1. We deliberately set initial commitment number to 1,
// so that we can get previous commitment point/number without checking if the channel
// is funded or not.
pub const INITIAL_COMMITMENT_NUMBER: u64 = 0;
// The channel is disabled, and no more tlcs can be added to the channel.
pub const CHANNEL_DISABLED_FLAG: u32 = 1;
#[derive(Debug)]
pub enum ChannelActorMessage {
/// Command are the messages that are sent to the channel actor to perform some action.
/// It is normally generated from a user request.
Command(ChannelCommand),
/// Some system events associated to a channel, such as the funding transaction confirmed.
Event(ChannelEvent),
/// PeerMessage are the messages sent from the peer.
PeerMessage(FiberChannelMessage),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AddTlcResponse {
pub tlc_id: u64,
}
#[derive(Clone)]
pub struct TlcNotification {
pub channel_id: Hash256,
pub tlc: TLC,
pub script: Script,
}
#[derive(Debug)]
pub enum ChannelCommand {
TxCollaborationCommand(TxCollaborationCommand),
// TODO: maybe we should automatically send commitment_signed message after receiving
// tx_complete event.
CommitmentSigned(),
AddTlc(AddTlcCommand, RpcReplyPort<Result<AddTlcResponse, String>>),
RemoveTlc(RemoveTlcCommand, RpcReplyPort<Result<(), String>>),
Shutdown(ShutdownCommand, RpcReplyPort<Result<(), String>>),
Update(UpdateCommand, RpcReplyPort<Result<(), String>>),
}
#[derive(Debug)]
pub enum TxCollaborationCommand {
TxUpdate(TxUpdateCommand),
TxComplete(),
}
#[derive(Debug)]
pub struct AddTlcCommand {
pub amount: u128,
pub preimage: Option<Hash256>,
pub payment_hash: Option<Hash256>,
pub expiry: LockTime,
pub hash_algorithm: HashAlgorithm,
pub onion_packet: Vec<u8>,
pub previous_tlc: Option<(Hash256, u64)>,
}
#[derive(Debug)]
pub struct RemoveTlcCommand {
pub id: u64,
pub reason: RemoveTlcReason,
}
#[derive(Debug)]
pub struct ShutdownCommand {
pub close_script: Script,
pub fee_rate: FeeRate,
pub force: bool,
}
#[derive(Debug)]
pub struct UpdateCommand {
pub enabled: Option<bool>,
pub tlc_locktime_expiry_delta: Option<u64>,
pub tlc_minimum_value: Option<u128>,
pub tlc_maximum_value: Option<u128>,
pub tlc_fee_proportional_millionths: Option<u128>,
}
fn get_random_preimage() -> Hash256 {
let mut preimage = [0u8; 32];
preimage.copy_from_slice(&rand::random::<[u8; 32]>());
preimage.into()
}
#[derive(Debug)]
pub struct ChannelCommandWithId {
pub channel_id: Hash256,
pub command: ChannelCommand,
}
pub const DEFAULT_FEE_RATE: u64 = 1_000;
pub const DEFAULT_COMMITMENT_FEE_RATE: u64 = 1_000;
pub const DEFAULT_MAX_TLC_VALUE_IN_FLIGHT: u128 = u128::MAX;
pub const DEFAULT_MAX_TLC_NUMBER_IN_FLIGHT: u64 = 30;
pub const SYS_MAX_TLC_NUMBER_IN_FLIGHT: u64 = 253;
pub const DEFAULT_MIN_TLC_VALUE: u128 = 0;
pub const DEFAULT_TO_LOCAL_DELAY_BLOCKS: u64 = 10;
#[derive(Debug)]
pub struct TxUpdateCommand {
pub transaction: Transaction,
}
pub struct OpenChannelParameter {
pub funding_amount: u128,
pub seed: [u8; 32],
pub public_channel_info: Option<PublicChannelInfo>,
pub funding_udt_type_script: Option<Script>,
pub shutdown_script: Script,
pub channel_id_sender: oneshot::Sender<Hash256>,
pub commitment_fee_rate: Option<u64>,
pub funding_fee_rate: Option<u64>,
pub max_tlc_value_in_flight: Option<u128>,
pub max_tlc_number_in_flight: Option<u64>,
}
pub struct AcceptChannelParameter {
pub funding_amount: u128,
pub reserved_ckb_amount: u64,
pub public_channel_info: Option<PublicChannelInfo>,
pub seed: [u8; 32],
pub open_channel: OpenChannel,
pub shutdown_script: Script,
pub channel_id_sender: Option<oneshot::Sender<Hash256>>,
}
pub enum ChannelInitializationParameter {
/// To open a new channel to another peer, the funding amount,
/// the temporary channel id a unique channel seed to generate
/// channel secrets must be given.
OpenChannel(OpenChannelParameter),
/// To accept a new channel from another peer, the funding amount,
/// a unique channel seed to generate unique channel id,
/// original OpenChannel message and an oneshot
/// channel to receive the new channel ID must be given.
AcceptChannel(AcceptChannelParameter),
/// Reestablish a channel with given channel id.
ReestablishChannel(Hash256),
}
#[derive(Clone)]
pub struct ChannelSubscribers {
pub pending_received_tlcs_subscribers: Arc<OutputPort<TlcNotification>>,
pub settled_tlcs_subscribers: Arc<OutputPort<TlcNotification>>,
}
impl Default for ChannelSubscribers {
fn default() -> Self {
Self {
pending_received_tlcs_subscribers: Arc::new(OutputPort::default()),
settled_tlcs_subscribers: Arc::new(OutputPort::default()),
}
}
}
pub struct ChannelActor<S> {
local_pubkey: Pubkey,
remote_pubkey: Pubkey,
network: ActorRef<NetworkActorMessage>,
store: S,
subscribers: ChannelSubscribers,
}
impl<S> ChannelActor<S>
where
S: InvoiceStore,
{
pub fn new(
local_pubkey: Pubkey,
remote_pubkey: Pubkey,
network: ActorRef<NetworkActorMessage>,
store: S,
subscribers: ChannelSubscribers,
) -> Self {
Self {
local_pubkey,
remote_pubkey,
network,
store,
subscribers,
}
}
pub fn get_local_pubkey(&self) -> Pubkey {
self.local_pubkey
}
pub fn get_remote_pubkey(&self) -> Pubkey {
self.remote_pubkey
}
pub fn get_remote_peer_id(&self) -> PeerId {
self.remote_pubkey.tentacle_peer_id()
}
pub async fn handle_peer_message(
&self,
state: &mut ChannelActorState,
message: FiberChannelMessage,
) -> Result<(), ProcessingChannelError> {
if state.reestablishing {
match message {
FiberChannelMessage::ReestablishChannel(ref reestablish_channel) => {
state.handle_reestablish_channel_message(reestablish_channel, &self.network)?;
}
_ => {
debug!("Ignoring message while reestablishing: {:?}", message);
}
}
return Ok(());
}
match message {
FiberChannelMessage::AnnouncementSignatures(announcement_signatures) => {
if !state.is_public() {
return Err(ProcessingChannelError::InvalidState(
"Received AnnouncementSignatures message, but the channel is not public"
.to_string(),
));
}
match state.state {
ChannelState::ChannelReady() => {}
ChannelState::AwaitingChannelReady(flags)
if flags.contains(AwaitingChannelReadyFlags::CHANNEL_READY) => {}
_ => {
return Err(ProcessingChannelError::InvalidState(format!(
"Received unexpected AnnouncementSignatures message in state {:?}, expecting state AwaitingChannelReady::CHANNEL_READY or ChannelReady",
state.state
)));
}
}
// TODO: check announcement_signatures validity here.
let AnnouncementSignatures {
node_signature,
partial_signature,
..
} = announcement_signatures;
state.update_remote_channel_announcement_signature(
node_signature,
partial_signature,
);
state.maybe_public_channel_is_ready(&self.network).await;
Ok(())
}
FiberChannelMessage::AcceptChannel(accept_channel) => {
state.handle_accept_channel_message(accept_channel)?;
let old_id = state.get_id();
state.fill_in_channel_id();
self.network
.send_message(NetworkActorMessage::new_event(
NetworkActorEvent::ChannelAccepted(
state.get_remote_peer_id(),
state.get_id(),
old_id,
state.to_local_amount,
state.to_remote_amount,
state.get_funding_lock_script(),
state.funding_udt_type_script.clone(),
state.local_reserved_ckb_amount,
state.remote_reserved_ckb_amount,
state.funding_fee_rate,
),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
Ok(())
}
FiberChannelMessage::TxUpdate(tx) => {
state.handle_tx_collaboration_msg(TxCollaborationMsg::TxUpdate(tx), &self.network)
}
FiberChannelMessage::TxComplete(tx) => {
state.handle_tx_collaboration_msg(
TxCollaborationMsg::TxComplete(tx),
&self.network,
)?;
if let ChannelState::CollaboratingFundingTx(flags) = state.state {
if flags.contains(CollaboratingFundingTxFlags::COLLABRATION_COMPLETED) {
self.handle_commitment_signed_command(state)?;
}
}
Ok(())
}
FiberChannelMessage::CommitmentSigned(commitment_signed) => {
state.handle_commitment_signed_message(commitment_signed, &self.network)?;
if let ChannelState::SigningCommitment(flags) = state.state {
if !flags.contains(SigningCommitmentFlags::OUR_COMMITMENT_SIGNED_SENT) {
// TODO: maybe we should send our commitment_signed message here.
debug!("CommitmentSigned message received, but we haven't sent our commitment_signed message yet");
// Notify outside observers.
self.network
.send_message(NetworkActorMessage::new_event(
NetworkActorEvent::NetworkServiceEvent(
NetworkServiceEvent::CommitmentSignaturePending(
state.get_remote_peer_id(),
state.get_id(),
state.get_current_commitment_number(false),
),
),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
}
}
self.try_to_settle_down_tlc(state);
Ok(())
}
FiberChannelMessage::TxSignatures(tx_signatures) => {
// We're the one who sent tx_signature first, and we received a tx_signature message.
// This means that the tx_signature procedure is now completed. Just change state,
// and exit.
if state.should_local_send_tx_signatures_first() {
let new_witnesses: Vec<_> = tx_signatures
.witnesses
.into_iter()
.map(|x| x.pack())
.collect();
debug!(
"Updating funding tx witnesses of {:?} to {:?}",
state.get_funding_transaction().calc_tx_hash(),
new_witnesses.iter().map(|x| hex::encode(x.as_slice()))
);
state.funding_tx = Some(
state
.get_funding_transaction()
.as_advanced_builder()
.set_witnesses(new_witnesses)
.build()
.data(),
);
self.network
.send_message(NetworkActorMessage::new_event(
NetworkActorEvent::FundingTransactionPending(
state.get_funding_transaction().clone(),
state.get_funding_transaction_outpoint(),
state.get_id(),
),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
state.update_state(ChannelState::AwaitingChannelReady(
AwaitingChannelReadyFlags::empty(),
));
return Ok(());
};
state.handle_tx_signatures(&self.network, Some(tx_signatures.witnesses))?;
Ok(())
}
FiberChannelMessage::RevokeAndAck(revoke_and_ack) => {
state.handle_revoke_and_ack_message(&self.network, revoke_and_ack)?;
Ok(())
}
FiberChannelMessage::ChannelReady(_channel_ready) => {
let flags = match state.state {
ChannelState::AwaitingTxSignatures(flags) => {
if flags.contains(AwaitingTxSignaturesFlags::TX_SIGNATURES_SENT) {
AwaitingChannelReadyFlags::empty()
} else {
return Err(ProcessingChannelError::InvalidState(format!(
"received ChannelReady message, but we're not ready for ChannelReady, state is currently {:?}",
state.state
)));
}
}
ChannelState::AwaitingChannelReady(flags) => flags,
_ => {
return Err(ProcessingChannelError::InvalidState(format!(
"received ChannelReady message, but we're not ready for ChannelReady, state is currently {:?}", state.state
)));
}
};
let flags = flags | AwaitingChannelReadyFlags::THEIR_CHANNEL_READY;
state.update_state(ChannelState::AwaitingChannelReady(flags));
state.maybe_channel_is_ready(&self.network).await;
Ok(())
}
FiberChannelMessage::AddTlc(add_tlc) => {
state.check_for_tlc_update(Some(add_tlc.amount))?;
// check the onion_packet is valid or not, if not, we should return an error.
// If there is a next hop, we should send the AddTlc message to the next hop.
// If this is the last hop, we should check the payment hash and amount and then
// try to fulfill the payment, find the corresponding payment preimage from payment hash.
let mut preimage = None;
let mut peeled_packet_bytes: Option<Vec<u8>> = None;
if !add_tlc.onion_packet.is_empty() {
// TODO: Here we call network actor to peel the onion packet. Indeed, this message is forwarded from
// the network actor when it handles `FiberMessage::ChannelNormalOperation`. A better alternative is
// peeling the onion packet there before forwarding the message to the channel actor.
let peeled_packet = call!(self.network, |tx| NetworkActorMessage::Command(
NetworkActorCommand::PeelPaymentOnionPacket(
add_tlc.onion_packet.clone(),
add_tlc.payment_hash.clone(),
tx
)
))
.expect("call network")
.map_err(|err| ProcessingChannelError::PeelingOnionPacketError(err))?;
// TODO: check the expiry time, if expired, we should return an error.
if peeled_packet.is_last() {
// check the payment hash and amount
if peeled_packet.current.payment_hash != add_tlc.payment_hash
|| peeled_packet.current.amount != add_tlc.amount
{
return Err(ProcessingChannelError::InvalidParameter(
"Payment hash or amount mismatch".to_string(),
));
}
// if this is the last hop, store the preimage.
preimage = peeled_packet.current.preimage;
} else {
peeled_packet_bytes = Some(peeled_packet.serialize());
}
}
let tlc = state.create_inbounding_tlc(add_tlc.clone(), preimage)?;
state.insert_tlc(tlc.clone())?;
if let Some(ref udt_type_script) = state.funding_udt_type_script {
self.subscribers
.pending_received_tlcs_subscribers
.send(TlcNotification {
tlc: tlc.clone(),
channel_id: state.get_id(),
script: udt_type_script.clone(),
});
}
warn!("created tlc: {:?}", &tlc);
// TODO: here we didn't send any ack message to the peer.
// The peer may falsely believe that we have already processed this message,
// while we have crashed. We need a way to make sure that the peer will resend
// this message, and our processing of this message is idempotent.
if let Some(peeled_packet_bytes) = peeled_packet_bytes {
self.network
.send_message(NetworkActorMessage::Command(
NetworkActorCommand::SendPaymentOnionPacket(
peeled_packet_bytes,
Some((state.get_id(), tlc.get_id())),
),
))
.expect("network actor is alive");
}
Ok(())
}
FiberChannelMessage::RemoveTlc(remove_tlc) => {
state.check_for_tlc_update(None)?;
let channel_id = state.get_id();
let tlc_details = state
.remove_tlc_with_reason(TLCId::Offered(remove_tlc.tlc_id), remove_tlc.reason)?;
if let (
Some(ref udt_type_script),
RemoveTlcReason::RemoveTlcFulfill(RemoveTlcFulfill { payment_preimage }),
) = (state.funding_udt_type_script.clone(), remove_tlc.reason)
{
let mut tlc = tlc_details.tlc.clone();
tlc.payment_preimage = Some(payment_preimage);
self.subscribers
.settled_tlcs_subscribers
.send(TlcNotification {
tlc,
channel_id,
script: udt_type_script.clone(),
});
}
if let Some((previous_channel_id, previous_tlc)) = tlc_details.tlc.previous_tlc {
assert!(previous_tlc.is_received());
info!(
"begin to remove tlc from previous channel: {:?}",
&previous_tlc
);
let (send, recv) = oneshot::channel::<Result<(), String>>();
let port = RpcReplyPort::from(send);
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::ControlFiberChannel(ChannelCommandWithId {
channel_id: previous_channel_id,
command: ChannelCommand::RemoveTlc(
RemoveTlcCommand {
id: previous_tlc.into(),
reason: remove_tlc.reason,
},
port,
),
}),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
let res = recv.await.expect("network actor is alive");
info!("remove tlc from previous channel: {:?}", &res);
}
Ok(())
}
FiberChannelMessage::Shutdown(shutdown) => {
let flags = match state.state {
ChannelState::ChannelReady() => ShuttingDownFlags::empty(),
ChannelState::ShuttingDown(flags)
if flags.contains(ShuttingDownFlags::THEIR_SHUTDOWN_SENT) =>
{
return Err(ProcessingChannelError::InvalidParameter(
"Received Shutdown message, but we're already in ShuttingDown state"
.to_string(),
));
}
ChannelState::ShuttingDown(flags) => flags,
_ => {
return Err(ProcessingChannelError::InvalidState(format!(
"received Shutdown message, but we're not ready for Shutdown, state is currently {:?}",
state.state
)));
}
};
let shutdown_info = ShutdownInfo {
close_script: shutdown.close_script,
fee_rate: shutdown.fee_rate.as_u64(),
signature: None,
};
state.remote_shutdown_info = Some(shutdown_info);
let mut flags = flags | ShuttingDownFlags::THEIR_SHUTDOWN_SENT;
// Only automatically reply shutdown if only their shutdown message is sent.
// If we are in a state other than only their shutdown is sent,
// e.g. our shutdown message is also sent, or we are trying to force shutdown,
// we should not reply.
let should_we_reply_shutdown =
matches!(flags, ShuttingDownFlags::THEIR_SHUTDOWN_SENT);
if state.check_valid_to_auto_accept_shutdown() && should_we_reply_shutdown {
let close_script = state.get_local_shutdown_script();
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::SendFiberMessage(FiberMessageWithPeerId::new(
state.get_remote_peer_id(),
FiberMessage::shutdown(Shutdown {
channel_id: state.get_id(),
close_script: close_script.clone(),
fee_rate: FeeRate::from_u64(0),
force: shutdown.force,
}),
)),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
let shutdown_info = ShutdownInfo {
close_script,
fee_rate: 0,
signature: None,
};
state.local_shutdown_info = Some(shutdown_info);
flags |= ShuttingDownFlags::OUR_SHUTDOWN_SENT;
debug!("Auto accept shutdown ...");
}
state.update_state(ChannelState::ShuttingDown(flags));
state.maybe_transition_to_shutdown(&self.network)?;
Ok(())
}
FiberChannelMessage::ClosingSigned(closing) => {
let ClosingSigned {
partial_signature,
channel_id,
} = closing;
if channel_id != state.get_id() {
return Err(ProcessingChannelError::InvalidParameter(
"Channel id mismatch".to_string(),
));
}
// Note that we don't check the validity of the signature here.
// we will check the validity when we're about to build the shutdown tx.
// This may be or may not be a problem.
// We do this to simplify the handling of the message.
// We may change this in the future.
// We also didn't check the state here.
if let Some(shutdown_info) = state.remote_shutdown_info.as_mut() {
shutdown_info.signature = Some(partial_signature);
}
state.maybe_transition_to_shutdown(&self.network)?;
Ok(())
}
FiberChannelMessage::ReestablishChannel(ref reestablish_channel) => {
state.handle_reestablish_channel_message(reestablish_channel, &self.network)?;
Ok(())
}
FiberChannelMessage::TxAbort(_)
| FiberChannelMessage::TxInitRBF(_)
| FiberChannelMessage::TxAckRBF(_) => {
warn!("Received unsupported message: {:?}", &message);
Ok(())
}
}
}
fn try_to_settle_down_tlc(&self, state: &mut ChannelActorState) {
let tlcs = state.get_tlcs_for_settle_down();
info!("try_to_settle_down_tlc get tlcs: {:?}", &tlcs);
for tlc_info in tlcs {
let tlc = tlc_info.tlc.clone();
let preimage = if let Some(preimage) = tlc.payment_preimage {
preimage
} else if let Some(preimage) = self.store.get_invoice_preimage(&tlc.payment_hash) {
preimage
} else {
continue;
};
let command = RemoveTlcCommand {
id: tlc.get_id(),
reason: RemoveTlcReason::RemoveTlcFulfill(RemoveTlcFulfill {
payment_preimage: preimage,
}),
};
let result = self.handle_remove_tlc_command(state, command);
info!("try to settle down tlc: {:?} result: {:?}", &tlc, &result);
// we only handle one tlc at a time.
break;
}
}
pub fn handle_commitment_signed_command(
&self,
state: &mut ChannelActorState,
) -> ProcessingChannelResult {
let flags = match state.state {
ChannelState::CollaboratingFundingTx(flags)
if !flags.contains(CollaboratingFundingTxFlags::COLLABRATION_COMPLETED) =>
{
return Err(ProcessingChannelError::InvalidState(format!(
"Unable to process commitment_signed command in state {:?}, as collaboration is not completed yet.",
&state.state
)));
}
ChannelState::CollaboratingFundingTx(_) => {
debug!(
"Processing commitment_signed command in from CollaboratingFundingTx state {:?}",
&state.state
);
CommitmentSignedFlags::SigningCommitment(SigningCommitmentFlags::empty())
}
ChannelState::SigningCommitment(flags)
if flags.contains(SigningCommitmentFlags::OUR_COMMITMENT_SIGNED_SENT) =>
{
return Err(ProcessingChannelError::InvalidState(format!(
"Unable to process commitment_signed command in state {:?}, as we have already sent our commitment_signed message.",
&state.state
)));
}
ChannelState::SigningCommitment(flags) => {
debug!(
"Processing commitment_signed command in from SigningCommitment state {:?}",
&state.state
);
CommitmentSignedFlags::SigningCommitment(flags)
}
ChannelState::ChannelReady() => CommitmentSignedFlags::ChannelReady(),
ChannelState::ShuttingDown(flags) => {
if flags.contains(ShuttingDownFlags::AWAITING_PENDING_TLCS) {
debug!(
"Signing commitment transactions while shutdown is pending, current state {:?}",
&state.state
);
CommitmentSignedFlags::PendingShutdown(flags)
} else {
return Err(ProcessingChannelError::InvalidState(format!(
"Unable to process commitment_signed message in shutdowning state with flags {:?}",
&flags
)));
}
}
_ => {
return Err(ProcessingChannelError::InvalidState(format!(
"Unable to send commitment signed message in state {:?}",
&state.state
)));
}
};
debug!(
"Building and signing commitment tx for state {:?}",
&state.state
);
let PartiallySignedCommitmentTransaction {
version,
commitment_tx,
funding_tx_partial_signature,
commitment_tx_partial_signature,
} = state.build_and_sign_commitment_tx()?;
debug!(
"Sending next local nonce {:?} (previous nonce {:?})",
state.get_next_local_nonce(),
state.get_local_nonce().borrow()
);
let commitment_signed = CommitmentSigned {
channel_id: state.get_id(),
funding_tx_partial_signature,
commitment_tx_partial_signature,
next_local_nonce: state.get_next_local_nonce(),
};
debug!(
"Sending built commitment_signed message: {:?}",
&commitment_signed
);
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::SendFiberMessage(FiberMessageWithPeerId::new(
state.get_remote_peer_id(),
FiberMessage::commitment_signed(commitment_signed),
)),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
self.network
.send_message(NetworkActorMessage::new_event(
NetworkActorEvent::NetworkServiceEvent(NetworkServiceEvent::LocalCommitmentSigned(
state.get_remote_peer_id(),
state.get_id(),
version,
commitment_tx,
)),
))
.expect("myself alive");
match flags {
CommitmentSignedFlags::SigningCommitment(flags) => {
let flags = flags | SigningCommitmentFlags::OUR_COMMITMENT_SIGNED_SENT;
state.update_state(ChannelState::SigningCommitment(flags));
state.maybe_transition_to_tx_signatures(flags, &self.network)?;
}
CommitmentSignedFlags::ChannelReady() => {}
CommitmentSignedFlags::PendingShutdown(_) => {
state.maybe_transition_to_shutdown(&self.network)?;
}
}
Ok(())
}
pub fn handle_add_tlc_command(
&self,
state: &mut ChannelActorState,
command: AddTlcCommand,
) -> Result<u64, ProcessingChannelError> {
debug!("handle add tlc command : {:?}", &command);
state.check_for_tlc_update(Some(command.amount))?;
let tlc = state.create_outbounding_tlc(command);
state.insert_tlc(tlc.clone())?;
debug!("Inserted tlc into channel state: {:?}", &tlc);
// TODO: Note that since message sending is async,
// we can't guarantee anything about the order of message sending
// and state updating. And any of these may fail while the other succeeds.
// We may need to handle all these possibilities.
// To make things worse, we currently don't have a way to ACK all the messages.
// Send tlc update message to peer.
let msg = FiberMessageWithPeerId::new(
state.get_remote_peer_id(),
FiberMessage::add_tlc(AddTlc {
channel_id: state.get_id(),
tlc_id: tlc.id.into(),
amount: tlc.amount,
payment_hash: tlc.payment_hash,
expiry: tlc.lock_time,
hash_algorithm: tlc.hash_algorithm,
onion_packet: tlc.onion_packet,
}),
);
debug!("Sending AddTlc message: {:?}", &msg);
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::SendFiberMessage(msg),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
self.handle_commitment_signed_command(state)?;
Ok(tlc.id.into())
}
pub fn handle_remove_tlc_command(
&self,
state: &mut ChannelActorState,
command: RemoveTlcCommand,
) -> ProcessingChannelResult {
state.check_for_tlc_update(None)?;
let tlc = state.remove_tlc_with_reason(TLCId::Received(command.id), command.reason)?;
let msg = FiberMessageWithPeerId::new(
state.get_remote_peer_id(),
FiberMessage::remove_tlc(RemoveTlc {
channel_id: state.get_id(),
tlc_id: command.id,
reason: command.reason,
}),
);
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::SendFiberMessage(msg),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
debug!(
"Channel ({:?}) balance after removing tlc {:?}: local balance: {}, remote balance: {}",
state.get_id(),
tlc,
state.to_local_amount,
state.to_remote_amount
);
state.maybe_transition_to_shutdown(&self.network)?;
self.handle_commitment_signed_command(state)?;
Ok(())
}
pub fn handle_shutdown_command(
&self,
state: &mut ChannelActorState,
command: ShutdownCommand,
) -> ProcessingChannelResult {
debug!("Handling shutdown command: {:?}", &command);
let flags = match state.state {
ChannelState::Closed(_) => {
debug!("Channel already closed, ignoring shutdown command");
return Ok(());
}
ChannelState::ChannelReady() => {
debug!("Handling shutdown command in ChannelReady state");
ShuttingDownFlags::empty()
}
ChannelState::ShuttingDown(flags) => {
if !command.force {
debug!("we already in shutting down state: {:?}", &flags);
return Ok(());
}
flags
}
_ => {
debug!("Handling shutdown command in state {:?}", &state.state);
return Err(ProcessingChannelError::InvalidState(format!(
"Trying to send shutdown message while in invalid state {:?}",
&state.state
)));
}
};
state.check_shutdown_fee_rate(command.fee_rate, &command.close_script)?;
if command.force {
if let Some(transaction) = &state.latest_commitment_transaction {
self.network
.send_message(NetworkActorMessage::new_event(
NetworkActorEvent::CommitmentTransactionPending(
transaction.clone(),
state.get_id(),
),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
state.update_state(ChannelState::ShuttingDown(
ShuttingDownFlags::WAITING_COMMITMENT_CONFIRMATION,
));
} else {
return Err(ProcessingChannelError::InvalidState(
"Force shutdown without a valid commitment transaction".to_string(),
));
}
} else {
self.network
.send_message(NetworkActorMessage::new_command(
NetworkActorCommand::SendFiberMessage(FiberMessageWithPeerId::new(
self.get_remote_peer_id(),
FiberMessage::shutdown(Shutdown {
channel_id: state.get_id(),
close_script: command.close_script.clone(),
fee_rate: command.fee_rate,
force: command.force,
}),
)),
))
.expect(ASSUME_NETWORK_ACTOR_ALIVE);
let shutdown_info = ShutdownInfo {
close_script: command.close_script,
fee_rate: command.fee_rate.as_u64(),
signature: None,
};
state.local_shutdown_info = Some(shutdown_info);
state.update_state(ChannelState::ShuttingDown(
flags | ShuttingDownFlags::OUR_SHUTDOWN_SENT,
));
debug!(
"Channel state updated to {:?} after processing shutdown command",
&state.state
);
state.maybe_transition_to_shutdown(&self.network)?;
}
Ok(())
}
pub async fn handle_update_command(
&self,
state: &mut ChannelActorState,
command: UpdateCommand,
) -> ProcessingChannelResult {
if !state.is_public() {
return Err(ProcessingChannelError::InvalidState(
"Only public channel can be updated".to_string(),
));
}
let UpdateCommand {
enabled,
tlc_locktime_expiry_delta,
tlc_minimum_value,
tlc_maximum_value,
tlc_fee_proportional_millionths,
} = command;