-
Notifications
You must be signed in to change notification settings - Fork 89
/
context.rs
1117 lines (951 loc) · 40.2 KB
/
context.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 crate::prelude::*;
use super::{
ics02_client::error::ClientError,
ics03_connection::error::ConnectionError,
ics04_channel::error::{ChannelError, PacketError},
};
use displaydoc::Display;
#[derive(Debug, Display)]
pub enum ContextError {
/// ICS02 Client error
ClientError(ClientError),
/// ICS03 Connection error
ConnectionError(ConnectionError),
/// Ics04 Channel error
ChannelError(ChannelError),
/// ICS04 Packet error
PacketError(PacketError),
}
impl From<ClientError> for ContextError {
fn from(err: ClientError) -> ContextError {
Self::ClientError(err)
}
}
impl From<ConnectionError> for ContextError {
fn from(err: ConnectionError) -> ContextError {
Self::ConnectionError(err)
}
}
impl From<ChannelError> for ContextError {
fn from(err: ChannelError) -> ContextError {
Self::ChannelError(err)
}
}
impl From<PacketError> for ContextError {
fn from(err: PacketError) -> ContextError {
Self::PacketError(err)
}
}
#[cfg(feature = "std")]
impl std::error::Error for ContextError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self {
Self::ClientError(e) => Some(e),
Self::ConnectionError(e) => Some(e),
Self::ChannelError(e) => Some(e),
Self::PacketError(e) => Some(e),
}
}
}
#[cfg(feature = "val_exec_ctx")]
pub use val_exec_ctx::*;
#[cfg(feature = "val_exec_ctx")]
mod val_exec_ctx {
use super::*;
use core::time::Duration;
use ibc_proto::google::protobuf::Any;
use crate::core::ics02_client::client_state::ClientState;
use crate::core::ics02_client::client_type::ClientType;
use crate::core::ics02_client::consensus_state::ConsensusState;
use crate::core::ics03_connection::connection::ConnectionEnd;
use crate::core::ics03_connection::error::ConnectionError;
use crate::core::ics03_connection::version::{
get_compatible_versions, pick_version, Version as ConnectionVersion,
};
use crate::core::ics04_channel::channel::{ChannelEnd, Counterparty, State};
use crate::core::ics04_channel::commitment::{AcknowledgementCommitment, PacketCommitment};
use crate::core::ics04_channel::context::calculate_block_delay;
use crate::core::ics04_channel::events::{
CloseConfirm, CloseInit, OpenAck, OpenConfirm, OpenInit, OpenTry,
};
use crate::core::ics04_channel::handler::{
chan_close_confirm, chan_close_init, chan_open_ack, chan_open_confirm, chan_open_init,
chan_open_try,
};
use crate::core::ics04_channel::msgs::acknowledgement::Acknowledgement;
use crate::core::ics04_channel::msgs::chan_close_confirm::MsgChannelCloseConfirm;
use crate::core::ics04_channel::msgs::chan_close_init::MsgChannelCloseInit;
use crate::core::ics04_channel::msgs::chan_open_ack::MsgChannelOpenAck;
use crate::core::ics04_channel::msgs::chan_open_confirm::MsgChannelOpenConfirm;
use crate::core::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit;
use crate::core::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry;
use crate::core::ics04_channel::msgs::ChannelMsg;
use crate::core::ics04_channel::packet::{Receipt, Sequence};
use crate::core::ics04_channel::timeout::TimeoutHeight;
use crate::core::ics05_port::error::PortError::UnknownPort;
use crate::core::ics23_commitment::commitment::CommitmentPrefix;
use crate::core::ics24_host::identifier::{ChannelId, ConnectionId, PortId};
use crate::core::ics24_host::path::{
ClientConnectionsPath, ClientConsensusStatePath, ClientStatePath, ClientTypePath,
CommitmentsPath, ConnectionsPath, ReceiptsPath,
};
use crate::core::ics26_routing::context::{Module, ModuleId};
use crate::core::{
ics02_client::{
handler::{create_client, misbehaviour, update_client, upgrade_client},
msgs::ClientMsg,
},
ics03_connection::{
handler::{conn_open_ack, conn_open_confirm, conn_open_init, conn_open_try},
msgs::ConnectionMsg,
},
ics24_host::identifier::ClientId,
ics26_routing::{error::RouterError, msgs::MsgEnvelope},
};
use crate::events::IbcEvent;
use crate::timestamp::Timestamp;
use crate::Height;
use super::ContextError;
pub trait Router {
/// Returns a reference to a `Module` registered against the specified `ModuleId`
fn get_route(&self, module_id: &ModuleId) -> Option<&dyn Module>;
/// Returns a mutable reference to a `Module` registered against the specified `ModuleId`
fn get_route_mut(&mut self, module_id: &ModuleId) -> Option<&mut dyn Module>;
/// Returns true if the `Router` has a `Module` registered against the specified `ModuleId`
fn has_route(&self, module_id: &ModuleId) -> bool;
/// Return the module_id associated with a given port_id
fn lookup_module_by_port(&self, port_id: &PortId) -> Option<ModuleId>;
fn lookup_module(&self, msg: &ChannelMsg) -> Result<ModuleId, ChannelError> {
let port_id = match msg {
ChannelMsg::OpenInit(msg) => &msg.port_id_on_a,
ChannelMsg::OpenTry(msg) => &msg.port_id_on_b,
ChannelMsg::OpenAck(msg) => &msg.port_id_on_a,
ChannelMsg::OpenConfirm(msg) => &msg.port_id_on_b,
ChannelMsg::CloseInit(msg) => &msg.port_id_on_a,
ChannelMsg::CloseConfirm(msg) => &msg.port_id_on_b,
};
let module_id = self
.lookup_module_by_port(port_id)
.ok_or(ChannelError::Port(UnknownPort {
port_id: port_id.clone(),
}))?;
Ok(module_id)
}
}
pub trait ValidationContext: Router {
/// Validation entrypoint.
fn validate(&self, msg: MsgEnvelope) -> Result<(), RouterError>
where
Self: Sized,
{
match msg {
MsgEnvelope::Client(msg) => match msg {
ClientMsg::CreateClient(msg) => create_client::validate(self, msg),
ClientMsg::UpdateClient(msg) => update_client::validate(self, msg),
ClientMsg::Misbehaviour(msg) => misbehaviour::validate(self, msg),
ClientMsg::UpgradeClient(msg) => upgrade_client::validate(self, msg),
}
.map_err(RouterError::ContextError),
MsgEnvelope::Connection(msg) => match msg {
ConnectionMsg::OpenInit(msg) => conn_open_init::validate(self, msg),
ConnectionMsg::OpenTry(msg) => conn_open_try::validate(self, msg),
ConnectionMsg::OpenAck(msg) => conn_open_ack::validate(self, msg),
ConnectionMsg::OpenConfirm(ref msg) => conn_open_confirm::validate(self, msg),
}
.map_err(RouterError::ContextError),
MsgEnvelope::Channel(msg) => {
let module_id = self.lookup_module(&msg).map_err(ContextError::from)?;
if !self.has_route(&module_id) {
return Err(ChannelError::RouteNotFound)
.map_err(ContextError::ChannelError)
.map_err(RouterError::ContextError);
}
match msg {
ChannelMsg::OpenInit(msg) => chan_open_init_validate(self, module_id, msg),
ChannelMsg::OpenTry(msg) => chan_open_try_validate(self, module_id, msg),
ChannelMsg::OpenAck(msg) => chan_open_ack_validate(self, module_id, msg),
ChannelMsg::OpenConfirm(msg) => {
chan_open_confirm_validate(self, module_id, msg)
}
ChannelMsg::CloseInit(msg) => {
chan_close_init_validate(self, module_id, msg)
}
ChannelMsg::CloseConfirm(msg) => {
chan_close_confirm_validate(self, module_id, msg)
}
}
.map_err(RouterError::ContextError)
}
MsgEnvelope::Packet(_msg) => todo!(),
}
}
/// Returns the ClientState for the given identifier `client_id`.
fn client_state(&self, client_id: &ClientId) -> Result<Box<dyn ClientState>, ContextError>;
/// Tries to decode the given `client_state` into a concrete light client state.
fn decode_client_state(
&self,
client_state: Any,
) -> Result<Box<dyn ClientState>, ContextError>;
/// Retrieve the consensus state for the given client ID at the specified
/// height.
///
/// Returns an error if no such state exists.
fn consensus_state(
&self,
client_id: &ClientId,
height: &Height,
) -> Result<Box<dyn ConsensusState>, ContextError>;
/// Search for the lowest consensus state higher than `height`.
fn next_consensus_state(
&self,
client_id: &ClientId,
height: &Height,
) -> Result<Option<Box<dyn ConsensusState>>, ContextError>;
/// Search for the highest consensus state lower than `height`.
fn prev_consensus_state(
&self,
client_id: &ClientId,
height: &Height,
) -> Result<Option<Box<dyn ConsensusState>>, ContextError>;
/// Returns the current height of the local chain.
fn host_height(&self) -> Result<Height, ContextError>;
/// Returns the current timestamp of the local chain.
fn host_timestamp(&self) -> Result<Timestamp, ContextError> {
let pending_consensus_state = self
.pending_host_consensus_state()
.expect("host must have pending consensus state");
Ok(pending_consensus_state.timestamp())
}
/// Returns the pending `ConsensusState` of the host (local) chain.
fn pending_host_consensus_state(&self) -> Result<Box<dyn ConsensusState>, ContextError>;
/// Returns the `ConsensusState` of the host (local) chain at a specific height.
fn host_consensus_state(
&self,
height: &Height,
) -> Result<Box<dyn ConsensusState>, ContextError>;
/// Returns a natural number, counting how many clients have been created thus far.
/// The value of this counter should increase only via method `ClientKeeper::increase_client_counter`.
fn client_counter(&self) -> Result<u64, ContextError>;
/// Returns the ConnectionEnd for the given identifier `conn_id`.
fn connection_end(&self, conn_id: &ConnectionId) -> Result<ConnectionEnd, ContextError>;
/// Validates the `ClientState` of the client on the counterparty chain.
fn validate_self_client(
&self,
counterparty_client_state: Any,
) -> Result<(), ConnectionError>;
/// Returns the prefix that the local chain uses in the KV store.
fn commitment_prefix(&self) -> CommitmentPrefix;
/// Returns a counter on how many connections have been created thus far.
fn connection_counter(&self) -> Result<u64, ContextError>;
/// Function required by ICS 03. Returns the list of all possible versions that the connection
/// handshake protocol supports.
fn get_compatible_versions(&self) -> Vec<ConnectionVersion> {
get_compatible_versions()
}
/// Function required by ICS 03. Returns one version out of the supplied list of versions, which the
/// connection handshake protocol prefers.
fn pick_version(
&self,
supported_versions: &[ConnectionVersion],
counterparty_candidate_versions: &[ConnectionVersion],
) -> Result<ConnectionVersion, ContextError> {
pick_version(supported_versions, counterparty_candidate_versions)
.map_err(ContextError::ConnectionError)
}
/// Returns the ChannelEnd for the given `port_id` and `chan_id`.
fn channel_end(
&self,
port_channel_id: &(PortId, ChannelId),
) -> Result<ChannelEnd, ContextError>;
fn connection_channels(
&self,
cid: &ConnectionId,
) -> Result<Vec<(PortId, ChannelId)>, ContextError>;
fn get_next_sequence_send(
&self,
port_channel_id: &(PortId, ChannelId),
) -> Result<Sequence, ContextError>;
fn get_next_sequence_recv(
&self,
port_channel_id: &(PortId, ChannelId),
) -> Result<Sequence, ContextError>;
fn get_next_sequence_ack(
&self,
port_channel_id: &(PortId, ChannelId),
) -> Result<Sequence, ContextError>;
fn get_packet_commitment(
&self,
key: &(PortId, ChannelId, Sequence),
) -> Result<PacketCommitment, ContextError>;
fn get_packet_receipt(
&self,
key: &(PortId, ChannelId, Sequence),
) -> Result<Receipt, ContextError>;
fn get_packet_acknowledgement(
&self,
key: &(PortId, ChannelId, Sequence),
) -> Result<AcknowledgementCommitment, ContextError>;
/// Compute the commitment for a packet.
/// Note that the absence of `timeout_height` is treated as
/// `{revision_number: 0, revision_height: 0}` to be consistent with ibc-go,
/// where this value is used to mean "no timeout height":
/// <https://github.com/cosmos/ibc-go/blob/04791984b3d6c83f704c4f058e6ca0038d155d91/modules/core/04-channel/keeper/packet.go#L206>
fn packet_commitment(
&self,
packet_data: &[u8],
timeout_height: &TimeoutHeight,
timeout_timestamp: &Timestamp,
) -> PacketCommitment {
let mut hash_input = timeout_timestamp.nanoseconds().to_be_bytes().to_vec();
let revision_number = timeout_height.commitment_revision_number().to_be_bytes();
hash_input.append(&mut revision_number.to_vec());
let revision_height = timeout_height.commitment_revision_height().to_be_bytes();
hash_input.append(&mut revision_height.to_vec());
let packet_data_hash = self.hash(packet_data);
hash_input.append(&mut packet_data_hash.to_vec());
self.hash(&hash_input).into()
}
fn ack_commitment(&self, ack: &Acknowledgement) -> AcknowledgementCommitment {
self.hash(ack.as_ref()).into()
}
/// A hashing function for packet commitments
fn hash(&self, value: &[u8]) -> Vec<u8>;
/// Returns the time when the client state for the given [`ClientId`] was updated with a header for the given [`Height`]
fn client_update_time(
&self,
client_id: &ClientId,
height: &Height,
) -> Result<Timestamp, ContextError>;
/// Returns the height when the client state for the given [`ClientId`] was updated with a header for the given [`Height`]
fn client_update_height(
&self,
client_id: &ClientId,
height: &Height,
) -> Result<Height, ContextError>;
/// Returns a counter on the number of channel ids have been created thus far.
/// The value of this counter should increase only via method
/// `ChannelKeeper::increase_channel_counter`.
fn channel_counter(&self) -> Result<u64, ContextError>;
/// Returns the maximum expected time per block
fn max_expected_time_per_block(&self) -> Duration;
/// Calculates the block delay period using the connection's delay period and the maximum
/// expected time per block.
fn block_delay(&self, delay_period_time: &Duration) -> u64 {
calculate_block_delay(delay_period_time, &self.max_expected_time_per_block())
}
}
pub trait ExecutionContext: ValidationContext {
/// Execution entrypoint
fn execute(&mut self, msg: MsgEnvelope) -> Result<(), RouterError>
where
Self: Sized,
{
match msg {
MsgEnvelope::Client(msg) => match msg {
ClientMsg::CreateClient(msg) => create_client::execute(self, msg),
ClientMsg::UpdateClient(msg) => update_client::execute(self, msg),
ClientMsg::Misbehaviour(msg) => misbehaviour::execute(self, msg),
ClientMsg::UpgradeClient(msg) => upgrade_client::execute(self, msg),
}
.map_err(RouterError::ContextError),
MsgEnvelope::Connection(msg) => match msg {
ConnectionMsg::OpenInit(msg) => conn_open_init::execute(self, msg),
ConnectionMsg::OpenTry(msg) => conn_open_try::execute(self, msg),
ConnectionMsg::OpenAck(msg) => conn_open_ack::execute(self, msg),
ConnectionMsg::OpenConfirm(ref msg) => conn_open_confirm::execute(self, msg),
}
.map_err(RouterError::ContextError),
MsgEnvelope::Channel(msg) => {
let module_id = self.lookup_module(&msg).map_err(ContextError::from)?;
if !self.has_route(&module_id) {
return Err(ChannelError::RouteNotFound)
.map_err(ContextError::ChannelError)
.map_err(RouterError::ContextError);
}
match msg {
ChannelMsg::OpenInit(msg) => chan_open_init_execute(self, module_id, msg),
ChannelMsg::OpenTry(msg) => chan_open_try_execute(self, module_id, msg),
ChannelMsg::OpenAck(msg) => chan_open_ack_execute(self, module_id, msg),
ChannelMsg::OpenConfirm(msg) => {
chan_open_confirm_execute(self, module_id, msg)
}
ChannelMsg::CloseInit(msg) => chan_close_init_execute(self, module_id, msg),
ChannelMsg::CloseConfirm(msg) => {
chan_close_confirm_execute(self, module_id, msg)
}
}
.map_err(RouterError::ContextError)
}
MsgEnvelope::Packet(_msg) => todo!(),
}
}
/// Called upon successful client creation
fn store_client_type(
&mut self,
client_type_path: ClientTypePath,
client_type: ClientType,
) -> Result<(), ContextError>;
/// Called upon successful client creation and update
fn store_client_state(
&mut self,
client_state_path: ClientStatePath,
client_state: Box<dyn ClientState>,
) -> Result<(), ContextError>;
/// Called upon successful client creation and update
fn store_consensus_state(
&mut self,
consensus_state_path: ClientConsensusStatePath,
consensus_state: Box<dyn ConsensusState>,
) -> Result<(), ContextError>;
/// Called upon client creation.
/// Increases the counter which keeps track of how many clients have been created.
/// Should never fail.
fn increase_client_counter(&mut self);
/// Called upon successful client update.
/// Implementations are expected to use this to record the specified time as the time at which
/// this update (or header) was processed.
fn store_update_time(
&mut self,
client_id: ClientId,
height: Height,
timestamp: Timestamp,
) -> Result<(), ContextError>;
/// Called upon successful client update.
/// Implementations are expected to use this to record the specified height as the height at
/// at which this update (or header) was processed.
fn store_update_height(
&mut self,
client_id: ClientId,
height: Height,
host_height: Height,
) -> Result<(), ContextError>;
/// Stores the given connection_end at path
fn store_connection(
&mut self,
connections_path: ConnectionsPath,
connection_end: ConnectionEnd,
) -> Result<(), ContextError>;
/// Stores the given connection_id at a path associated with the client_id.
fn store_connection_to_client(
&mut self,
client_connections_path: ClientConnectionsPath,
conn_id: ConnectionId,
) -> Result<(), ContextError>;
/// Called upon connection identifier creation (Init or Try process).
/// Increases the counter which keeps track of how many connections have been created.
/// Should never fail.
fn increase_connection_counter(&mut self);
fn store_packet_commitment(
&mut self,
commitments_path: CommitmentsPath,
commitment: PacketCommitment,
) -> Result<(), ContextError>;
fn delete_packet_commitment(&mut self, key: CommitmentsPath) -> Result<(), ContextError>;
fn store_packet_receipt(
&mut self,
path: ReceiptsPath,
receipt: Receipt,
) -> Result<(), ContextError>;
fn store_packet_acknowledgement(
&mut self,
key: (PortId, ChannelId, Sequence),
ack_commitment: AcknowledgementCommitment,
) -> Result<(), ContextError>;
fn delete_packet_acknowledgement(
&mut self,
key: (PortId, ChannelId, Sequence),
) -> Result<(), ContextError>;
fn store_connection_channels(
&mut self,
conn_id: ConnectionId,
port_channel_id: (PortId, ChannelId),
) -> Result<(), ContextError>;
/// Stores the given channel_end at a path associated with the port_id and channel_id.
fn store_channel(
&mut self,
port_channel_id: (PortId, ChannelId),
channel_end: ChannelEnd,
) -> Result<(), ContextError>;
fn store_next_sequence_send(
&mut self,
port_channel_id: (PortId, ChannelId),
seq: Sequence,
) -> Result<(), ContextError>;
fn store_next_sequence_recv(
&mut self,
port_channel_id: (PortId, ChannelId),
seq: Sequence,
) -> Result<(), ContextError>;
fn store_next_sequence_ack(
&mut self,
port_channel_id: (PortId, ChannelId),
seq: Sequence,
) -> Result<(), ContextError>;
/// Called upon channel identifier creation (Init or Try message processing).
/// Increases the counter which keeps track of how many channels have been created.
/// Should never fail.
fn increase_channel_counter(&mut self);
/// Ibc events
fn emit_ibc_event(&mut self, event: IbcEvent);
/// Logging facility
fn log_message(&mut self, message: String);
}
fn chan_open_init_validate<ValCtx>(
ctx_a: &ValCtx,
module_id: ModuleId,
msg: MsgChannelOpenInit,
) -> Result<(), ContextError>
where
ValCtx: ValidationContext,
{
chan_open_init::validate(ctx_a, &msg)?;
let chan_id_on_a = ChannelId::new(ctx_a.channel_counter()?);
let module = ctx_a
.get_route(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
module.on_chan_open_init_validate(
msg.ordering,
&msg.connection_hops_on_a,
&msg.port_id_on_a,
&chan_id_on_a,
&Counterparty::new(msg.port_id_on_b.clone(), None),
&msg.version_proposal,
)?;
Ok(())
}
fn chan_open_init_execute<ExecCtx>(
ctx_a: &mut ExecCtx,
module_id: ModuleId,
msg: MsgChannelOpenInit,
) -> Result<(), ContextError>
where
ExecCtx: ExecutionContext,
{
let chan_id_on_a = ChannelId::new(ctx_a.channel_counter()?);
let module = ctx_a
.get_route_mut(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
let (extras, version) = module.on_chan_open_init_execute(
msg.ordering,
&msg.connection_hops_on_a,
&msg.port_id_on_a,
&chan_id_on_a,
&Counterparty::new(msg.port_id_on_b.clone(), None),
&msg.version_proposal,
)?;
let conn_id_on_a = msg.connection_hops_on_a[0].clone();
// state changes
{
let port_channel_id_on_a = (msg.port_id_on_a.clone(), chan_id_on_a.clone());
let chan_end_on_a = ChannelEnd::new(
State::Init,
msg.ordering,
Counterparty::new(msg.port_id_on_b.clone(), None),
msg.connection_hops_on_a.clone(),
msg.version_proposal.clone(),
);
ctx_a.store_channel(port_channel_id_on_a.clone(), chan_end_on_a)?;
ctx_a.increase_channel_counter();
// Associate also the channel end to its connection.
ctx_a.store_connection_channels(conn_id_on_a.clone(), port_channel_id_on_a.clone())?;
// Initialize send, recv, and ack sequence numbers.
ctx_a.store_next_sequence_send(port_channel_id_on_a.clone(), 1.into())?;
ctx_a.store_next_sequence_recv(port_channel_id_on_a.clone(), 1.into())?;
ctx_a.store_next_sequence_ack(port_channel_id_on_a, 1.into())?;
}
// emit events and logs
{
ctx_a.log_message(format!(
"success: channel open init with channel identifier: {chan_id_on_a}"
));
let core_event = IbcEvent::OpenInitChannel(OpenInit::new(
msg.port_id_on_a.clone(),
chan_id_on_a.clone(),
msg.port_id_on_b,
conn_id_on_a,
version,
));
ctx_a.emit_ibc_event(core_event);
for module_event in extras.events {
ctx_a.emit_ibc_event(IbcEvent::AppModule(module_event));
}
for log_message in extras.log {
ctx_a.log_message(log_message);
}
}
Ok(())
}
fn chan_open_try_validate<ValCtx>(
ctx_b: &ValCtx,
module_id: ModuleId,
msg: MsgChannelOpenTry,
) -> Result<(), ContextError>
where
ValCtx: ValidationContext,
{
chan_open_try::validate(ctx_b, &msg)?;
let chan_id_on_b = ChannelId::new(ctx_b.channel_counter()?);
let module = ctx_b
.get_route(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
module.on_chan_open_try_validate(
msg.ordering,
&msg.connection_hops_on_b,
&msg.port_id_on_b,
&chan_id_on_b,
&Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())),
&msg.version_supported_on_a,
)?;
Ok(())
}
fn chan_open_try_execute<ExecCtx>(
ctx_b: &mut ExecCtx,
module_id: ModuleId,
msg: MsgChannelOpenTry,
) -> Result<(), ContextError>
where
ExecCtx: ExecutionContext,
{
let chan_id_on_b = ChannelId::new(ctx_b.channel_counter()?);
let module = ctx_b
.get_route_mut(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
let (extras, version) = module.on_chan_open_try_execute(
msg.ordering,
&msg.connection_hops_on_b,
&msg.port_id_on_b,
&chan_id_on_b,
&Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())),
&msg.version_supported_on_a,
)?;
let conn_id_on_b = msg.connection_hops_on_b[0].clone();
// state changes
{
let port_channel_id_on_b = (msg.port_id_on_b.clone(), chan_id_on_b.clone());
let chan_end_on_b = ChannelEnd::new(
State::TryOpen,
msg.ordering,
Counterparty::new(msg.port_id_on_a.clone(), Some(msg.chan_id_on_a.clone())),
msg.connection_hops_on_b.clone(),
version.clone(),
);
ctx_b.store_channel(port_channel_id_on_b.clone(), chan_end_on_b)?;
ctx_b.increase_channel_counter();
// Associate also the channel end to its connection.
ctx_b.store_connection_channels(conn_id_on_b.clone(), port_channel_id_on_b.clone())?;
// Initialize send, recv, and ack sequence numbers.
ctx_b.store_next_sequence_send(port_channel_id_on_b.clone(), 1.into())?;
ctx_b.store_next_sequence_recv(port_channel_id_on_b.clone(), 1.into())?;
ctx_b.store_next_sequence_ack(port_channel_id_on_b, 1.into())?;
}
// emit events and logs
{
ctx_b.log_message(format!(
"success: channel open try with channel identifier: {chan_id_on_b}"
));
let core_event = IbcEvent::OpenTryChannel(OpenTry::new(
msg.port_id_on_b.clone(),
chan_id_on_b.clone(),
msg.port_id_on_a.clone(),
msg.chan_id_on_a.clone(),
conn_id_on_b,
version,
));
ctx_b.emit_ibc_event(core_event);
for module_event in extras.events {
ctx_b.emit_ibc_event(IbcEvent::AppModule(module_event));
}
for log_message in extras.log {
ctx_b.log_message(log_message);
}
}
Ok(())
}
fn chan_open_ack_validate<ValCtx>(
ctx_a: &ValCtx,
module_id: ModuleId,
msg: MsgChannelOpenAck,
) -> Result<(), ContextError>
where
ValCtx: ValidationContext,
{
chan_open_ack::validate(ctx_a, &msg)?;
let module = ctx_a
.get_route(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
module.on_chan_open_ack_validate(
&msg.port_id_on_a,
&msg.chan_id_on_a,
&msg.version_on_b,
)?;
Ok(())
}
fn chan_open_ack_execute<ExecCtx>(
ctx_a: &mut ExecCtx,
module_id: ModuleId,
msg: MsgChannelOpenAck,
) -> Result<(), ContextError>
where
ExecCtx: ExecutionContext,
{
let module = ctx_a
.get_route_mut(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
let extras = module.on_chan_open_ack_execute(
&msg.port_id_on_a,
&msg.chan_id_on_a,
&msg.version_on_b,
)?;
let chan_end_on_a =
ctx_a.channel_end(&(msg.port_id_on_a.clone(), msg.chan_id_on_a.clone()))?;
// state changes
{
let port_channel_id_on_a = (msg.port_id_on_a.clone(), msg.chan_id_on_a.clone());
let chan_end_on_a = {
let mut chan_end_on_a = chan_end_on_a.clone();
chan_end_on_a.set_state(State::Open);
chan_end_on_a.set_version(msg.version_on_b.clone());
chan_end_on_a.set_counterparty_channel_id(msg.chan_id_on_b.clone());
chan_end_on_a
};
ctx_a.store_channel(port_channel_id_on_a, chan_end_on_a)?;
}
// emit events and logs
{
ctx_a.log_message("success: channel open ack".to_string());
let core_event = {
let port_id_on_b = chan_end_on_a.counterparty().port_id.clone();
let conn_id_on_a = chan_end_on_a.connection_hops[0].clone();
IbcEvent::OpenAckChannel(OpenAck::new(
msg.port_id_on_a.clone(),
msg.chan_id_on_a.clone(),
port_id_on_b,
msg.chan_id_on_b,
conn_id_on_a,
))
};
ctx_a.emit_ibc_event(core_event);
for module_event in extras.events {
ctx_a.emit_ibc_event(IbcEvent::AppModule(module_event));
}
for log_message in extras.log {
ctx_a.log_message(log_message);
}
}
Ok(())
}
fn chan_open_confirm_validate<ValCtx>(
ctx_b: &ValCtx,
module_id: ModuleId,
msg: MsgChannelOpenConfirm,
) -> Result<(), ContextError>
where
ValCtx: ValidationContext,
{
chan_open_confirm::validate(ctx_b, &msg)?;
let module = ctx_b
.get_route(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
module.on_chan_open_confirm_validate(&msg.port_id_on_b, &msg.chan_id_on_b)?;
Ok(())
}
fn chan_open_confirm_execute<ExecCtx>(
ctx_b: &mut ExecCtx,
module_id: ModuleId,
msg: MsgChannelOpenConfirm,
) -> Result<(), ContextError>
where
ExecCtx: ExecutionContext,
{
let module = ctx_b
.get_route_mut(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
let extras = module.on_chan_open_confirm_execute(&msg.port_id_on_b, &msg.chan_id_on_b)?;
let chan_end_on_b =
ctx_b.channel_end(&(msg.port_id_on_b.clone(), msg.chan_id_on_b.clone()))?;
// state changes
{
let port_channel_id_on_b = (msg.port_id_on_b.clone(), msg.chan_id_on_b.clone());
let chan_end_on_b = {
let mut chan_end_on_b = chan_end_on_b.clone();
chan_end_on_b.set_state(State::Open);
chan_end_on_b
};
ctx_b.store_channel(port_channel_id_on_b, chan_end_on_b)?;
}
// emit events and logs
{
ctx_b.log_message("success: channel open confirm".to_string());
let conn_id_on_b = chan_end_on_b.connection_hops[0].clone();
let port_id_on_a = chan_end_on_b.counterparty().port_id.clone();
let chan_id_on_a = chan_end_on_b
.counterparty()
.channel_id
.clone()
.ok_or(ContextError::ChannelError(ChannelError::Other {
description:
"internal error: ChannelEnd doesn't have a counterparty channel id in OpenConfirm"
.to_string(),
}))?;
let core_event = IbcEvent::OpenConfirmChannel(OpenConfirm::new(
msg.port_id_on_b.clone(),
msg.chan_id_on_b.clone(),
port_id_on_a,
chan_id_on_a,
conn_id_on_b,
));
ctx_b.emit_ibc_event(core_event);
for module_event in extras.events {
ctx_b.emit_ibc_event(IbcEvent::AppModule(module_event));
}
for log_message in extras.log {
ctx_b.log_message(log_message);
}
}
Ok(())
}
fn chan_close_init_validate<ValCtx>(
ctx_a: &ValCtx,
module_id: ModuleId,
msg: MsgChannelCloseInit,
) -> Result<(), ContextError>
where
ValCtx: ValidationContext,
{
chan_close_init::validate(ctx_a, &msg)?;
let module = ctx_a
.get_route(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
module.on_chan_close_init_validate(&msg.port_id_on_a, &msg.chan_id_on_a)?;
Ok(())
}
fn chan_close_init_execute<ExecCtx>(
ctx_a: &mut ExecCtx,
module_id: ModuleId,
msg: MsgChannelCloseInit,
) -> Result<(), ContextError>
where
ExecCtx: ExecutionContext,
{
let module = ctx_a
.get_route_mut(&module_id)
.ok_or(ChannelError::RouteNotFound)?;
let extras = module.on_chan_close_init_execute(&msg.port_id_on_a, &msg.chan_id_on_a)?;
let chan_end_on_a =
ctx_a.channel_end(&(msg.port_id_on_a.clone(), msg.chan_id_on_a.clone()))?;
// state changes
{
let chan_end_on_a = {
let mut chan_end_on_a = chan_end_on_a.clone();
chan_end_on_a.set_state(State::Closed);
chan_end_on_a
};
let port_channel_id_on_a = (msg.port_id_on_a.clone(), msg.chan_id_on_a.clone());
ctx_a.store_channel(port_channel_id_on_a, chan_end_on_a)?;
}
// emit events and logs
{
ctx_a.log_message("success: channel close init".to_string());
let core_event = {
let port_id_on_b = chan_end_on_a.counterparty().port_id.clone();
let chan_id_on_b = chan_end_on_a