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
use crate::{
configuration::{self, HostConfiguration},
initializer,
};
use frame_support::{pallet_prelude::*, traits::EnsureOrigin};
use frame_system::pallet_prelude::*;
use primitives::v2::{Id as ParaId, UpwardMessage};
use sp_std::{collections::btree_map::BTreeMap, fmt, marker::PhantomData, mem, prelude::*};
use xcm::latest::Outcome;
pub use pallet::*;
pub const MAX_UPWARD_MESSAGE_SIZE_BOUND: u32 = 50 * 1024;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
pub(crate) mod tests;
pub trait UmpSink {
fn process_upward_message(
origin: ParaId,
msg: &[u8],
max_weight: Weight,
) -> Result<Weight, (MessageId, Weight)>;
}
impl UmpSink for () {
fn process_upward_message(
_: ParaId,
_: &[u8],
_: Weight,
) -> Result<Weight, (MessageId, Weight)> {
Ok(Weight::zero())
}
}
pub type MessageId = [u8; 32];
pub type OverweightIndex = u64;
pub struct XcmSink<XcmExecutor, Config>(PhantomData<(XcmExecutor, Config)>);
fn upward_message_id(data: &[u8]) -> MessageId {
sp_io::hashing::blake2_256(data)
}
impl<XcmExecutor: xcm::latest::ExecuteXcm<C::Call>, C: Config> UmpSink for XcmSink<XcmExecutor, C> {
fn process_upward_message(
origin: ParaId,
mut data: &[u8],
max_weight: Weight,
) -> Result<Weight, (MessageId, Weight)> {
use parity_scale_codec::DecodeLimit;
use xcm::{
latest::{Error as XcmError, Junction, Xcm},
VersionedXcm,
};
let id = upward_message_id(&data[..]);
let maybe_msg_and_weight = VersionedXcm::<C::Call>::decode_all_with_depth_limit(
xcm::MAX_XCM_DECODE_DEPTH,
&mut data,
)
.map(|xcm| {
(
Xcm::<C::Call>::try_from(xcm),
<C as Config>::WeightInfo::process_upward_message(data.len() as u32),
)
});
match maybe_msg_and_weight {
Err(_) => {
Pallet::<C>::deposit_event(Event::InvalidFormat(id));
Ok(Weight::zero())
},
Ok((Err(()), weight_used)) => {
Pallet::<C>::deposit_event(Event::UnsupportedVersion(id));
Ok(weight_used)
},
Ok((Ok(xcm_message), weight_used)) => {
let xcm_junction = Junction::Parachain(origin.into());
let outcome =
XcmExecutor::execute_xcm(xcm_junction, xcm_message, max_weight.ref_time());
match outcome {
Outcome::Error(XcmError::WeightLimitReached(required)) =>
Err((id, Weight::from_ref_time(required))),
outcome => {
let outcome_weight = Weight::from_ref_time(outcome.weight_used());
Pallet::<C>::deposit_event(Event::ExecutedUpward(id, outcome));
Ok(weight_used.saturating_add(outcome_weight))
},
}
},
}
}
}
pub enum AcceptanceCheckErr {
MoreMessagesThanPermitted { sent: u32, permitted: u32 },
MessageSize { idx: u32, msg_size: u32, max_size: u32 },
CapacityExceeded { count: u32, limit: u32 },
TotalSizeExceeded { total_size: u32, limit: u32 },
}
impl fmt::Debug for AcceptanceCheckErr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
AcceptanceCheckErr::MoreMessagesThanPermitted { sent, permitted } => write!(
fmt,
"more upward messages than permitted by config ({} > {})",
sent, permitted,
),
AcceptanceCheckErr::MessageSize { idx, msg_size, max_size } => write!(
fmt,
"upward message idx {} larger than permitted by config ({} > {})",
idx, msg_size, max_size,
),
AcceptanceCheckErr::CapacityExceeded { count, limit } => write!(
fmt,
"the ump queue would have more items than permitted by config ({} > {})",
count, limit,
),
AcceptanceCheckErr::TotalSizeExceeded { total_size, limit } => write!(
fmt,
"the ump queue would have grown past the max size permitted by config ({} > {})",
total_size, limit,
),
}
}
}
pub trait WeightInfo {
fn service_overweight() -> Weight;
fn process_upward_message(s: u32) -> Weight;
fn clean_ump_after_outgoing() -> Weight;
}
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn service_overweight() -> Weight {
Weight::MAX
}
fn process_upward_message(_msg_size: u32) -> Weight {
Weight::MAX
}
fn clean_ump_after_outgoing() -> Weight {
Weight::MAX
}
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + configuration::Config {
type Event: From<Event> + IsType<<Self as frame_system::Config>::Event>;
type UmpSink: UmpSink;
type FirstMessageFactorPercent: Get<u64>;
type ExecuteOverweightOrigin: EnsureOrigin<Self::Origin>;
type WeightInfo: WeightInfo;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event {
InvalidFormat(MessageId),
UnsupportedVersion(MessageId),
ExecutedUpward(MessageId, Outcome),
WeightExhausted(MessageId, Weight, Weight),
UpwardMessagesReceived(ParaId, u32, u32),
OverweightEnqueued(ParaId, MessageId, OverweightIndex, Weight),
OverweightServiced(OverweightIndex, Weight),
}
#[pallet::error]
pub enum Error<T> {
UnknownMessageIndex,
WeightOverLimit,
}
#[pallet::storage]
pub type RelayDispatchQueues<T: Config> =
StorageMap<_, Twox64Concat, ParaId, Vec<UpwardMessage>, ValueQuery>;
#[pallet::storage]
pub type RelayDispatchQueueSize<T: Config> =
StorageMap<_, Twox64Concat, ParaId, (u32, u32), ValueQuery>;
#[pallet::storage]
pub type NeedsDispatch<T: Config> = StorageValue<_, Vec<ParaId>, ValueQuery>;
#[pallet::storage]
pub type NextDispatchRoundStartWith<T: Config> = StorageValue<_, ParaId>;
#[pallet::storage]
pub type Overweight<T: Config> =
StorageMap<_, Twox64Concat, OverweightIndex, (ParaId, Vec<u8>), OptionQuery>;
#[pallet::storage]
pub type OverweightCount<T: Config> = StorageValue<_, OverweightIndex, ValueQuery>;
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(weight_limit.saturating_add(<T as Config>::WeightInfo::service_overweight()))]
pub fn service_overweight(
origin: OriginFor<T>,
index: OverweightIndex,
weight_limit: Weight,
) -> DispatchResultWithPostInfo {
T::ExecuteOverweightOrigin::ensure_origin(origin)?;
let (sender, data) =
Overweight::<T>::get(index).ok_or(Error::<T>::UnknownMessageIndex)?;
let used = T::UmpSink::process_upward_message(sender, &data[..], weight_limit)
.map_err(|_| Error::<T>::WeightOverLimit)?;
Overweight::<T>::remove(index);
Self::deposit_event(Event::OverweightServiced(index, used));
Ok(Some(used.saturating_add(<T as Config>::WeightInfo::service_overweight())).into())
}
}
}
impl<T: Config> Pallet<T> {
pub(crate) fn initializer_initialize(_now: T::BlockNumber) -> Weight {
Weight::zero()
}
pub(crate) fn initializer_finalize() {}
pub(crate) fn initializer_on_new_session(
_notification: &initializer::SessionChangeNotification<T::BlockNumber>,
outgoing_paras: &[ParaId],
) -> Weight {
Self::perform_outgoing_para_cleanup(outgoing_paras)
}
fn perform_outgoing_para_cleanup(outgoing: &[ParaId]) -> Weight {
let mut weight: Weight = Weight::zero();
for outgoing_para in outgoing {
weight = weight.saturating_add(Self::clean_ump_after_outgoing(outgoing_para));
}
weight
}
pub(crate) fn clean_ump_after_outgoing(outgoing_para: &ParaId) -> Weight {
<Self as Store>::RelayDispatchQueueSize::remove(outgoing_para);
<Self as Store>::RelayDispatchQueues::remove(outgoing_para);
<Self as Store>::NeedsDispatch::mutate(|v| {
if let Ok(i) = v.binary_search(outgoing_para) {
v.remove(i);
}
});
<Self as Store>::NextDispatchRoundStartWith::mutate(|v| {
*v = v.filter(|p| p == outgoing_para)
});
<T as Config>::WeightInfo::clean_ump_after_outgoing()
}
pub(crate) fn check_upward_messages(
config: &HostConfiguration<T::BlockNumber>,
para: ParaId,
upward_messages: &[UpwardMessage],
) -> Result<(), AcceptanceCheckErr> {
if upward_messages.len() as u32 > config.max_upward_message_num_per_candidate {
return Err(AcceptanceCheckErr::MoreMessagesThanPermitted {
sent: upward_messages.len() as u32,
permitted: config.max_upward_message_num_per_candidate,
})
}
let (mut para_queue_count, mut para_queue_size) =
<Self as Store>::RelayDispatchQueueSize::get(¶);
for (idx, msg) in upward_messages.into_iter().enumerate() {
let msg_size = msg.len() as u32;
if msg_size > config.max_upward_message_size {
return Err(AcceptanceCheckErr::MessageSize {
idx: idx as u32,
msg_size,
max_size: config.max_upward_message_size,
})
}
para_queue_count += 1;
para_queue_size += msg_size;
}
if para_queue_count > config.max_upward_queue_count {
return Err(AcceptanceCheckErr::CapacityExceeded {
count: para_queue_count,
limit: config.max_upward_queue_count,
})
}
if para_queue_size > config.max_upward_queue_size {
return Err(AcceptanceCheckErr::TotalSizeExceeded {
total_size: para_queue_size,
limit: config.max_upward_queue_size,
})
}
Ok(())
}
pub(crate) fn receive_upward_messages(
para: ParaId,
upward_messages: Vec<UpwardMessage>,
) -> Weight {
let mut weight = Weight::zero();
if !upward_messages.is_empty() {
let (extra_count, extra_size) = upward_messages
.iter()
.fold((0, 0), |(cnt, size), d| (cnt + 1, size + d.len() as u32));
<Self as Store>::RelayDispatchQueues::mutate(¶, |v| {
v.extend(upward_messages.into_iter())
});
<Self as Store>::RelayDispatchQueueSize::mutate(
¶,
|(ref mut cnt, ref mut size)| {
*cnt += extra_count;
*size += extra_size;
},
);
<Self as Store>::NeedsDispatch::mutate(|v| {
if let Err(i) = v.binary_search(¶) {
v.insert(i, para);
}
});
weight += T::DbWeight::get().reads_writes(3, 3);
Self::deposit_event(Event::UpwardMessagesReceived(para, extra_count, extra_size));
}
weight
}
pub(crate) fn process_pending_upward_messages() -> Weight {
let mut weight_used = Weight::zero();
let config = <configuration::Pallet<T>>::config();
let mut cursor = NeedsDispatchCursor::new::<T>();
let mut queue_cache = QueueCache::new();
while let Some(dispatchee) = cursor.peek() {
if weight_used >= config.ump_service_total_weight {
break
}
let max_weight = if weight_used == Weight::zero() {
config.ump_service_total_weight * T::FirstMessageFactorPercent::get() / 100
} else {
config.ump_service_total_weight - weight_used
};
let maybe_next = queue_cache.peek_front::<T>(dispatchee);
if let Some(upward_message) = maybe_next {
match T::UmpSink::process_upward_message(dispatchee, upward_message, max_weight) {
Ok(used) => {
weight_used += used;
let _ = queue_cache.consume_front::<T>(dispatchee);
},
Err((id, required)) => {
if required > config.ump_max_individual_weight {
let upward_message = queue_cache.consume_front::<T>(dispatchee).expect(
"`consume_front` should return the same msg as `peek_front`;\
if we get into this branch then `peek_front` returned `Some`;\
thus `upward_message` cannot be `None`; qed",
);
let index = Self::stash_overweight(dispatchee, upward_message);
Self::deposit_event(Event::OverweightEnqueued(
dispatchee, id, index, required,
));
} else {
Self::deposit_event(Event::WeightExhausted(id, max_weight, required));
break
}
},
}
}
if queue_cache.is_empty::<T>(dispatchee) {
cursor.remove();
} else {
cursor.advance();
}
}
cursor.flush::<T>();
queue_cache.flush::<T>();
weight_used
}
fn stash_overweight(sender: ParaId, upward_message: Vec<u8>) -> OverweightIndex {
let index = <Self as Store>::OverweightCount::mutate(|count| {
let index = *count;
*count += 1;
index
});
<Self as Store>::Overweight::insert(index, (sender, upward_message));
index
}
}
struct QueueCache(BTreeMap<ParaId, QueueCacheEntry>);
struct QueueCacheEntry {
queue: Vec<UpwardMessage>,
total_size: u32,
consumed_count: usize,
consumed_size: usize,
}
impl QueueCache {
fn new() -> Self {
Self(BTreeMap::new())
}
fn ensure_cached<T: Config>(&mut self, para: ParaId) -> &mut QueueCacheEntry {
self.0.entry(para).or_insert_with(|| {
let queue = RelayDispatchQueues::<T>::get(¶);
let (_, total_size) = RelayDispatchQueueSize::<T>::get(¶);
QueueCacheEntry { queue, total_size, consumed_count: 0, consumed_size: 0 }
})
}
fn peek_front<T: Config>(&mut self, para: ParaId) -> Option<&UpwardMessage> {
let entry = self.ensure_cached::<T>(para);
entry.queue.get(entry.consumed_count)
}
fn consume_front<T: Config>(&mut self, para: ParaId) -> Option<UpwardMessage> {
let cache_entry = self.ensure_cached::<T>(para);
match cache_entry.queue.get_mut(cache_entry.consumed_count) {
Some(msg) => {
cache_entry.consumed_count += 1;
cache_entry.consumed_size += msg.len();
Some(mem::take(msg))
},
None => None,
}
}
fn is_empty<T: Config>(&mut self, para: ParaId) -> bool {
let cache_entry = self.ensure_cached::<T>(para);
cache_entry.consumed_count >= cache_entry.queue.len()
}
fn flush<T: Config>(self) {
for (para, entry) in self.0 {
if entry.consumed_count >= entry.queue.len() {
RelayDispatchQueues::<T>::remove(¶);
RelayDispatchQueueSize::<T>::remove(¶);
} else if entry.consumed_count > 0 {
RelayDispatchQueues::<T>::insert(¶, &entry.queue[entry.consumed_count..]);
let count = (entry.queue.len() - entry.consumed_count) as u32;
let size = entry.total_size.saturating_sub(entry.consumed_size as u32);
RelayDispatchQueueSize::<T>::insert(¶, (count, size));
}
}
}
}
#[derive(Debug)]
struct NeedsDispatchCursor {
needs_dispatch: Vec<ParaId>,
index: usize,
}
impl NeedsDispatchCursor {
fn new<T: Config>() -> Self {
let needs_dispatch: Vec<ParaId> = <Pallet<T> as Store>::NeedsDispatch::get();
let start_with = <Pallet<T> as Store>::NextDispatchRoundStartWith::get();
let initial_index = match start_with {
Some(para) => match needs_dispatch.binary_search(¶) {
Ok(found_index) => found_index,
Err(_supposed_index) => {
debug_assert!(false);
0
},
},
None => 0,
};
Self { needs_dispatch, index: initial_index }
}
fn peek(&self) -> Option<ParaId> {
self.needs_dispatch.get(self.index).cloned()
}
fn advance(&mut self) {
if self.needs_dispatch.is_empty() {
return
}
self.index = (self.index + 1) % self.needs_dispatch.len();
}
fn remove(&mut self) {
if self.needs_dispatch.is_empty() {
return
}
let _ = self.needs_dispatch.remove(self.index);
if self.needs_dispatch.get(self.index).is_none() {
self.index = 0;
}
}
fn flush<T: Config>(self) {
let next_one = self.peek();
<Pallet<T> as Store>::NextDispatchRoundStartWith::set(next_one);
<Pallet<T> as Store>::NeedsDispatch::put(self.needs_dispatch);
}
}