This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 379
/
Copy pathtests.rs
executable file
·1313 lines (1220 loc) · 35.2 KB
/
tests.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 2020 Parity Technologies (UK) Ltd.
// This file is part of Cumulus.
// Cumulus 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.
// Cumulus 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 Cumulus. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use codec::Encode;
use cumulus_primitives_core::{
relay_chain::BlockNumber as RelayBlockNumber, AbridgedHrmpChannel, InboundDownwardMessage,
InboundHrmpMessage, PersistedValidationData,
};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use frame_support::{
assert_ok,
dispatch::UnfilteredDispatchable,
inherent::{InherentData, ProvideInherent},
parameter_types,
traits::{OnFinalize, OnInitialize},
weights::Weight,
};
use frame_system::RawOrigin;
use hex_literal::hex;
use relay_chain::HrmpChannelId;
use sp_core::{blake2_256, H256};
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
DispatchErrorWithPostInfo,
};
use sp_std::{collections::vec_deque::VecDeque, num::NonZeroU32};
use sp_version::RuntimeVersion;
use std::cell::RefCell;
use crate as parachain_system;
use crate::consensus_hook::UnincludedSegmentCapacity;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
ParachainSystem: parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned},
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub Version: RuntimeVersion = RuntimeVersion {
spec_name: sp_version::create_runtime_str!("test"),
impl_name: sp_version::create_runtime_str!("system-test"),
authoring_version: 1,
spec_version: 1,
impl_version: 1,
apis: sp_version::create_apis_vec!([]),
transaction_version: 1,
state_version: 1,
};
pub const ParachainId: ParaId = ParaId::new(200);
pub const ReservedXcmpWeight: Weight = Weight::zero();
pub const ReservedDmpWeight: Weight = Weight::zero();
}
impl frame_system::Config for Test {
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type BlockLength = ();
type BlockWeights = ();
type Version = Version;
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BaseCallFilter = frame_support::traits::Everything;
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type SelfParaId = ParachainId;
type OutboundXcmpMessageSource = FromThreadLocal;
type DmpMessageHandler = SaveIntoThreadLocal;
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = SaveIntoThreadLocal;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = AnyRelayNumber;
type ConsensusHook = TestConsensusHook;
}
pub struct FromThreadLocal;
pub struct SaveIntoThreadLocal;
std::thread_local! {
static HANDLED_DMP_MESSAGES: RefCell<Vec<(relay_chain::BlockNumber, Vec<u8>)>> = RefCell::new(Vec::new());
static HANDLED_XCMP_MESSAGES: RefCell<Vec<(ParaId, relay_chain::BlockNumber, Vec<u8>)>> = RefCell::new(Vec::new());
static SENT_MESSAGES: RefCell<Vec<(ParaId, Vec<u8>)>> = RefCell::new(Vec::new());
static CONSENSUS_HOOK: RefCell<Box<dyn Fn(&RelayChainStateProof) -> (Weight, UnincludedSegmentCapacity)>>
= RefCell::new(Box::new(|_| (Weight::zero(), NonZeroU32::new(1).unwrap().into())));
}
pub struct TestConsensusHook;
impl ConsensusHook for TestConsensusHook {
fn on_state_proof(s: &RelayChainStateProof) -> (Weight, UnincludedSegmentCapacity) {
CONSENSUS_HOOK.with(|f| f.borrow_mut()(s))
}
}
fn send_message(dest: ParaId, message: Vec<u8>) {
SENT_MESSAGES.with(|m| m.borrow_mut().push((dest, message)));
}
impl XcmpMessageSource for FromThreadLocal {
fn take_outbound_messages(maximum_channels: usize) -> Vec<(ParaId, Vec<u8>)> {
let mut ids = std::collections::BTreeSet::<ParaId>::new();
let mut taken = 0;
let mut result = Vec::new();
SENT_MESSAGES.with(|ms| {
ms.borrow_mut().retain(|m| {
let status = <Pallet<Test> as GetChannelInfo>::get_channel_status(m.0);
let ready = matches!(status, ChannelStatus::Ready(..));
if ready && !ids.contains(&m.0) && taken < maximum_channels {
ids.insert(m.0);
taken += 1;
result.push(m.clone());
false
} else {
true
}
})
});
result
}
}
impl DmpMessageHandler for SaveIntoThreadLocal {
fn handle_dmp_messages(
iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
_max_weight: Weight,
) -> Weight {
HANDLED_DMP_MESSAGES.with(|m| {
for i in iter {
m.borrow_mut().push(i);
}
Weight::zero()
})
}
}
impl XcmpMessageHandler for SaveIntoThreadLocal {
fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
iter: I,
_max_weight: Weight,
) -> Weight {
HANDLED_XCMP_MESSAGES.with(|m| {
for (sender, sent_at, message) in iter {
m.borrow_mut().push((sender, sent_at, message.to_vec()));
}
Weight::zero()
})
}
}
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
fn new_test_ext() -> sp_io::TestExternalities {
HANDLED_DMP_MESSAGES.with(|m| m.borrow_mut().clear());
HANDLED_XCMP_MESSAGES.with(|m| m.borrow_mut().clear());
frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into()
}
struct ReadRuntimeVersion(Vec<u8>);
impl sp_core::traits::ReadRuntimeVersion for ReadRuntimeVersion {
fn read_runtime_version(
&self,
_wasm_code: &[u8],
_ext: &mut dyn sp_externalities::Externalities,
) -> Result<Vec<u8>, String> {
Ok(self.0.clone())
}
}
fn wasm_ext() -> sp_io::TestExternalities {
let version = RuntimeVersion {
spec_name: "test".into(),
spec_version: 2,
impl_version: 1,
..Default::default()
};
let mut ext = new_test_ext();
ext.register_extension(sp_core::traits::ReadRuntimeVersionExt::new(ReadRuntimeVersion(
version.encode(),
)));
ext
}
struct BlockTest {
n: <Test as frame_system::Config>::BlockNumber,
within_block: Box<dyn Fn()>,
after_block: Option<Box<dyn Fn()>>,
}
/// BlockTests exist to test blocks with some setup: we have to assume that
/// `validate_block` will mutate and check storage in certain predictable
/// ways, for example, and we want to always ensure that tests are executed
/// in the context of some particular block number.
#[derive(Default)]
struct BlockTests {
tests: Vec<BlockTest>,
pending_upgrade: Option<RelayChainBlockNumber>,
ran: bool,
relay_sproof_builder_hook:
Option<Box<dyn Fn(&BlockTests, RelayChainBlockNumber, &mut RelayStateSproofBuilder)>>,
inherent_data_hook:
Option<Box<dyn Fn(&BlockTests, RelayChainBlockNumber, &mut ParachainInherentData)>>,
inclusion_delay: Option<usize>,
relay_block_number:
Option<Box<dyn Fn(&<Test as frame_system::Config>::BlockNumber) -> RelayChainBlockNumber>>,
included_para_head: Option<relay_chain::HeadData>,
pending_blocks: VecDeque<relay_chain::HeadData>,
}
impl BlockTests {
fn new() -> BlockTests {
Default::default()
}
fn add_raw(mut self, test: BlockTest) -> Self {
self.tests.push(test);
self
}
fn add<F>(self, n: <Test as frame_system::Config>::BlockNumber, within_block: F) -> Self
where
F: 'static + Fn(),
{
self.add_raw(BlockTest { n, within_block: Box::new(within_block), after_block: None })
}
fn add_with_post_test<F1, F2>(
self,
n: <Test as frame_system::Config>::BlockNumber,
within_block: F1,
after_block: F2,
) -> Self
where
F1: 'static + Fn(),
F2: 'static + Fn(),
{
self.add_raw(BlockTest {
n,
within_block: Box::new(within_block),
after_block: Some(Box::new(after_block)),
})
}
fn with_relay_sproof_builder<F>(mut self, f: F) -> Self
where
F: 'static + Fn(&BlockTests, RelayChainBlockNumber, &mut RelayStateSproofBuilder),
{
self.relay_sproof_builder_hook = Some(Box::new(f));
self
}
fn with_relay_block_number<F>(mut self, f: F) -> Self
where
F: 'static + Fn(&<Test as frame_system::Config>::BlockNumber) -> RelayChainBlockNumber,
{
self.relay_block_number = Some(Box::new(f));
self
}
fn with_inherent_data<F>(mut self, f: F) -> Self
where
F: 'static + Fn(&BlockTests, RelayChainBlockNumber, &mut ParachainInherentData),
{
self.inherent_data_hook = Some(Box::new(f));
self
}
fn with_inclusion_delay(mut self, inclusion_delay: usize) -> Self {
self.inclusion_delay.replace(inclusion_delay);
self
}
fn run(&mut self) {
self.ran = true;
wasm_ext().execute_with(|| {
let mut parent_head_data = {
let header = Header::new_from_number(0);
relay_chain::HeadData(header.encode())
};
self.included_para_head = Some(parent_head_data.clone());
for BlockTest { n, within_block, after_block } in self.tests.iter() {
let relay_parent_number = self
.relay_block_number
.as_ref()
.map(|f| f(n))
.unwrap_or(*n as RelayChainBlockNumber);
// clear pending updates, as applicable
if let Some(upgrade_block) = self.pending_upgrade {
if n >= &upgrade_block.into() {
self.pending_upgrade = None;
}
}
// begin initialization
let parent_hash = BlakeTwo256::hash(&parent_head_data.0);
System::reset_events();
System::initialize(n, &parent_hash, &Default::default());
// now mess with the storage the way validate_block does
let mut sproof_builder = RelayStateSproofBuilder::default();
sproof_builder.included_para_head = self
.included_para_head
.clone()
.unwrap_or_else(|| parent_head_data.clone())
.into();
if let Some(ref hook) = self.relay_sproof_builder_hook {
hook(self, relay_parent_number, &mut sproof_builder);
}
let (relay_parent_storage_root, relay_chain_state) =
sproof_builder.into_state_root_and_proof();
let vfp = PersistedValidationData {
relay_parent_number,
relay_parent_storage_root,
..Default::default()
};
<ValidationData<Test>>::put(&vfp);
NewValidationCode::<Test>::kill();
// It is insufficient to push the validation function params
// to storage; they must also be included in the inherent data.
let inherent_data = {
let mut inherent_data = InherentData::default();
let mut system_inherent_data = ParachainInherentData {
validation_data: vfp.clone(),
relay_chain_state,
downward_messages: Default::default(),
horizontal_messages: Default::default(),
};
if let Some(ref hook) = self.inherent_data_hook {
hook(self, relay_parent_number, &mut system_inherent_data);
}
inherent_data
.put_data(
cumulus_primitives_parachain_inherent::INHERENT_IDENTIFIER,
&system_inherent_data,
)
.expect("failed to put VFP inherent");
inherent_data
};
// execute the block
ParachainSystem::on_initialize(*n);
ParachainSystem::create_inherent(&inherent_data)
.expect("got an inherent")
.dispatch_bypass_filter(RawOrigin::None.into())
.expect("dispatch succeeded");
within_block();
ParachainSystem::on_finalize(*n);
// did block execution set new validation code?
if NewValidationCode::<Test>::exists() && self.pending_upgrade.is_some() {
panic!("attempted to set validation code while upgrade was pending");
}
// clean up
let header = System::finalize();
let head_data = relay_chain::HeadData(header.encode());
parent_head_data = head_data.clone();
match self.inclusion_delay {
Some(delay) if delay > 0 => {
self.pending_blocks.push_back(head_data);
if self.pending_blocks.len() > delay {
let included = self.pending_blocks.pop_front().unwrap();
self.included_para_head.replace(included);
}
},
_ => {
self.included_para_head.replace(head_data);
},
}
if let Some(after_block) = after_block {
after_block();
}
}
});
}
}
impl Drop for BlockTests {
fn drop(&mut self) {
if !self.ran {
self.run();
}
}
}
#[test]
#[should_panic]
fn block_tests_run_on_drop() {
BlockTests::new().add(123, || panic!("if this test passes, block tests run properly"));
}
#[test]
fn unincluded_segment_works() {
CONSENSUS_HOOK.with(|c| {
*c.borrow_mut() = Box::new(|_| (Weight::zero(), NonZeroU32::new(10).unwrap().into()))
});
BlockTests::new()
.with_inclusion_delay(1)
.add_with_post_test(
123,
|| {},
|| {
let segment = <UnincludedSegment<Test>>::get();
assert_eq!(segment.len(), 1);
assert!(<AggregatedUnincludedSegment<Test>>::get().is_some());
},
)
.add_with_post_test(
124,
|| {},
|| {
let segment = <UnincludedSegment<Test>>::get();
assert_eq!(segment.len(), 2);
},
)
.add_with_post_test(
125,
|| {},
|| {
let segment = <UnincludedSegment<Test>>::get();
// Block 123 was popped from the segment, the len is still 2.
assert_eq!(segment.len(), 2);
},
);
}
#[test]
#[should_panic = "no space left for the block in the unincluded segment"]
fn unincluded_segment_is_limited() {
CONSENSUS_HOOK.with(|c| {
*c.borrow_mut() = Box::new(|_| (Weight::zero(), NonZeroU32::new(1).unwrap().into()))
});
BlockTests::new()
.with_inclusion_delay(2)
.add_with_post_test(
123,
|| {},
|| {
let segment = <UnincludedSegment<Test>>::get();
assert_eq!(segment.len(), 1);
assert!(<AggregatedUnincludedSegment<Test>>::get().is_some());
},
)
.add(124, || {}); // The previous block wasn't included yet, should panic in `create_inherent`.
}
#[test]
fn unincluded_code_upgrade_handles_signal() {
CONSENSUS_HOOK.with(|c| {
*c.borrow_mut() = Box::new(|_| (Weight::zero(), NonZeroU32::new(2).unwrap().into()))
});
BlockTests::new()
.with_inclusion_delay(1)
.with_relay_sproof_builder(|_, block_number, builder| {
if block_number > 123 && block_number <= 125 {
builder.upgrade_go_ahead = Some(relay_chain::UpgradeGoAhead::GoAhead);
}
})
.add(123, || {
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
})
.add_with_post_test(
124,
|| {},
|| {
assert!(
!<PendingValidationCode<Test>>::exists(),
"validation function must have been unset"
);
},
)
.add_with_post_test(
125,
|| {
// The signal is present in relay state proof and ignored.
// Block that processed the signal is still not included.
},
|| {
let segment = <UnincludedSegment<Test>>::get();
assert_eq!(segment.len(), 2);
let aggregated_segment =
<AggregatedUnincludedSegment<Test>>::get().expect("segment is non-empty");
assert_eq!(
aggregated_segment.consumed_go_ahead_signal(),
Some(relay_chain::UpgradeGoAhead::GoAhead)
);
},
)
.add_with_post_test(
126,
|| {},
|| {
let aggregated_segment =
<AggregatedUnincludedSegment<Test>>::get().expect("segment is non-empty");
// Block that processed the signal is included.
assert!(aggregated_segment.consumed_go_ahead_signal().is_none());
},
);
}
#[test]
fn unincluded_code_upgrade_scheduled_after_go_ahead() {
CONSENSUS_HOOK.with(|c| {
*c.borrow_mut() = Box::new(|_| (Weight::zero(), NonZeroU32::new(2).unwrap().into()))
});
BlockTests::new()
.with_inclusion_delay(1)
.with_relay_sproof_builder(|_, block_number, builder| {
if block_number > 123 && block_number <= 125 {
builder.upgrade_go_ahead = Some(relay_chain::UpgradeGoAhead::GoAhead);
}
})
.add(123, || {
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
})
.add_with_post_test(
124,
|| {},
|| {
assert!(
!<PendingValidationCode<Test>>::exists(),
"validation function must have been unset"
);
// The previous go-ahead signal was processed, schedule another upgrade.
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
},
)
.add_with_post_test(
125,
|| {
// The signal is present in relay state proof and ignored.
// Block that processed the signal is still not included.
},
|| {
let segment = <UnincludedSegment<Test>>::get();
assert_eq!(segment.len(), 2);
let aggregated_segment =
<AggregatedUnincludedSegment<Test>>::get().expect("segment is non-empty");
assert_eq!(
aggregated_segment.consumed_go_ahead_signal(),
Some(relay_chain::UpgradeGoAhead::GoAhead)
);
},
)
.add_with_post_test(
126,
|| {},
|| {
assert!(<PendingValidationCode<Test>>::exists(), "upgrade is pending");
},
);
}
#[test]
fn inherent_processed_messages_are_ignored() {
CONSENSUS_HOOK.with(|c| {
*c.borrow_mut() = Box::new(|_| (Weight::zero(), NonZeroU32::new(2).unwrap().into()))
});
lazy_static::lazy_static! {
static ref DMQ_MSG: InboundDownwardMessage = InboundDownwardMessage {
sent_at: 3,
msg: b"down".to_vec(),
};
static ref XCMP_MSG_1: InboundHrmpMessage = InboundHrmpMessage {
sent_at: 2,
data: b"h1".to_vec(),
};
static ref XCMP_MSG_2: InboundHrmpMessage = InboundHrmpMessage {
sent_at: 3,
data: b"h2".to_vec(),
};
static ref EXPECTED_PROCESSED_DMQ: Vec<(RelayChainBlockNumber, Vec<u8>)> = vec![
(DMQ_MSG.sent_at, DMQ_MSG.msg.clone())
];
static ref EXPECTED_PROCESSED_XCMP: Vec<(ParaId, RelayChainBlockNumber, Vec<u8>)> = vec![
(ParaId::from(200), XCMP_MSG_1.sent_at, XCMP_MSG_1.data.clone()),
(ParaId::from(200), XCMP_MSG_2.sent_at, XCMP_MSG_2.data.clone()),
];
}
BlockTests::new()
.with_inclusion_delay(1)
.with_relay_block_number(|block_number| 3.max(*block_number as RelayChainBlockNumber))
.with_relay_sproof_builder(|_, relay_block_num, sproof| match relay_block_num {
3 => {
sproof.dmq_mqc_head =
Some(MessageQueueChain::default().extend_downward(&DMQ_MSG).head());
sproof.upsert_inbound_channel(ParaId::from(200)).mqc_head = Some(
MessageQueueChain::default()
.extend_hrmp(&XCMP_MSG_1)
.extend_hrmp(&XCMP_MSG_2)
.head(),
);
},
_ => unreachable!(),
})
.with_inherent_data(|_, relay_block_num, data| match relay_block_num {
3 => {
data.downward_messages.push(DMQ_MSG.clone());
data.horizontal_messages
.insert(ParaId::from(200), vec![XCMP_MSG_1.clone(), XCMP_MSG_2.clone()]);
},
_ => unreachable!(),
})
.add(1, || {
// Don't drop processed messages for this test.
HANDLED_DMP_MESSAGES.with(|m| {
let m = m.borrow();
assert_eq!(&*m, EXPECTED_PROCESSED_DMQ.as_slice());
});
HANDLED_XCMP_MESSAGES.with(|m| {
let m = m.borrow_mut();
assert_eq!(&*m, EXPECTED_PROCESSED_XCMP.as_slice());
});
})
.add(2, || {})
.add(3, || {
HANDLED_DMP_MESSAGES.with(|m| {
let m = m.borrow();
assert_eq!(&*m, EXPECTED_PROCESSED_DMQ.as_slice());
});
HANDLED_XCMP_MESSAGES.with(|m| {
let m = m.borrow_mut();
assert_eq!(&*m, EXPECTED_PROCESSED_XCMP.as_slice());
});
});
}
#[test]
fn events() {
BlockTests::new()
.with_relay_sproof_builder(|_, block_number, builder| {
if block_number > 123 {
builder.upgrade_go_ahead = Some(relay_chain::UpgradeGoAhead::GoAhead);
}
})
.add_with_post_test(
123,
|| {
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
},
|| {
let events = System::events();
assert_eq!(
events[0].event,
RuntimeEvent::ParachainSystem(crate::Event::ValidationFunctionStored)
);
},
)
.add_with_post_test(
1234,
|| {},
|| {
let events = System::events();
assert_eq!(
events[0].event,
RuntimeEvent::ParachainSystem(crate::Event::ValidationFunctionApplied {
relay_chain_block_num: 1234
})
);
},
);
}
#[test]
fn non_overlapping() {
BlockTests::new()
.with_relay_sproof_builder(|_, _, builder| {
builder.host_config.validation_upgrade_delay = 1000;
})
.add(123, || {
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
})
.add(234, || {
assert_eq!(
System::set_code(RawOrigin::Root.into(), Default::default()),
Err(Error::<Test>::OverlappingUpgrades.into()),
)
});
}
#[test]
fn manipulates_storage() {
BlockTests::new()
.with_relay_sproof_builder(|_, block_number, builder| {
if block_number > 123 {
builder.upgrade_go_ahead = Some(relay_chain::UpgradeGoAhead::GoAhead);
}
})
.add(123, || {
assert!(
!<PendingValidationCode<Test>>::exists(),
"validation function must not exist yet"
);
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
assert!(<PendingValidationCode<Test>>::exists(), "validation function must now exist");
})
.add_with_post_test(
1234,
|| {},
|| {
assert!(
!<PendingValidationCode<Test>>::exists(),
"validation function must have been unset"
);
},
);
}
#[test]
fn aborted_upgrade() {
BlockTests::new()
.with_relay_sproof_builder(|_, block_number, builder| {
if block_number > 123 {
builder.upgrade_go_ahead = Some(relay_chain::UpgradeGoAhead::Abort);
}
})
.add(123, || {
assert_ok!(System::set_code(RawOrigin::Root.into(), Default::default()));
})
.add_with_post_test(
1234,
|| {},
|| {
assert!(
!<PendingValidationCode<Test>>::exists(),
"validation function must have been unset"
);
let events = System::events();
assert_eq!(
events[0].event,
RuntimeEvent::ParachainSystem(crate::Event::ValidationFunctionDiscarded)
);
},
);
}
#[test]
fn checks_size() {
BlockTests::new()
.with_relay_sproof_builder(|_, _, builder| {
builder.host_config.max_code_size = 8;
})
.add(123, || {
assert_eq!(
System::set_code(RawOrigin::Root.into(), vec![0; 64]),
Err(Error::<Test>::TooBig.into()),
);
});
}
#[test]
fn send_upward_message_num_per_candidate() {
BlockTests::new()
.with_relay_sproof_builder(|_, _, sproof| {
sproof.host_config.max_upward_message_num_per_candidate = 1;
sproof.relay_dispatch_queue_remaining_capacity = None;
})
.add_with_post_test(
1,
|| {
ParachainSystem::send_upward_message(b"Mr F was here".to_vec()).unwrap();
ParachainSystem::send_upward_message(b"message 2".to_vec()).unwrap();
},
|| {
let v = UpwardMessages::<Test>::get();
assert_eq!(v, vec![b"Mr F was here".to_vec()]);
},
)
.add_with_post_test(
2,
|| {
assert_eq!(UnincludedSegment::<Test>::get().len(), 0);
/* do nothing within block */
},
|| {
let v = UpwardMessages::<Test>::get();
assert_eq!(v, vec![b"message 2".to_vec()]);
},
);
}
#[test]
fn send_upward_message_relay_bottleneck() {
BlockTests::new()
.with_relay_sproof_builder(|_, relay_block_num, sproof| {
sproof.host_config.max_upward_message_num_per_candidate = 2;
sproof.host_config.max_upward_queue_count = 5;
match relay_block_num {
1 => sproof.relay_dispatch_queue_remaining_capacity = Some((0, 2048)),
2 => sproof.relay_dispatch_queue_remaining_capacity = Some((1, 2048)),
_ => unreachable!(),
}
})
.add_with_post_test(
1,
|| {
ParachainSystem::send_upward_message(vec![0u8; 8]).unwrap();
},
|| {
// The message won't be sent because there is already one message in queue.
let v = UpwardMessages::<Test>::get();
assert!(v.is_empty());
},
)
.add_with_post_test(
2,
|| { /* do nothing within block */ },
|| {
let v = UpwardMessages::<Test>::get();
assert_eq!(v, vec![vec![0u8; 8]]);
},
);
}
#[test]
fn send_hrmp_message_buffer_channel_close() {
BlockTests::new()
.with_relay_sproof_builder(|_, relay_block_num, sproof| {
//
// Base case setup
//
sproof.para_id = ParaId::from(200);
sproof.hrmp_egress_channel_index = Some(vec![ParaId::from(300), ParaId::from(400)]);
sproof.hrmp_channels.insert(
HrmpChannelId { sender: ParaId::from(200), recipient: ParaId::from(300) },
AbridgedHrmpChannel {
max_capacity: 1,
msg_count: 1, // <- 1/1 means the channel is full
max_total_size: 1024,
max_message_size: 8,
total_size: 0,
mqc_head: Default::default(),
},
);
sproof.hrmp_channels.insert(
HrmpChannelId { sender: ParaId::from(200), recipient: ParaId::from(400) },
AbridgedHrmpChannel {
max_capacity: 1,
msg_count: 1,
max_total_size: 1024,
max_message_size: 8,
total_size: 0,
mqc_head: Default::default(),
},
);
//
// Adjustment according to block
//
match relay_block_num {
1 => {},
2 => {},
3 => {
// The channel 200->400 ceases to exist at the relay chain block 3
sproof
.hrmp_egress_channel_index
.as_mut()
.unwrap()
.retain(|n| n != &ParaId::from(400));
sproof.hrmp_channels.remove(&HrmpChannelId {
sender: ParaId::from(200),
recipient: ParaId::from(400),
});
// We also free up space for a message in the 200->300 channel.
sproof
.hrmp_channels
.get_mut(&HrmpChannelId {
sender: ParaId::from(200),
recipient: ParaId::from(300),
})
.unwrap()
.msg_count = 0;
},
_ => unreachable!(),
}
})
.add_with_post_test(
1,
|| {
send_message(ParaId::from(300), b"1".to_vec());
send_message(ParaId::from(400), b"2".to_vec());
},
|| {},
)
.add_with_post_test(
2,
|| {},
|| {
// both channels are at capacity so we do not expect any messages.
let v = HrmpOutboundMessages::<Test>::get();
assert!(v.is_empty());
},
)
.add_with_post_test(
3,
|| {},
|| {
let v = HrmpOutboundMessages::<Test>::get();
assert_eq!(
v,
vec![OutboundHrmpMessage { recipient: ParaId::from(300), data: b"1".to_vec() }]
);
},
);
}
#[test]
fn message_queue_chain() {
assert_eq!(MessageQueueChain::default().head(), H256::zero());
// Note that the resulting hashes are the same for HRMP and DMP. That's because even though
// the types are nominally different, they have the same structure and computation of the
// new head doesn't differ.
//
// These cases are taken from https://github.com/paritytech/polkadot/pull/2351
assert_eq!(
MessageQueueChain::default()
.extend_downward(&InboundDownwardMessage { sent_at: 2, msg: vec![1, 2, 3] })
.extend_downward(&InboundDownwardMessage { sent_at: 3, msg: vec![4, 5, 6] })
.head(),
hex!["88dc00db8cc9d22aa62b87807705831f164387dfa49f80a8600ed1cbe1704b6b"].into(),
);
assert_eq!(
MessageQueueChain::default()
.extend_hrmp(&InboundHrmpMessage { sent_at: 2, data: vec![1, 2, 3] })
.extend_hrmp(&InboundHrmpMessage { sent_at: 3, data: vec![4, 5, 6] })
.head(),
hex!["88dc00db8cc9d22aa62b87807705831f164387dfa49f80a8600ed1cbe1704b6b"].into(),
);
}
#[test]
fn receive_dmp() {
lazy_static::lazy_static! {
static ref MSG: InboundDownwardMessage = InboundDownwardMessage {
sent_at: 1,
msg: b"down".to_vec(),
};
}