-
Notifications
You must be signed in to change notification settings - Fork 747
/
hrmp.rs
1825 lines (1637 loc) · 65.1 KB
/
hrmp.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
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::{
configuration::{self, HostConfiguration},
dmp, ensure_parachain, initializer, paras,
};
use frame_support::{pallet_prelude::*, traits::ReservableCurrency, DefaultNoBound};
use frame_system::pallet_prelude::*;
use parity_scale_codec::{Decode, Encode};
use polkadot_parachain_primitives::primitives::{HorizontalMessages, IsSystem};
use primitives::{
Balance, Hash, HrmpChannelId, Id as ParaId, InboundHrmpMessage, OutboundHrmpMessage,
SessionIndex,
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{AccountIdConversion, BlakeTwo256, Hash as HashT, UniqueSaturatedInto, Zero},
ArithmeticError,
};
use sp_std::{
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
fmt, mem,
prelude::*,
};
pub use pallet::*;
/// Maximum bound that can be set for inbound channels.
///
/// If inaccurate, the weighing of this pallet might become inaccurate. It is expected form the
/// `configurations` pallet to check these values before setting
pub const HRMP_MAX_INBOUND_CHANNELS_BOUND: u32 = 128;
/// Same as [`HRMP_MAX_INBOUND_CHANNELS_BOUND`], but for outbound channels.
pub const HRMP_MAX_OUTBOUND_CHANNELS_BOUND: u32 = 128;
#[cfg(test)]
pub(crate) mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub trait WeightInfo {
fn hrmp_init_open_channel() -> Weight;
fn hrmp_accept_open_channel() -> Weight;
fn hrmp_close_channel() -> Weight;
fn force_clean_hrmp(i: u32, e: u32) -> Weight;
fn force_process_hrmp_open(c: u32) -> Weight;
fn force_process_hrmp_close(c: u32) -> Weight;
fn hrmp_cancel_open_request(c: u32) -> Weight;
fn clean_open_channel_requests(c: u32) -> Weight;
fn force_open_hrmp_channel(c: u32) -> Weight;
fn establish_system_channel() -> Weight;
fn poke_channel_deposits() -> Weight;
}
/// A weight info that is only suitable for testing.
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn hrmp_accept_open_channel() -> Weight {
Weight::MAX
}
fn force_clean_hrmp(_: u32, _: u32) -> Weight {
Weight::MAX
}
fn force_process_hrmp_close(_: u32) -> Weight {
Weight::MAX
}
fn force_process_hrmp_open(_: u32) -> Weight {
Weight::MAX
}
fn hrmp_cancel_open_request(_: u32) -> Weight {
Weight::MAX
}
fn hrmp_close_channel() -> Weight {
Weight::MAX
}
fn hrmp_init_open_channel() -> Weight {
Weight::MAX
}
fn clean_open_channel_requests(_: u32) -> Weight {
Weight::MAX
}
fn force_open_hrmp_channel(_: u32) -> Weight {
Weight::MAX
}
fn establish_system_channel() -> Weight {
Weight::MAX
}
fn poke_channel_deposits() -> Weight {
Weight::MAX
}
}
/// A description of a request to open an HRMP channel.
#[derive(Encode, Decode, TypeInfo)]
pub struct HrmpOpenChannelRequest {
/// Indicates if this request was confirmed by the recipient.
pub confirmed: bool,
/// NOTE: this field is deprecated. Channel open requests became non-expiring and this value
/// became unused.
pub _age: SessionIndex,
/// The amount that the sender supplied at the time of creation of this request.
pub sender_deposit: Balance,
/// The maximum message size that could be put into the channel.
pub max_message_size: u32,
/// The maximum number of messages that can be pending in the channel at once.
pub max_capacity: u32,
/// The maximum total size of the messages that can be pending in the channel at once.
pub max_total_size: u32,
}
/// A metadata of an HRMP channel.
#[derive(Encode, Decode, TypeInfo)]
#[cfg_attr(test, derive(Debug))]
pub struct HrmpChannel {
// NOTE: This structure is used by parachains via merkle proofs. Therefore, this struct
// requires special treatment.
//
// A parachain requested this struct can only depend on the subset of this struct.
// Specifically, only a first few fields can be depended upon (See `AbridgedHrmpChannel`).
// These fields cannot be changed without corresponding migration of parachains.
/// The maximum number of messages that can be pending in the channel at once.
pub max_capacity: u32,
/// The maximum total size of the messages that can be pending in the channel at once.
pub max_total_size: u32,
/// The maximum message size that could be put into the channel.
pub max_message_size: u32,
/// The current number of messages pending in the channel.
/// Invariant: should be less or equal to `max_capacity`.s`.
pub msg_count: u32,
/// The total size in bytes of all message payloads in the channel.
/// Invariant: should be less or equal to `max_total_size`.
pub total_size: u32,
/// A head of the Message Queue Chain for this channel. Each link in this chain has a form:
/// `(prev_head, B, H(M))`, where
/// - `prev_head`: is the previous value of `mqc_head` or zero if none.
/// - `B`: is the [relay-chain] block number in which a message was appended
/// - `H(M)`: is the hash of the message being appended.
/// This value is initialized to a special value that consists of all zeroes which indicates
/// that no messages were previously added.
pub mqc_head: Option<Hash>,
/// The amount that the sender supplied as a deposit when opening this channel.
pub sender_deposit: Balance,
/// The amount that the recipient supplied as a deposit when accepting opening this channel.
pub recipient_deposit: Balance,
}
/// An error returned by [`Pallet::check_hrmp_watermark`] that indicates an acceptance criteria
/// check didn't pass.
pub(crate) enum HrmpWatermarkAcceptanceErr<BlockNumber> {
AdvancementRule { new_watermark: BlockNumber, last_watermark: BlockNumber },
AheadRelayParent { new_watermark: BlockNumber, relay_chain_parent_number: BlockNumber },
LandsOnBlockWithNoMessages { new_watermark: BlockNumber },
}
/// An error returned by [`Pallet::check_outbound_hrmp`] that indicates an acceptance criteria check
/// didn't pass.
pub(crate) enum OutboundHrmpAcceptanceErr {
MoreMessagesThanPermitted { sent: u32, permitted: u32 },
NotSorted { idx: u32 },
NoSuchChannel { idx: u32, channel_id: HrmpChannelId },
MaxMessageSizeExceeded { idx: u32, msg_size: u32, max_size: u32 },
TotalSizeExceeded { idx: u32, total_size: u32, limit: u32 },
CapacityExceeded { idx: u32, count: u32, limit: u32 },
}
impl<BlockNumber> fmt::Debug for HrmpWatermarkAcceptanceErr<BlockNumber>
where
BlockNumber: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use HrmpWatermarkAcceptanceErr::*;
match self {
AdvancementRule { new_watermark, last_watermark } => write!(
fmt,
"the HRMP watermark is not advanced relative to the last watermark ({:?} > {:?})",
new_watermark, last_watermark,
),
AheadRelayParent { new_watermark, relay_chain_parent_number } => write!(
fmt,
"the HRMP watermark is ahead the relay-parent ({:?} > {:?})",
new_watermark, relay_chain_parent_number
),
LandsOnBlockWithNoMessages { new_watermark } => write!(
fmt,
"the HRMP watermark ({:?}) doesn't land on a block with messages received",
new_watermark
),
}
}
}
impl fmt::Debug for OutboundHrmpAcceptanceErr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use OutboundHrmpAcceptanceErr::*;
match self {
MoreMessagesThanPermitted { sent, permitted } => write!(
fmt,
"more HRMP messages than permitted by config ({} > {})",
sent, permitted,
),
NotSorted { idx } => {
write!(fmt, "the HRMP messages are not sorted (first unsorted is at index {})", idx,)
},
NoSuchChannel { idx, channel_id } => write!(
fmt,
"the HRMP message at index {} is sent to a non existent channel {:?}->{:?}",
idx, channel_id.sender, channel_id.recipient,
),
MaxMessageSizeExceeded { idx, msg_size, max_size } => write!(
fmt,
"the HRMP message at index {} exceeds the negotiated channel maximum message size ({} > {})",
idx, msg_size, max_size,
),
TotalSizeExceeded { idx, total_size, limit } => write!(
fmt,
"sending the HRMP message at index {} would exceed the neogitiated channel total size ({} > {})",
idx, total_size, limit,
),
CapacityExceeded { idx, count, limit } => write!(
fmt,
"sending the HRMP message at index {} would exceed the neogitiated channel capacity ({} > {})",
idx, count, limit,
),
}
}
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config:
frame_system::Config + configuration::Config + paras::Config + dmp::Config
{
/// The outer event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type RuntimeOrigin: From<crate::Origin>
+ From<<Self as frame_system::Config>::RuntimeOrigin>
+ Into<Result<crate::Origin, <Self as Config>::RuntimeOrigin>>;
/// The origin that can perform "force" actions on channels.
type ChannelManager: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
/// An interface for reserving deposits for opening channels.
///
/// NOTE that this Currency instance will be charged with the amounts defined in the
/// `Configuration` pallet. Specifically, that means that the `Balance` of the `Currency`
/// implementation should be the same as `Balance` as used in the `Configuration`.
type Currency: ReservableCurrency<Self::AccountId>;
/// Something that provides the weight of this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Open HRMP channel requested.
OpenChannelRequested {
sender: ParaId,
recipient: ParaId,
proposed_max_capacity: u32,
proposed_max_message_size: u32,
},
/// An HRMP channel request sent by the receiver was canceled by either party.
OpenChannelCanceled { by_parachain: ParaId, channel_id: HrmpChannelId },
/// Open HRMP channel accepted.
OpenChannelAccepted { sender: ParaId, recipient: ParaId },
/// HRMP channel closed.
ChannelClosed { by_parachain: ParaId, channel_id: HrmpChannelId },
/// An HRMP channel was opened via Root origin.
HrmpChannelForceOpened {
sender: ParaId,
recipient: ParaId,
proposed_max_capacity: u32,
proposed_max_message_size: u32,
},
/// An HRMP channel was opened between two system chains.
HrmpSystemChannelOpened {
sender: ParaId,
recipient: ParaId,
proposed_max_capacity: u32,
proposed_max_message_size: u32,
},
/// An HRMP channel's deposits were updated.
OpenChannelDepositsUpdated { sender: ParaId, recipient: ParaId },
}
#[pallet::error]
pub enum Error<T> {
/// The sender tried to open a channel to themselves.
OpenHrmpChannelToSelf,
/// The recipient is not a valid para.
OpenHrmpChannelInvalidRecipient,
/// The requested capacity is zero.
OpenHrmpChannelZeroCapacity,
/// The requested capacity exceeds the global limit.
OpenHrmpChannelCapacityExceedsLimit,
/// The requested maximum message size is 0.
OpenHrmpChannelZeroMessageSize,
/// The open request requested the message size that exceeds the global limit.
OpenHrmpChannelMessageSizeExceedsLimit,
/// The channel already exists
OpenHrmpChannelAlreadyExists,
/// There is already a request to open the same channel.
OpenHrmpChannelAlreadyRequested,
/// The sender already has the maximum number of allowed outbound channels.
OpenHrmpChannelLimitExceeded,
/// The channel from the sender to the origin doesn't exist.
AcceptHrmpChannelDoesntExist,
/// The channel is already confirmed.
AcceptHrmpChannelAlreadyConfirmed,
/// The recipient already has the maximum number of allowed inbound channels.
AcceptHrmpChannelLimitExceeded,
/// The origin tries to close a channel where it is neither the sender nor the recipient.
CloseHrmpChannelUnauthorized,
/// The channel to be closed doesn't exist.
CloseHrmpChannelDoesntExist,
/// The channel close request is already requested.
CloseHrmpChannelAlreadyUnderway,
/// Canceling is requested by neither the sender nor recipient of the open channel request.
CancelHrmpOpenChannelUnauthorized,
/// The open request doesn't exist.
OpenHrmpChannelDoesntExist,
/// Cannot cancel an HRMP open channel request because it is already confirmed.
OpenHrmpChannelAlreadyConfirmed,
/// The provided witness data is wrong.
WrongWitness,
/// The channel between these two chains cannot be authorized.
ChannelCreationNotAuthorized,
}
/// The set of pending HRMP open channel requests.
///
/// The set is accompanied by a list for iteration.
///
/// Invariant:
/// - There are no channels that exists in list but not in the set and vice versa.
#[pallet::storage]
pub type HrmpOpenChannelRequests<T: Config> =
StorageMap<_, Twox64Concat, HrmpChannelId, HrmpOpenChannelRequest>;
// NOTE: could become bounded, but we don't have a global maximum for this.
// `HRMP_MAX_INBOUND_CHANNELS_BOUND` are per parachain, while this storage tracks the
// global state.
#[pallet::storage]
pub type HrmpOpenChannelRequestsList<T: Config> =
StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
/// This mapping tracks how many open channel requests are initiated by a given sender para.
/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items that has
/// `(X, _)` as the number of `HrmpOpenChannelRequestCount` for `X`.
#[pallet::storage]
pub type HrmpOpenChannelRequestCount<T: Config> =
StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
/// This mapping tracks how many open channel requests were accepted by a given recipient para.
/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items `(_, X)` with
/// `confirmed` set to true, as the number of `HrmpAcceptedChannelRequestCount` for `X`.
#[pallet::storage]
pub type HrmpAcceptedChannelRequestCount<T: Config> =
StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
/// A set of pending HRMP close channel requests that are going to be closed during the session
/// change. Used for checking if a given channel is registered for closure.
///
/// The set is accompanied by a list for iteration.
///
/// Invariant:
/// - There are no channels that exists in list but not in the set and vice versa.
#[pallet::storage]
pub type HrmpCloseChannelRequests<T: Config> = StorageMap<_, Twox64Concat, HrmpChannelId, ()>;
#[pallet::storage]
pub type HrmpCloseChannelRequestsList<T: Config> =
StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
/// The HRMP watermark associated with each para.
/// Invariant:
/// - each para `P` used here as a key should satisfy `Paras::is_valid_para(P)` within a
/// session.
#[pallet::storage]
pub type HrmpWatermarks<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
/// HRMP channel data associated with each para.
/// Invariant:
/// - each participant in the channel should satisfy `Paras::is_valid_para(P)` within a session.
#[pallet::storage]
pub type HrmpChannels<T: Config> = StorageMap<_, Twox64Concat, HrmpChannelId, HrmpChannel>;
/// Ingress/egress indexes allow to find all the senders and receivers given the opposite side.
/// I.e.
///
/// (a) ingress index allows to find all the senders for a given recipient.
/// (b) egress index allows to find all the recipients for a given sender.
///
/// Invariants:
/// - for each ingress index entry for `P` each item `I` in the index should present in
/// `HrmpChannels` as `(I, P)`.
/// - for each egress index entry for `P` each item `E` in the index should present in
/// `HrmpChannels` as `(P, E)`.
/// - there should be no other dangling channels in `HrmpChannels`.
/// - the vectors are sorted.
#[pallet::storage]
pub type HrmpIngressChannelsIndex<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
// the format will require migration of parachains.
#[pallet::storage]
pub type HrmpEgressChannelsIndex<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
/// Storage for the messages for each channel.
/// Invariant: cannot be non-empty if the corresponding channel in `HrmpChannels` is `None`.
#[pallet::storage]
pub type HrmpChannelContents<T: Config> = StorageMap<
_,
Twox64Concat,
HrmpChannelId,
Vec<InboundHrmpMessage<BlockNumberFor<T>>>,
ValueQuery,
>;
/// Maintains a mapping that can be used to answer the question: What paras sent a message at
/// the given block number for a given receiver. Invariants:
/// - The inner `Vec<ParaId>` is never empty.
/// - The inner `Vec<ParaId>` cannot store two same `ParaId`.
/// - The outer vector is sorted ascending by block number and cannot store two items with the
/// same block number.
#[pallet::storage]
pub type HrmpChannelDigests<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<(BlockNumberFor<T>, Vec<ParaId>)>, ValueQuery>;
/// Preopen the given HRMP channels.
///
/// The values in the tuple corresponds to
/// `(sender, recipient, max_capacity, max_message_size)`, i.e. similar to `init_open_channel`.
/// In fact, the initialization is performed as if the `init_open_channel` and
/// `accept_open_channel` were called with the respective parameters and the session change take
/// place.
///
/// As such, each channel initializer should satisfy the same constraints, namely:
///
/// 1. `max_capacity` and `max_message_size` should be within the limits set by the
/// configuration pallet.
/// 2. `sender` and `recipient` must be valid paras.
#[pallet::genesis_config]
#[derive(DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
#[serde(skip)]
_config: sp_std::marker::PhantomData<T>,
preopen_hrmp_channels: Vec<(ParaId, ParaId, u32, u32)>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
initialize_storage::<T>(&self.preopen_hrmp_channels);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Initiate opening a channel from a parachain to a given recipient with given channel
/// parameters.
///
/// - `proposed_max_capacity` - specifies how many messages can be in the channel at once.
/// - `proposed_max_message_size` - specifies the maximum size of the messages.
///
/// These numbers are a subject to the relay-chain configuration limits.
///
/// The channel can be opened only after the recipient confirms it and only on a session
/// change.
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::hrmp_init_open_channel())]
pub fn hrmp_init_open_channel(
origin: OriginFor<T>,
recipient: ParaId,
proposed_max_capacity: u32,
proposed_max_message_size: u32,
) -> DispatchResult {
let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
Self::init_open_channel(
origin,
recipient,
proposed_max_capacity,
proposed_max_message_size,
)?;
Self::deposit_event(Event::OpenChannelRequested {
sender: origin,
recipient,
proposed_max_capacity,
proposed_max_message_size,
});
Ok(())
}
/// Accept a pending open channel request from the given sender.
///
/// The channel will be opened only on the next session boundary.
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::hrmp_accept_open_channel())]
pub fn hrmp_accept_open_channel(origin: OriginFor<T>, sender: ParaId) -> DispatchResult {
let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
Self::accept_open_channel(origin, sender)?;
Self::deposit_event(Event::OpenChannelAccepted { sender, recipient: origin });
Ok(())
}
/// Initiate unilateral closing of a channel. The origin must be either the sender or the
/// recipient in the channel being closed.
///
/// The closure can only happen on a session change.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::hrmp_close_channel())]
pub fn hrmp_close_channel(
origin: OriginFor<T>,
channel_id: HrmpChannelId,
) -> DispatchResult {
let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
Self::close_channel(origin, channel_id.clone())?;
Self::deposit_event(Event::ChannelClosed { by_parachain: origin, channel_id });
Ok(())
}
/// This extrinsic triggers the cleanup of all the HRMP storage items that a para may have.
/// Normally this happens once per session, but this allows you to trigger the cleanup
/// immediately for a specific parachain.
///
/// Number of inbound and outbound channels for `para` must be provided as witness data.
///
/// Origin must be the `ChannelManager`.
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::force_clean_hrmp(*num_inbound, *num_outbound))]
pub fn force_clean_hrmp(
origin: OriginFor<T>,
para: ParaId,
num_inbound: u32,
num_outbound: u32,
) -> DispatchResult {
T::ChannelManager::ensure_origin(origin)?;
ensure!(
HrmpIngressChannelsIndex::<T>::decode_len(para).unwrap_or_default() <=
num_inbound as usize,
Error::<T>::WrongWitness
);
ensure!(
HrmpEgressChannelsIndex::<T>::decode_len(para).unwrap_or_default() <=
num_outbound as usize,
Error::<T>::WrongWitness
);
Self::clean_hrmp_after_outgoing(¶);
Ok(())
}
/// Force process HRMP open channel requests.
///
/// If there are pending HRMP open channel requests, you can use this function to process
/// all of those requests immediately.
///
/// Total number of opening channels must be provided as witness data.
///
/// Origin must be the `ChannelManager`.
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::force_process_hrmp_open(*channels))]
pub fn force_process_hrmp_open(origin: OriginFor<T>, channels: u32) -> DispatchResult {
T::ChannelManager::ensure_origin(origin)?;
ensure!(
HrmpOpenChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
channels,
Error::<T>::WrongWitness
);
let host_config = configuration::Pallet::<T>::config();
Self::process_hrmp_open_channel_requests(&host_config);
Ok(())
}
/// Force process HRMP close channel requests.
///
/// If there are pending HRMP close channel requests, you can use this function to process
/// all of those requests immediately.
///
/// Total number of closing channels must be provided as witness data.
///
/// Origin must be the `ChannelManager`.
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::force_process_hrmp_close(*channels))]
pub fn force_process_hrmp_close(origin: OriginFor<T>, channels: u32) -> DispatchResult {
T::ChannelManager::ensure_origin(origin)?;
ensure!(
HrmpCloseChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
channels,
Error::<T>::WrongWitness
);
Self::process_hrmp_close_channel_requests();
Ok(())
}
/// This cancels a pending open channel request. It can be canceled by either of the sender
/// or the recipient for that request. The origin must be either of those.
///
/// The cancellation happens immediately. It is not possible to cancel the request if it is
/// already accepted.
///
/// Total number of open requests (i.e. `HrmpOpenChannelRequestsList`) must be provided as
/// witness data.
#[pallet::call_index(6)]
#[pallet::weight(<T as Config>::WeightInfo::hrmp_cancel_open_request(*open_requests))]
pub fn hrmp_cancel_open_request(
origin: OriginFor<T>,
channel_id: HrmpChannelId,
open_requests: u32,
) -> DispatchResult {
let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
ensure!(
HrmpOpenChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
open_requests,
Error::<T>::WrongWitness
);
Self::cancel_open_request(origin, channel_id.clone())?;
Self::deposit_event(Event::OpenChannelCanceled { by_parachain: origin, channel_id });
Ok(())
}
/// Open a channel from a `sender` to a `recipient` `ParaId`. Although opened by governance,
/// the `max_capacity` and `max_message_size` are still subject to the Relay Chain's
/// configured limits.
///
/// Expected use is when one (and only one) of the `ParaId`s involved in the channel is
/// governed by the system, e.g. a system parachain.
///
/// Origin must be the `ChannelManager`.
#[pallet::call_index(7)]
#[pallet::weight(<T as Config>::WeightInfo::force_open_hrmp_channel(1))]
pub fn force_open_hrmp_channel(
origin: OriginFor<T>,
sender: ParaId,
recipient: ParaId,
max_capacity: u32,
max_message_size: u32,
) -> DispatchResultWithPostInfo {
T::ChannelManager::ensure_origin(origin)?;
// Guard against a common footgun where someone makes a channel request to a system
// parachain and then makes a proposal to open the channel via governance, which fails
// because `init_open_channel` fails if there is an existing request. This check will
// clear an existing request such that `init_open_channel` should otherwise succeed.
let channel_id = HrmpChannelId { sender, recipient };
let cancel_request: u32 =
if let Some(_open_channel) = HrmpOpenChannelRequests::<T>::get(&channel_id) {
Self::cancel_open_request(sender, channel_id)?;
1
} else {
0
};
// Now we proceed with normal init/accept, except that we set `no_deposit` to true such
// that it will not require deposits from either member.
Self::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
Self::accept_open_channel(recipient, sender)?;
Self::deposit_event(Event::HrmpChannelForceOpened {
sender,
recipient,
proposed_max_capacity: max_capacity,
proposed_max_message_size: max_message_size,
});
Ok(Some(<T as Config>::WeightInfo::force_open_hrmp_channel(cancel_request)).into())
}
/// Establish an HRMP channel between two system chains. If the channel does not already
/// exist, the transaction fees will be refunded to the caller. The system does not take
/// deposits for channels between system chains, and automatically sets the message number
/// and size limits to the maximum allowed by the network's configuration.
///
/// Arguments:
///
/// - `sender`: A system chain, `ParaId`.
/// - `recipient`: A system chain, `ParaId`.
///
/// Any signed origin can call this function, but _both_ inputs MUST be system chains. If
/// the channel does not exist yet, there is no fee.
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::establish_system_channel())]
pub fn establish_system_channel(
origin: OriginFor<T>,
sender: ParaId,
recipient: ParaId,
) -> DispatchResultWithPostInfo {
let _caller = ensure_signed(origin)?;
// both chains must be system
ensure!(
sender.is_system() && recipient.is_system(),
Error::<T>::ChannelCreationNotAuthorized
);
let config = <configuration::Pallet<T>>::config();
let max_message_size = config.hrmp_channel_max_message_size;
let max_capacity = config.hrmp_channel_max_capacity;
Self::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
Self::accept_open_channel(recipient, sender)?;
Self::deposit_event(Event::HrmpSystemChannelOpened {
sender,
recipient,
proposed_max_capacity: max_capacity,
proposed_max_message_size: max_message_size,
});
Ok(Pays::No.into())
}
/// Update the deposits held for an HRMP channel to the latest `Configuration`. Channels
/// with system chains do not require a deposit.
///
/// Arguments:
///
/// - `sender`: A chain, `ParaId`.
/// - `recipient`: A chain, `ParaId`.
///
/// Any signed origin can call this function.
#[pallet::call_index(9)]
#[pallet::weight(<T as Config>::WeightInfo::poke_channel_deposits())]
pub fn poke_channel_deposits(
origin: OriginFor<T>,
sender: ParaId,
recipient: ParaId,
) -> DispatchResult {
let _caller = ensure_signed(origin)?;
let channel_id = HrmpChannelId { sender, recipient };
let is_system = sender.is_system() || recipient.is_system();
let config = <configuration::Pallet<T>>::config();
// Channels with and amongst the system do not require a deposit.
let (new_sender_deposit, new_recipient_deposit) = if is_system {
(0, 0)
} else {
(config.hrmp_sender_deposit, config.hrmp_recipient_deposit)
};
let _ = HrmpChannels::<T>::mutate(&channel_id, |channel| -> DispatchResult {
if let Some(ref mut channel) = channel {
let current_sender_deposit = channel.sender_deposit;
let current_recipient_deposit = channel.recipient_deposit;
// nothing to update
if current_sender_deposit == new_sender_deposit &&
current_recipient_deposit == new_recipient_deposit
{
return Ok(())
}
// sender
if current_sender_deposit > new_sender_deposit {
// Can never underflow, but be paranoid.
let amount = current_sender_deposit
.checked_sub(new_sender_deposit)
.ok_or(ArithmeticError::Underflow)?;
T::Currency::unreserve(
&channel_id.sender.into_account_truncating(),
// The difference should always be convertable into `Balance`, but be
// paranoid and do nothing in case.
amount.try_into().unwrap_or(Zero::zero()),
);
} else if current_sender_deposit < new_sender_deposit {
let amount = new_sender_deposit
.checked_sub(current_sender_deposit)
.ok_or(ArithmeticError::Underflow)?;
T::Currency::reserve(
&channel_id.sender.into_account_truncating(),
amount.try_into().unwrap_or(Zero::zero()),
)?;
}
// recipient
if current_recipient_deposit > new_recipient_deposit {
let amount = current_recipient_deposit
.checked_sub(new_recipient_deposit)
.ok_or(ArithmeticError::Underflow)?;
T::Currency::unreserve(
&channel_id.recipient.into_account_truncating(),
amount.try_into().unwrap_or(Zero::zero()),
);
} else if current_recipient_deposit < new_recipient_deposit {
let amount = new_recipient_deposit
.checked_sub(current_recipient_deposit)
.ok_or(ArithmeticError::Underflow)?;
T::Currency::reserve(
&channel_id.recipient.into_account_truncating(),
amount.try_into().unwrap_or(Zero::zero()),
)?;
}
// update storage
channel.sender_deposit = new_sender_deposit;
channel.recipient_deposit = new_recipient_deposit;
} else {
return Err(Error::<T>::OpenHrmpChannelDoesntExist.into())
}
Ok(())
})?;
Self::deposit_event(Event::OpenChannelDepositsUpdated { sender, recipient });
Ok(())
}
}
}
fn initialize_storage<T: Config>(preopen_hrmp_channels: &[(ParaId, ParaId, u32, u32)]) {
let host_config = configuration::Pallet::<T>::config();
for &(sender, recipient, max_capacity, max_message_size) in preopen_hrmp_channels {
if let Err(err) =
preopen_hrmp_channel::<T>(sender, recipient, max_capacity, max_message_size)
{
panic!("failed to initialize the genesis storage: {:?}", err);
}
}
<Pallet<T>>::process_hrmp_open_channel_requests(&host_config);
}
fn preopen_hrmp_channel<T: Config>(
sender: ParaId,
recipient: ParaId,
max_capacity: u32,
max_message_size: u32,
) -> DispatchResult {
<Pallet<T>>::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
<Pallet<T>>::accept_open_channel(recipient, sender)?;
Ok(())
}
/// Routines and getters related to HRMP.
impl<T: Config> Pallet<T> {
/// Block initialization logic, called by initializer.
pub(crate) fn initializer_initialize(_now: BlockNumberFor<T>) -> Weight {
Weight::zero()
}
/// Block finalization logic, called by initializer.
pub(crate) fn initializer_finalize() {}
/// Called by the initializer to note that a new session has started.
pub(crate) fn initializer_on_new_session(
notification: &initializer::SessionChangeNotification<BlockNumberFor<T>>,
outgoing_paras: &[ParaId],
) -> Weight {
let w1 = Self::perform_outgoing_para_cleanup(¬ification.prev_config, outgoing_paras);
Self::process_hrmp_open_channel_requests(¬ification.prev_config);
Self::process_hrmp_close_channel_requests();
w1.saturating_add(<T as Config>::WeightInfo::force_process_hrmp_open(
outgoing_paras.len() as u32
))
.saturating_add(<T as Config>::WeightInfo::force_process_hrmp_close(
outgoing_paras.len() as u32
))
}
/// Iterate over all paras that were noted for offboarding and remove all the data
/// associated with them.
fn perform_outgoing_para_cleanup(
config: &HostConfiguration<BlockNumberFor<T>>,
outgoing: &[ParaId],
) -> Weight {
let mut w = Self::clean_open_channel_requests(config, outgoing);
for outgoing_para in outgoing {
Self::clean_hrmp_after_outgoing(outgoing_para);
// we need a few extra bits of data to weigh this -- all of this is read internally
// anyways, so no overhead.
let ingress_count =
HrmpIngressChannelsIndex::<T>::decode_len(outgoing_para).unwrap_or_default() as u32;
let egress_count =
HrmpEgressChannelsIndex::<T>::decode_len(outgoing_para).unwrap_or_default() as u32;
w = w.saturating_add(<T as Config>::WeightInfo::force_clean_hrmp(
ingress_count,
egress_count,
));
}
w
}
// Go over the HRMP open channel requests and remove all in which offboarding paras participate.
//
// This will also perform the refunds for the counterparty if it doesn't offboard.
pub(crate) fn clean_open_channel_requests(
config: &HostConfiguration<BlockNumberFor<T>>,
outgoing: &[ParaId],
) -> Weight {
// First collect all the channel ids of the open requests in which there is at least one
// party presents in the outgoing list.
//
// Both the open channel request list and outgoing list are expected to be small enough.
// In the most common case there will be only single outgoing para.
let open_channel_reqs = HrmpOpenChannelRequestsList::<T>::get();
let (go, stay): (Vec<HrmpChannelId>, Vec<HrmpChannelId>) = open_channel_reqs
.into_iter()
.partition(|req_id| outgoing.iter().any(|id| req_id.is_participant(*id)));
HrmpOpenChannelRequestsList::<T>::put(stay);
// Then iterate over all open requests to be removed, pull them out of the set and perform
// the refunds if applicable.
for req_id in go {
let req_data = match HrmpOpenChannelRequests::<T>::take(&req_id) {
Some(req_data) => req_data,
None => {
// Can't normally happen but no need to panic.
continue
},
};
// Return the deposit of the sender, but only if it is not the para being offboarded.
if !outgoing.contains(&req_id.sender) {
T::Currency::unreserve(
&req_id.sender.into_account_truncating(),
req_data.sender_deposit.unique_saturated_into(),
);
}
// If the request was confirmed, then it means it was confirmed in the finished session.
// Therefore, the config's hrmp_recipient_deposit represents the actual value of the
// deposit.
//
// We still want to refund the deposit only if the para is not being offboarded.
if req_data.confirmed {
if !outgoing.contains(&req_id.recipient) {
T::Currency::unreserve(
&req_id.recipient.into_account_truncating(),
config.hrmp_recipient_deposit.unique_saturated_into(),
);
}
Self::decrease_accepted_channel_request_count(req_id.recipient);
}
}
<T as Config>::WeightInfo::clean_open_channel_requests(outgoing.len() as u32)
}
/// Remove all storage entries associated with the given para.
fn clean_hrmp_after_outgoing(outgoing_para: &ParaId) {
HrmpOpenChannelRequestCount::<T>::remove(outgoing_para);
HrmpAcceptedChannelRequestCount::<T>::remove(outgoing_para);
let ingress = HrmpIngressChannelsIndex::<T>::take(outgoing_para)
.into_iter()
.map(|sender| HrmpChannelId { sender, recipient: *outgoing_para });
let egress = HrmpEgressChannelsIndex::<T>::take(outgoing_para)
.into_iter()
.map(|recipient| HrmpChannelId { sender: *outgoing_para, recipient });
let mut to_close = ingress.chain(egress).collect::<Vec<_>>();
to_close.sort();
to_close.dedup();
for channel in to_close {
Self::close_hrmp_channel(&channel);
}
}
/// Iterate over all open channel requests and:
///
/// - prune the stale requests
/// - enact the confirmed requests
fn process_hrmp_open_channel_requests(config: &HostConfiguration<BlockNumberFor<T>>) {
let mut open_req_channels = HrmpOpenChannelRequestsList::<T>::get();
if open_req_channels.is_empty() {
return
}