-
Notifications
You must be signed in to change notification settings - Fork 22
/
lib.rs
1633 lines (1534 loc) · 66.6 KB
/
lib.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
#![cfg_attr(not(feature = "std"), no_std)]
//! # IBC Module
//!
//! This module implements the standard [IBC protocol](https://github.com/cosmos/ics).
//!
//! ## Overview
//!
//! The goal of this pallet is to allow the blockchains built on Substrate to gain the ability to interact with other chains in a trustless way via IBC protocol, no matter what consensus the counterparty chains use.
//!
//! This project is currently in an early stage and will eventually be submitted to upstream.
//!
//! Some components in [IBC spec](https://github.com/cosmos/ics/tree/master/spec) are implemented to support a working demo (https://github.com/cdot-network/ibc-demo), but not fully implemented as the spec yet:
//! * ics-002-client-semantics
//! * ics-003-connection-semantics
//! * ics-004-channel-and-packet-semantics
//! * ics-005-port-allocation
//! * ics-010-grandpa-client
//! * ics-018-relayer-algorithms
//! * ics-025-handler-interface
//! * ics-026-routing-module
//!
//! ### Terminology
//!
//! Please refer to [IBC Terminology](https://github.com/cosmos/ics/blob/master/ibc/1_IBC_TERMINOLOGY.md#1-ibc-terminology).
//!
//! ### Goals
//!
//! This IBC module handles authentication, transport, and ordering of structured data packets relayed between modules on separate machines.
//!
//! Example applications include cross-chain asset transfer, atomic swaps, multi-chain smart contracts (with or without mutually comprehensible VMs), and data & code sharding of various kinds.
//!
//! ## Interface
//!
//! ### Public Functions
//!
//! * `handle_datagram` - Receives datagram transmitted from relayers, and implements the following:
//! + Synchronizing block headers from other chains.
//! + Process connection opening handshakes after its initialization - ICS-003.
//! + Process channel opening handshakes after its initialization - ICS-004.
//! + Handling packet flow after its initialization - ICS-004.
//!
//! ### Dispatchable Functions
//!
//! * `conn_open_init` - Connection opening handshake initialization.
//! * `chan_open_init` - Channel opening handshake initialization.
//! * `send_packet` - Packet flow initialization.
//!
//! ## Usage
//! Please refer to section "How to Interact with the Pallet" in the repository's README.md
use codec::{Decode, Encode};
use finality_grandpa::voter_set::VoterSet;
use frame_support::{
decl_error, decl_event, decl_module, decl_storage, dispatch, ensure, traits::Get,
};
use frame_system::ensure_signed;
use grandpa::justification::GrandpaJustification;
use grandpa::state_machine::read_proof_check;
use ibc;
use sp_core::H256;
use sp_finality_grandpa::{AuthorityList, VersionedAuthorityList, GRANDPA_AUTHORITIES_KEY};
use sp_runtime::{
generic,
traits::{BlakeTwo256, Hash},
OpaqueExtrinsic as UncheckedExtrinsic, RuntimeDebug,
};
use sp_std::{if_std, prelude::*};
use sp_trie::StorageProof;
pub use client::ClientType;
use core::marker::PhantomData;
pub use routing::ModuleCallbacks;
mod client;
pub mod grandpa;
mod handler;
mod header;
pub mod informalsystems;
mod routing;
mod state;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
type BlockNumber = u32;
type Block = generic::Block<generic::Header<BlockNumber, BlakeTwo256>, UncheckedExtrinsic>;
// Todo: Find a crate specific for semantic version
const VERSIONS: [u8; 3] = [1, 3, 5];
// Todo: Find a proper value for MAX_HISTORY_SIZE
const MAX_HISTORY_SIZE: u32 = 3;
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
pub struct Packet {
pub sequence: u64,
/// If the latest block height of the destination chain is greater than ```timeout_height```, the packet will not be processed.
pub timeout_height: u32,
pub source_port: Vec<u8>,
pub source_channel: H256,
pub dest_port: Vec<u8>,
pub dest_channel: H256,
pub data: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
pub enum Datagram {
ClientUpdate {
client_id: H256,
header: grandpa::header::Header,
},
ClientMisbehaviour {
identifier: H256,
evidence: Vec<u8>,
},
ConnOpenTry {
connection_id: H256,
counterparty_connection_id: H256,
counterparty_client_id: H256,
client_id: H256,
version: Vec<u8>, // Todo: remove this field
counterparty_version: Vec<u8>,
proof_init: StorageProof,
proof_consensus: StorageProof,
proof_height: u32,
consensus_height: u32,
},
ConnOpenAck {
connection_id: H256,
counterparty_connection_id: H256,
version: u8,
proof_try: StorageProof,
proof_consensus: StorageProof,
proof_height: u32,
consensus_height: u32,
},
ConnOpenConfirm {
connection_id: H256,
proof_ack: StorageProof,
proof_height: u32,
},
ChanOpenTry {
order: ChannelOrder,
connection_hops: Vec<H256>,
port_id: Vec<u8>,
channel_id: H256,
counterparty_port_id: Vec<u8>,
counterparty_channel_id: H256,
channel_version: Vec<u8>,
counterparty_version: Vec<u8>,
proof_init: StorageProof,
proof_height: u32,
},
ChanOpenAck {
port_id: Vec<u8>,
channel_id: H256,
version: Vec<u8>,
proof_try: StorageProof, // Todo: In ibc-rs, proofs contains `object_proof`, `client_proof`, `consensus_proof` and `height`
proof_height: u32,
},
ChanOpenConfirm {
port_id: Vec<u8>,
channel_id: H256,
proof_ack: StorageProof,
proof_height: u32,
},
PacketRecv {
packet: Packet,
proof: StorageProof,
proof_height: u32,
},
PacketAcknowledgement {
packet: Packet,
acknowledgement: Vec<u8>,
proof: StorageProof,
proof_height: u32,
},
}
#[derive(Clone, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum ConnectionState {
None,
Init,
TryOpen,
Open,
Closed,
}
impl Default for ConnectionState {
fn default() -> Self {
Self::None
}
}
#[derive(Clone, Default, Encode, Decode, RuntimeDebug)]
pub struct ConnectionEnd {
pub state: ConnectionState,
pub counterparty_connection_id: H256,
/// The prefix used for state verification on the counterparty chain associated with this connection.
/// If not specified, a default counterpartyPrefix of "ibc" should be used.
counterparty_prefix: Vec<u8>,
pub client_id: H256,
counterparty_client_id: H256,
pub version: Vec<u8>, // TODO: A ConnectionEnd should only store one version.
}
#[derive(Clone, PartialEq, Encode, Decode, RuntimeDebug)]
pub enum ChannelState {
None,
Init,
TryOpen,
Open,
Closed,
}
impl Default for ChannelState {
fn default() -> Self {
Self::None
}
}
// Todo: In ibc-rs, `ChannelOrder` is type i32
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
pub enum ChannelOrder {
Ordered,
Unordered,
}
impl Default for ChannelOrder {
fn default() -> Self {
Self::Ordered
}
}
#[derive(Clone, Default, Encode, Decode, RuntimeDebug)]
pub struct ChannelEnd {
pub state: ChannelState,
pub ordering: ChannelOrder,
pub counterparty_port_id: Vec<u8>,
pub counterparty_channel_id: H256,
pub connection_hops: Vec<H256>,
pub version: Vec<u8>,
}
/// Configure the pallet by specifying the parameters and types on which it depends.
pub trait Trait: frame_system::Trait {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;
type ModuleCallbacks: routing::ModuleCallbacks;
}
// The pallet's runtime storage items.
// https://substrate.dev/docs/en/knowledgebase/runtime/storage
decl_storage! {
// A unique name is used to ensure that the pallet's storage items are isolated.
// This name may be updated, but each pallet in the runtime must use a unique name.
trait Store for Module<T: Trait> as Ibc {
ClientStatesV2: map hasher(blake2_128_concat) Vec<u8> => Vec<u8>; // client_id => ClientState
ConsensusStatesV2: map hasher(blake2_128_concat) (Vec<u8>, Vec<u8>) => Vec<u8>; // (client_id, height) => ConsensusState
ClientStates: map hasher(blake2_128_concat) H256 => grandpa::client_state::ClientState; // client_id => ClientState
ConsensusStates: map hasher(blake2_128_concat) (H256, u32) => grandpa::consensus_state::ConsensusState; // (client_id, height) => ConsensusState
Connections: map hasher(blake2_128_concat) H256 => ConnectionEnd; // connection_identifier => ConnectionEnd
Ports: map hasher(blake2_128_concat) Vec<u8> => u8; // port_identifier => module_index
/// Channel structures are stored under a store path prefix unique to a combination of a port identifier and channel identifier.
Channels: map hasher(blake2_128_concat) (Vec<u8>, H256) => ChannelEnd; // (port_identifier, channel_identifier) => ChannelEnd
NextSequenceSend: map hasher(blake2_128_concat) (Vec<u8>, H256) => u64; // (port_identifier, channel_identifier) => Sequence
NextSequenceRecv: map hasher(blake2_128_concat) (Vec<u8>, H256) => u64; // (port_identifier, channel_identifier) => Sequence
NextSequenceAck: map hasher(blake2_128_concat) (Vec<u8>, H256) => u64; // (port_identifier, channel_identifier) => Sequence
Packets: map hasher(blake2_128_concat) (Vec<u8>, H256, u64) => H256; // (port_identifier, channel_identifier, sequence) => Hash
Acknowledgements: map hasher(blake2_128_concat) (Vec<u8>, H256, u64) => H256; // (port_identifier, channel_identifier, sequence) => Hash
}
}
// Pallets use events to inform users when important changes are made.
// https://substrate.dev/docs/en/knowledgebase/runtime/events
decl_event!(
pub enum Event<T>
where
AccountId = <T as frame_system::Trait>::AccountId,
{
/// Event documentation should end with an array that provides descriptive names for event
/// parameters. [something, who]
SomethingStored(u32, AccountId),
ClientCreated,
ClientUpdated,
ClientMisbehaviourReceived,
ConnOpenInit,
ConnOpenTry,
ConnOpenAck,
ConnOpenConfirm,
PortBound(u8),
PortReleased,
ChanOpenInit,
ChanOpenTry,
ChanOpenAck,
ChanOpenConfirm,
SendPacket(u64, Vec<u8>, u32, Vec<u8>, H256, Vec<u8>, H256),
RecvPacket(u64, Vec<u8>, u32, Vec<u8>, H256, Vec<u8>, H256, Vec<u8>),
PacketRecvReceived,
AcknowledgePacket,
}
);
// Errors inform users that something went wrong.
decl_error! {
pub enum Error for Module<T: Trait> {
/// The IBC client identifier already exists.
ClientIdExist,
/// The IBC client identifier doesn't exist.
ClientIdNotExist,
/// The IBC port identifier is already binded.
PortIdBinded,
/// The IBC connection identifier already exists.
ConnectionIdExist,
/// The IBC connection identifier doesn't exist.
ConnectionIdNotExist,
/// The IBC channel identifier already exists.
ChannelIdExist,
/// The IBC port identifier doesn't match.
PortIdNotMatch,
/// The IBC connection is closed.
ConnectionClosed,
/// Only allow 1 hop for v1 of the IBC protocol.
OnlyOneHopAllowedV1,
/// The sequence sending packet not match
PackedSequenceNotMatch,
/// The destination channel identifier doesn't match
DestChannelIdNotMatch
}
}
// Dispatchable functions allows users to interact with the pallet and invoke state changes.
// These functions materialize as "extrinsics", which are often compared to transactions.
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
decl_module! {
/// The struct defines the major functions for the module.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// Errors must be initialized if they are used by the pallet.
type Error = Error<T>;
// Events must be initialized if they are used by the pallet.
fn deposit_event() = default;
#[weight = 0]
fn submit_datagram(origin, datagram: Datagram) -> dispatch::DispatchResult {
let _sender = ensure_signed(origin)?;
Self::handle_datagram(datagram)
}
#[weight = 0]
fn deliver(origin, msg: informalsystems::ClientMsg) -> dispatch::DispatchResult {
use tendermint_proto::Protobuf;
use informalsystems::ClientMsg::{CreateClient, UpdateClient};
use ibc::ics02_client::msgs::create_client::MsgCreateAnyClient;
use ibc::ics02_client::msgs::update_client::MsgUpdateAnyClient;
use ibc::ics26_routing::msgs::ICS26Envelope;
use ibc::ics02_client::msgs::ClientMsg;
if_std! {
println!("in deliver");
}
let _sender = ensure_signed(origin)?;
let mut ctx = informalsystems::Context{_pd: PhantomData::<T>, client_ids_counter: 0, connection_ids_counter: 0};
let envelope = match msg {
// ICS2 messages
CreateClient(data) => {
// Pop out the message and then wrap it in the corresponding type
let domain_msg = MsgCreateAnyClient::decode_vec(&*data).unwrap();
ICS26Envelope::ICS2Msg(ClientMsg::CreateClient(domain_msg))
}
UpdateClient(data) => {
let domain_msg = MsgUpdateAnyClient::decode_vec(&*data).unwrap();
ICS26Envelope::ICS2Msg(ClientMsg::UpdateClient(domain_msg))
}
// TODO: ICS3 messages
};
let result = ibc::ics26_routing::handler::dispatch(&mut ctx, envelope);
if_std! {
println!("result: {:?}", result);
}
Ok(())
}
/// An example dispatchable that may throw a custom error.
#[weight = 10_000 + T::DbWeight::get().reads_writes(1,1)]
pub fn cause_error(origin) -> dispatch::DispatchResult {
let _who = ensure_signed(origin)?;
Ok(())
}
}
}
// The main implementation block for the module.
impl<T: Trait> Module<T> {
/// Create an IBC client, by the 2 major steps:
/// * Insert concensus state into storage "ConsensusStates"
/// * Insert client state into storage "ClientStates"
///
/// Both storage's keys contains client id
///
/// # Example
///
/// ```ignore
/// let identifier1 = Blake2Hasher::hash("appia".as_bytes());
/// let identifier2 = Blake2Hasher::hash("flaminia".as_bytes());
/// let height = 0;
/// let consensus_state = ConsensusState {
/// root: Blake2Hasher::hash("root".as_bytes()),
/// height: 0,
/// set_id: 0,
/// authorities: vec![],
/// };
///
/// assert_ok!(IbcModule::create_client(identifier1, ClientType::GRANDPA, height.clone(), consensus_state.clone()));
/// ```
pub fn create_client(
client_id: H256,
client_type: client::ClientType,
height: u32,
consensus_state: grandpa::consensus_state::ConsensusState,
) -> dispatch::DispatchResult {
ensure!(
!ClientStates::contains_key(&client_id),
Error::<T>::ClientIdExist
);
let client_state = match client_type {
ClientType::GRANDPA => {
grandpa::client_state::ClientState::new(client_id.clone(), height)
}
_ => grandpa::client_state::ClientState::new(client_id.clone(), height),
};
ConsensusStates::insert((client_id, height), consensus_state);
ClientStates::insert(&client_id, client_state);
// Todo: Persiste ClientType to substrate storage per ibc-spec
Self::deposit_event(RawEvent::ClientCreated);
Ok(())
}
/// Initialize an IBC connection opening handshake.
/// - Create a conneciton whose state is ```ConnectionState::Init```.
/// - Insert the conneciton to storage ```Connections```.
/// - Manipulate storage ```ClientStates``` by adding the connection id, e.g. Add "appia-connection", to the client id's connection list.
///
/// # Example
///
/// ```ignore
/// let identifier = Blake2Hasher::hash("appia-connection".as_bytes());
/// let desired_counterparty_connection_identifier =
/// Blake2Hasher::hash("flaminia-connection".as_bytes());
/// let client_id =
/// hex::decode("53a954d6a7b1c595e025226e5f2a1782fdea30cd8b0d207ed4cdb040af3bfa10").unwrap();
/// let client_id = H256::from_slice(&client_id);
/// let counterparty_client_id =
/// hex::decode("779ca65108d1d515c3e4bc2e9f6d2f90e27b33b147864d1cd422d9f92ce08e03").unwrap();
/// let counterparty_client_id = H256::from_slice(&counterparty_client_id);
/// conn_open_init(
/// identifier,
/// desired_counterparty_connection_identifier,
/// client_id,
/// counterparty_client_id
/// );
/// ```
pub fn conn_open_init(
connection_id: H256,
counterparty_connection_id: H256,
client_id: H256,
counterparty_client_id: H256,
) -> dispatch::DispatchResult {
// abortTransactionUnless(validateConnectionIdentifier(connection_id))
ensure!(
ClientStates::contains_key(&client_id),
Error::<T>::ClientIdNotExist
);
// TODO: ensure!(!client.connections.exists(&connection_id)))
ensure!(
!Connections::contains_key(&connection_id),
Error::<T>::ConnectionIdExist
);
let connection_end = ConnectionEnd {
state: ConnectionState::Init,
counterparty_connection_id,
counterparty_prefix: vec![],
client_id,
counterparty_client_id,
version: Self::get_compatible_versions(),
};
if_std! {
println!("connection inserted: {:?}", connection_id);
}
Connections::insert(&connection_id, connection_end);
// addConnectionToClient(clientIdentifier, connection_id)
ClientStates::mutate(&client_id, |client_state| {
(*client_state).connections.push(connection_id);
});
Self::deposit_event(RawEvent::ConnOpenInit);
Ok(())
}
/// Allocate a port, which modules can bind to uniquely named ports allocated by the IBC handler.
///
/// As the IBC spec "ics-005-port-allocation": Once a module has bound to a port, no other modules can use that port until the module releases it.
///
/// The restriction is implemented by binding a port to a module's index.
///
/// # Example
/// ```ignore
/// let identifier = "bank".as_bytes().to_vec();
/// let module_index = 45 as u8;
/// bind_port(identifier.clone(), module_index);
/// ```
pub fn bind_port(identifier: Vec<u8>, module_index: u8) -> dispatch::DispatchResult {
// abortTransactionUnless(validatePortIdentifier(id))
ensure!(!Ports::contains_key(&identifier), Error::<T>::PortIdBinded);
Ports::insert(&identifier, module_index);
Self::deposit_event(RawEvent::PortBound(module_index));
Ok(())
}
pub fn release_port(identifier: Vec<u8>, module_index: u8) -> dispatch::DispatchResult {
#![warn(missing_docs)]
ensure!(
Ports::get(&identifier) == module_index,
"Port identifier not found"
);
Ports::remove(&identifier);
Self::deposit_event(RawEvent::PortReleased);
Ok(())
}
/// Initialize an IBC channel opening handshake by:
/// - Save a channel whose state is `ChannelState::Init` to the storage.
/// - Guarantee the order of the packets by setting `NextSequenceSend`, `NextSequenceRecv`, and `NextSequenceAck` in the storage
/// - Manipulate storage ```ClientStates``` by adding the (channel id, port id), e.g. Add "(CHANNEL_ID, PORT_ID)" to the client id's channel list.
///
/// # Example
///
/// ```ignore
/// let module_index = 45 as u8;
/// let order = ChannelOrder::Unordered;
/// let connection_identifier =
/// hex::decode("d93fc49e1b2087234a1e2fc204b500da5d16874e631e761bdab932b37907bd11").unwrap();
/// let connection_identifier = H256::from_slice(&connection_identifier);
/// let connection_hops = vec![connection_identifier];
/// let port_identifier = "bank".as_bytes().to_vec();
/// let channel_identifier = Blake2Hasher::hash(b"appia-channel");
/// let counterparty_port_identifier = "bank".as_bytes().to_vec();
/// let counterparty_channel_identifier = Blake2Hasher::hash(b"flaminia-channel");
/// chan_open_init(
/// module_index,
/// order.clone(),
/// connection_hops.clone(),
/// port_identifier.clone(),
/// channel_identifier,
/// counterparty_port_identifier.clone(),
/// counterparty_channel_identifier,
/// vec![]
/// );
/// ```
pub fn chan_open_init(
module_index: u8,
order: ChannelOrder,
connection_hops: Vec<H256>,
port_id: Vec<u8>,
channel_id: H256,
counterparty_port_id: Vec<u8>,
counterparty_channel_id: H256,
version: Vec<u8>,
) -> dispatch::DispatchResult {
// abortTransactionUnless(validateChannelIdentifier(portIdentifier, channelIdentifier))
ensure!(connection_hops.len() == 1, Error::<T>::OnlyOneHopAllowedV1);
ensure!(
!Channels::contains_key((port_id.clone(), channel_id)),
Error::<T>::ChannelIdExist
);
ensure!(
Connections::contains_key(&connection_hops[0]),
Error::<T>::ConnectionIdNotExist
);
// optimistic channel handshakes are allowed
let connection = Connections::get(&connection_hops[0]);
ensure!(
connection.state != ConnectionState::Closed,
Error::<T>::ConnectionClosed
);
// abortTransactionUnless(authenticate(privateStore.get(portPath(portIdentifier))))
ensure!(
Ports::get(&port_id) == module_index,
Error::<T>::PortIdNotMatch
);
let channel_end = ChannelEnd {
state: ChannelState::Init,
ordering: order,
counterparty_port_id,
counterparty_channel_id: counterparty_channel_id,
connection_hops,
version: vec![],
};
Channels::insert((port_id.clone(), channel_id), channel_end);
// key = generate()
// provableStore.set(channelCapabilityPath(portIdentifier, channelIdentifier), key)
NextSequenceSend::insert((port_id.clone(), channel_id), 1);
NextSequenceRecv::insert((port_id.clone(), channel_id), 1);
NextSequenceAck::insert((port_id.clone(), channel_id), 1);
// return key
ClientStates::mutate(&connection.client_id, |client_state| {
(*client_state).channels.push((port_id.clone(), channel_id));
});
Self::deposit_event(RawEvent::ChanOpenInit);
Ok(())
}
/// Initialize sending packet flow by:
/// - Modify packet sequence by writting to storage `NextSequenceSend`.
/// - Deposit a packet sending event.
///
/// # Example
///
/// ```ignore
/// let sequence = 1;
/// let timeout_height = 1000;
/// let source_port = "bank".as_bytes().to_vec();
/// let source_channel =
/// hex::decode("00e2e14470ed9a017f586dfe6b76bb0871a8c91c3151778de110db3dfcc286ac").unwrap();
/// let source_channel = H256::from_slice(&source_channel);
/// let dest_port = "bank".as_bytes().to_vec();
/// let dest_channel =
/// hex::decode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
/// let dest_channel = H256::from_slice(&dest_channel);
/// let data: Vec<u8> = hex::decode("01020304").unwrap();
///
/// let mut packet = Packet {
/// sequence,
/// timeout_height,
/// source_port,
/// source_channel,
/// dest_port,
/// dest_channel,
/// data,
/// };
/// send_packet(packet.clone());
/// ```
///
pub fn send_packet(packet: Packet) -> dispatch::DispatchResult {
let channel = Channels::get((packet.source_port.clone(), packet.source_channel));
// optimistic sends are permitted once the handshake has started
ensure!(
channel.state != ChannelState::Closed,
"channel has been closed"
);
// abortTransactionUnless(authenticate(privateStore.get(channelCapabilityPath(packet.sourcePort, packet.sourceChannel))))
ensure!(
packet.dest_port == channel.counterparty_port_id,
Error::<T>::PortIdNotMatch
);
ensure!(
packet.dest_channel == channel.counterparty_channel_id,
Error::<T>::DestChannelIdNotMatch
);
let connection = Connections::get(&channel.connection_hops[0]);
ensure!(
connection.state != ConnectionState::Closed,
"connection has been closed"
);
// consensusState = provableStore.get(consensusStatePath(connection.clientIdentifier))
// abortTransactionUnless(consensusState.getHeight() < packet.timeoutHeight)
let mut next_sequence_send =
NextSequenceSend::get((packet.source_port.clone(), packet.source_channel));
ensure!(
packet.sequence == next_sequence_send,
Error::<T>::PackedSequenceNotMatch
);
// all assertions passed, we can alter state
next_sequence_send = next_sequence_send + 1;
NextSequenceSend::insert(
(packet.source_port.clone(), packet.source_channel),
next_sequence_send,
);
let timeout_height = packet.timeout_height.encode();
let hash = BlakeTwo256::hash_of(&[&packet.data[..], &timeout_height[..]].concat());
Packets::insert(
(
packet.source_port.clone(),
packet.source_channel,
packet.sequence,
),
hash,
);
// provableStore.set(packetCommitmentPath(packet.sourcePort, packet.sourceChannel, packet.sequence), hash(packet.data, packet.timeout))
// log that a packet has been sent
Self::deposit_event(RawEvent::SendPacket(
packet.sequence,
packet.data,
packet.timeout_height,
packet.source_port,
packet.source_channel,
packet.dest_port,
packet.dest_channel,
));
Ok(())
}
/// This function handles datagram, transmitted from relayers, for the kinds task below:
/// + Synchronizing block headers from other chains.
/// + After connection opening handshakes are initiated, processing the subsequent handshakes - ICS-003.
/// + After channel opening handshakes are initiated, processing the subsequent handshakes - ICS-004.
/// + After packet flows are initiated, processing the subsequent packet flows - ICS-004.
pub fn handle_datagram(datagram: Datagram) -> dispatch::DispatchResult {
#![warn(missing_doc_code_examples)]
match datagram {
// Receiving the message containing a block header of other chains from relayers, IBC module tryies to synchronize the block header.
Datagram::ClientUpdate { client_id, header } => {
ensure!(ClientStates::contains_key(&client_id), "Client not found");
let client_state = ClientStates::get(&client_id);
ensure!(
client_state.latest_height < header.height,
"Client already updated"
);
ensure!(
ConsensusStates::contains_key((client_id, client_state.latest_height)),
"ConsensusState not found"
);
let consensus_state = ConsensusStates::get((client_id, client_state.latest_height));
// TODO: verify header using validity_predicate
let justification =
GrandpaJustification::<Block>::decode(&mut &*header.justification);
if_std! {
println!(
"consensus_state: {:?}, header: {:?}",
consensus_state,
header,
);
}
let authorities = VoterSet::new(consensus_state.authorities.iter().cloned());
ensure!(authorities.is_some(), "Invalid authorities set");
let authorities = authorities.unwrap();
if let Ok(justification) = justification {
let result = justification.verify(consensus_state.set_id, &authorities);
if_std! {
println!("verify result: {:?}", result);
}
if result.is_ok() {
if_std! {
println!("block_hash: {:?}", header.block_hash);
}
assert_eq!(header.block_hash, justification.commit.target_hash);
ClientStates::mutate(&client_id, |client_state| {
(*client_state).latest_height = header.height;
});
// TODO
let new_consensus_state = grandpa::consensus_state::ConsensusState {
root: header.commitment_root,
height: header.height,
set_id: consensus_state.set_id,
authorities: consensus_state.authorities.clone(),
};
if_std! {
println!(
"consensus_state inserted: {:?}, {}",
client_id,
header.height
);
}
ConsensusStates::insert((client_id, header.height), new_consensus_state);
let result = read_proof_check::<BlakeTwo256>(
header.commitment_root,
header.authorities_proof,
&GRANDPA_AUTHORITIES_KEY.to_vec(),
);
// TODO
let result = result.unwrap().unwrap();
let new_authorities: AuthorityList =
VersionedAuthorityList::decode(&mut &*result)
.unwrap()
.into();
if_std! {
println!("new_authorities: {:?}", new_authorities);
}
if new_authorities != consensus_state.authorities {
ConsensusStates::mutate(
(client_id, header.height),
|consensus_state| {
(*consensus_state).set_id += 1;
(*consensus_state).authorities = new_authorities;
},
);
}
Self::deposit_event(RawEvent::ClientUpdated);
}
}
}
Datagram::ClientMisbehaviour {
identifier,
evidence,
} => {
Self::deposit_event(RawEvent::ClientMisbehaviourReceived);
}
Datagram::ConnOpenTry {
connection_id,
counterparty_connection_id,
counterparty_client_id,
client_id,
version,
counterparty_version,
proof_init,
proof_consensus,
proof_height,
consensus_height,
} => {
let mut new_connection_end;
if Connections::contains_key(&connection_id) {
let old_conn_end = Connections::get(&connection_id);
let state_is_consistent = old_conn_end.state.eq(&ConnectionState::Init)
&& old_conn_end
.counterparty_connection_id
.eq(&counterparty_connection_id)
&& old_conn_end
.counterparty_client_id
.eq(&counterparty_client_id);
ensure!(state_is_consistent, "Local connection corrupted!");
new_connection_end = old_conn_end.clone();
} else {
new_connection_end = ConnectionEnd {
state: ConnectionState::Init,
counterparty_connection_id,
counterparty_prefix: vec![],
client_id,
counterparty_client_id,
version: vec![],
};
}
// abortTransactionUnless(validateConnectionIdentifier(desiredIdentifier))
// abortTransactionUnless(consensusHeight <= getCurrentHeight())
// expectedConsensusState = getConsensusState(consensusHeight)
// expected = ConnectionEnd{INIT, desiredIdentifier, getCommitmentPrefix(), counterpartyClientIdentifier,
// clientIdentifier, counterpartyVersions}
// version = pickVersion(counterpartyVersions)
if_std! {
println!(
"query consensus_state: {:?}, {}",
client_id,
proof_height
);
}
ensure!(
ConsensusStates::contains_key((client_id, proof_height)),
"ConsensusState not found"
);
let value = Self::verify_connection_state(
client_id,
proof_height,
counterparty_connection_id,
proof_init,
);
ensure!(value.is_some(), "verify connection state failed");
// abortTransactionUnless(connection.verifyConnectionState(proofHeight, proofInit, counterpartyConnectionIdentifier, expected))
// abortTransactionUnless(connection.verifyClientConsensusState(proofHeight, proofConsensus, counterpartyClientIdentifier, expectedConsensusState))
// previous = provableStore.get(connectionPath(desiredIdentifier))
// abortTransactionUnless(
// (previous === null) ||
// (previous.state === INIT &&
// previous.counterpartyConnectionIdentifier === counterpartyConnectionIdentifier &&
// previous.counterpartyPrefix === counterpartyPrefix &&
// previous.clientIdentifier === clientIdentifier &&
// previous.counterpartyClientIdentifier === counterpartyClientIdentifier &&
// previous.version === version))
new_connection_end.state = ConnectionState::TryOpen;
// Pick the version.
let local_versions = Self::get_compatible_versions();
let intersection: Vec<u8> = counterparty_version
.iter()
.filter(|cv| local_versions.contains(cv))
.cloned()
.collect();
new_connection_end.version = vec![Self::pick_version(intersection)]; // Todo: change the field `version` in `new_connection_end` to `u8`
let identifier = connection_id;
Connections::insert(&identifier, new_connection_end);
// addConnectionToClient(clientIdentifier, identifier)
ClientStates::mutate(&client_id, |client_state| {
(*client_state).connections.push(identifier);
});
Self::deposit_event(RawEvent::ConnOpenTry);
}
Datagram::ConnOpenAck {
connection_id,
counterparty_connection_id,
version,
proof_try,
proof_consensus,
proof_height,
consensus_height,
} => {
use sp_runtime::traits::SaturatedConversion;
let current_block_number_self =
<frame_system::Module<T>>::block_number().saturated_into::<u32>();
Self::check_client_consensus_height(current_block_number_self, consensus_height);
ensure!(
Connections::contains_key(&connection_id),
"Connection uninitialized"
);
// let mut new_connection_end;
// {
// let old_conn_end = Connections::get(&connection_id);
// let state_is_consistent = old_conn_end.state.eq(&ConnectionState::Init)
// && old_conn_end.version.contains(&version)
// || old_conn_end.state.eq(&ConnectionState::TryOpen)
// && (old_conn_end.version.get(0) == Some(&version));
// // Check that if the msg's counterparty connection id is not empty then it matches
// // the old connection's counterparty.
// // Todo: Ensure connecion id is not empty?
// let counterparty_matches= old_conn_end.counterparty_connection_id == counterparty_connection_id;
// ensure!(state_is_consistent && counterparty_matches, "Connection mismatch!");
// new_connection_end = old_conn_end.clone();
// }
let mut new_connection_end = Connections::get(&connection_id);
// expectedConsensusState = getConsensusState(consensusHeight)
// expected = ConnectionEnd{TRYOPEN, identifier, getCommitmentPrefix(),
// connection.counterpartyClientIdentifier, connection.clientIdentifier,
// version}
ensure!(
ConsensusStates::contains_key((new_connection_end.client_id, proof_height)),
"ConsensusState not found"
);
let value = Self::verify_connection_state(
new_connection_end.client_id,
proof_height,
new_connection_end.counterparty_connection_id,
proof_try,
);
ensure!(value.is_some(), "verify connection state failed");
// abortTransactionUnless(connection.verifyConnectionState(proofHeight, proofTry, connection.counterpartyConnectionIdentifier, expected))
// abortTransactionUnless(connection.verifyClientConsensusState(proofHeight, proofConsensus, connection.counterpartyClientIdentifier, expectedConsensusState))
new_connection_end.version = vec![version];
Connections::mutate(&connection_id, |connection| {
(*connection).state = ConnectionState::Open;
});
// abortTransactionUnless(getCompatibleVersions().indexOf(version) !== -1)
// connection.version = version
// provableStore.set(connectionPath(identifier), connection)
Self::deposit_event(RawEvent::ConnOpenAck);
}
Datagram::ConnOpenConfirm {
connection_id,
proof_ack,
proof_height,
} => {
ensure!(
Connections::contains_key(&connection_id),
"Connection uninitialized"
);
let mut new_connection_end;
{
let old_conn_end = Connections::get(&connection_id);
ensure!(
old_conn_end.state.eq(&ConnectionState::TryOpen),
"Connection mismatch!"
);
new_connection_end = old_conn_end.clone();
}
ensure!(
ConsensusStates::contains_key((new_connection_end.client_id, proof_height)),
"ConsensusState not found"
);
let value = Self::verify_connection_state(
new_connection_end.client_id,
proof_height,
new_connection_end.counterparty_connection_id,
proof_ack,
);