This repository was archived by the owner on Aug 15, 2022. It is now read-only.
forked from paritytech/polkadot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
353 lines (310 loc) · 11.7 KB
/
lib.rs
File metadata and controls
353 lines (310 loc) · 11.7 KB
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
// Copyright 2020 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/>.
#![deny(unused_extern_crates, missing_docs)]
//! Utilities for End to end runtime tests
use test_runner::{
Node, ChainInfo, SignatureVerificationOverride, task_executor,
build_runtime, client_parts, ConfigOrChainSpec,
};
use grandpa::GrandpaBlockImport;
use sc_service::{TFullBackend, TFullClient};
use sp_runtime::generic::Era;
use sc_consensus_babe::BabeBlockImport;
use polkadot_runtime_common::claims;
use sp_runtime::AccountId32;
use support::{weights::Weight, StorageValue};
use democracy::{AccountVote, Conviction, Vote};
use polkadot_runtime::{FastTrackVotingPeriod, Runtime, RuntimeApi, Event, TechnicalCollective, CouncilCollective};
use std::{str::FromStr, future::Future, error::Error};
use codec::Encode;
use sc_consensus_manual_seal::consensus::babe::SlotTimestampProvider;
use sp_runtime::app_crypto::sp_core::H256;
type BlockImport<B, BE, C, SC> = BabeBlockImport<B, C, GrandpaBlockImport<BE, B, C, SC>>;
type Block = polkadot_primitives::v1::Block;
type SelectChain = sc_consensus::LongestChain<TFullBackend<Block>, Block>;
sc_executor::native_executor_instance!(
pub Executor,
polkadot_runtime::api::dispatch,
polkadot_runtime::native_version,
(benchmarking::benchmarking::HostFunctions, SignatureVerificationOverride),
);
/// `ChainInfo` implementation.
pub struct PolkadotChainInfo;
impl ChainInfo for PolkadotChainInfo {
type Block = Block;
type Executor = Executor;
type Runtime = Runtime;
type RuntimeApi = RuntimeApi;
type SelectChain = SelectChain;
type BlockImport = BlockImport<
Self::Block,
TFullBackend<Self::Block>,
TFullClient<Self::Block, RuntimeApi, Self::Executor>,
Self::SelectChain,
>;
type SignedExtras = polkadot_runtime::SignedExtra;
type InherentDataProviders = (SlotTimestampProvider, sp_consensus_babe::inherents::InherentDataProvider);
fn signed_extras(from: <Runtime as system::Config>::AccountId) -> Self::SignedExtras {
(
system::CheckSpecVersion::<Runtime>::new(),
system::CheckTxVersion::<Runtime>::new(),
system::CheckGenesis::<Runtime>::new(),
system::CheckMortality::<Runtime>::from(Era::Immortal),
system::CheckNonce::<Runtime>::from(system::Pallet::<Runtime>::account_nonce(from)),
system::CheckWeight::<Runtime>::new(),
transaction_payment::ChargeTransactionPayment::<Runtime>::from(0),
claims::PrevalidateAttests::<Runtime>::new(),
)
}
}
/// Dispatch with root origin, via pallet-democracy
pub async fn dispatch_with_root<T>(call: impl Into<<T::Runtime as system::Config>::Call>, node: &Node<T>)
-> Result<(), Box<dyn Error>>
where
T: ChainInfo<
Block=Block,
Executor=Executor,
Runtime=Runtime,
RuntimeApi=RuntimeApi,
SelectChain=SelectChain,
BlockImport=BlockImport<
Block,
TFullBackend<Block>,
TFullClient<Block, RuntimeApi, Executor>,
SelectChain,
>,
SignedExtras=polkadot_runtime::SignedExtra
>
{
type DemocracyCall = democracy::Call<Runtime>;
type CouncilCollectiveEvent = collective::Event::<Runtime, CouncilCollective>;
type CouncilCollectiveCall = collective::Call<Runtime, CouncilCollective>;
type TechnicalCollectiveCall = collective::Call<Runtime, TechnicalCollective>;
type TechnicalCollectiveEvent = collective::Event::<Runtime, TechnicalCollective>;
// here lies a black mirror esque copy of on chain whales.
let whales = vec![
"1rvXMZpAj9nKLQkPFCymyH7Fg3ZyKJhJbrc7UtHbTVhJm1A",
"15j4dg5GzsL1bw2U2AWgeyAk6QTxq43V7ZPbXdAmbVLjvDCK",
]
.into_iter()
.map(|account| AccountId32::from_str(account).unwrap())
.collect::<Vec<_>>();
// and these
let (technical_collective, council_collective) = node.with_state(|| (
collective::Members::<Runtime, TechnicalCollective>::get(),
collective::Members::<Runtime, CouncilCollective>::get()
));
// hash of the proposal in democracy
let proposal_hash = {
// note the call (pre-image?) of the call.
node.submit_extrinsic(DemocracyCall::note_preimage(call.into().encode()), whales[0].clone()).await?;
node.seal_blocks(1).await;
// fetch proposal hash from event emitted by the runtime
node.events()
.into_iter()
.filter_map(|event| match event.event {
Event::Democracy(democracy::Event::PreimageNoted(proposal_hash, _, _)) => Some(proposal_hash),
_ => None
})
.next()
.ok_or_else(|| "failed to note pre-image")?
};
// submit external_propose call through council collective
{
let external_propose = DemocracyCall::external_propose_majority(proposal_hash.clone().into());
let length = external_propose.using_encoded(|x| x.len()) as u32 + 1;
let weight = Weight::MAX / 100_000_000;
let proposal = CouncilCollectiveCall::propose(
council_collective.len() as u32,
Box::new(external_propose.clone().into()),
length,
);
node.submit_extrinsic(proposal.clone(), council_collective[0].clone()).await?;
node.seal_blocks(1).await;
// fetch proposal index from event emitted by the runtime
let (index, hash): (u32, H256) = node.events()
.into_iter()
.filter_map(|event| {
match event.event {
Event::Council(CouncilCollectiveEvent::Proposed(_, index, hash, _)) => Some((index, hash)),
_ => None
}
})
.next()
.ok_or_else(|| "failed to execute council::Call::propose(democracy::Call::external_propose_majority)")?;
// vote
for member in &council_collective[1..] {
let call = CouncilCollectiveCall::vote(hash.clone(), index, true);
node.submit_extrinsic(call, member.clone()).await?;
}
node.seal_blocks(1).await;
// close vote
let call = CouncilCollectiveCall::close(hash, index, weight, length);
node.submit_extrinsic(call, council_collective[0].clone()).await?;
node.seal_blocks(1).await;
// assert that proposal has been passed on chain
let events = node.events()
.into_iter()
.filter(|event| {
match event.event {
Event::Council(CouncilCollectiveEvent::Closed(_, _, _)) |
Event::Council(CouncilCollectiveEvent::Approved(_, )) |
Event::Council(CouncilCollectiveEvent::Executed(_, Ok(()))) => true,
_ => false,
}
})
.collect::<Vec<_>>();
// make sure all 3 events are in state
assert_eq!(events.len(), 3);
}
// next technical collective must fast track the proposal.
{
let fast_track = DemocracyCall::fast_track(proposal_hash.into(), FastTrackVotingPeriod::get(), 0);
let weight = Weight::MAX / 100_000_000;
let length = fast_track.using_encoded(|x| x.len()) as u32 + 1;
let proposal = TechnicalCollectiveCall::propose(
technical_collective.len() as u32,
Box::new(fast_track.into()),
length,
);
node.submit_extrinsic(proposal, technical_collective[0].clone()).await?;
node.seal_blocks(1).await;
let (index, hash) = node.events()
.into_iter()
.filter_map(|event| {
match event.event {
Event::TechnicalCommittee(TechnicalCollectiveEvent::Proposed(_, index, hash, _)) => Some((index, hash)),
_ => None
}
})
.next()
.ok_or_else(|| "failed to execute council::Call::propose(democracy::Call::fast_track))")?;
// vote
for member in &technical_collective[1..] {
let call = TechnicalCollectiveCall::vote(hash.clone(), index, true);
node.submit_extrinsic(call, member.clone()).await?;
}
node.seal_blocks(1).await;
// close vote
let call = TechnicalCollectiveCall::close(hash, index, weight, length);
node.submit_extrinsic(call, technical_collective[0].clone()).await?;
node.seal_blocks(1).await;
// assert that fast-track proposal has been passed on chain
let events = node.events()
.into_iter()
.filter(|event| {
match event.event {
Event::TechnicalCommittee(TechnicalCollectiveEvent::Closed(_, _, _)) |
Event::TechnicalCommittee(TechnicalCollectiveEvent::Approved(_)) |
Event::TechnicalCommittee(TechnicalCollectiveEvent::Executed(_, Ok(()))) => true,
_ => false,
}
})
.collect::<Vec<_>>();
// make sure all 3 events are in state
assert_eq!(events.len(), 3);
}
// now runtime upgrade proposal is a fast-tracked referendum we can vote for.
let referendum_index = node.events()
.into_iter()
.filter_map(|event| match event.event {
Event::Democracy(democracy::Event::<Runtime>::Started(index, _)) => Some(index),
_ => None,
})
.next()
.ok_or_else(|| "failed to execute council::Call::close")?;
let call = DemocracyCall::vote(
referendum_index,
AccountVote::Standard {
vote: Vote { aye: true, conviction: Conviction::Locked1x },
// 10 DOTS
balance: 10_000_000_000_000,
},
);
for whale in whales {
node.submit_extrinsic(call.clone(), whale).await?;
}
// wait for fast track period.
node.seal_blocks(FastTrackVotingPeriod::get() as usize).await;
// assert that the proposal is passed by looking at events
let events = node.events()
.into_iter()
.filter(|event| {
match event.event {
Event::Democracy(democracy::Event::Passed(_)) |
Event::Democracy(democracy::Event::PreimageUsed(_, _, _)) |
Event::Democracy(democracy::Event::Executed(_, Ok(()))) => true,
_ => false,
}
})
.collect::<Vec<_>>();
// make sure all events were emitted
assert_eq!(events.len(), 3);
Ok(())
}
/// Runs the test-runner as a binary.
pub fn run<F, Fut>(callback: F) -> Result<(), Box<dyn Error>>
where
F: FnOnce(Node<PolkadotChainInfo>) -> Fut,
Fut: Future<Output=Result<(), Box<dyn Error>>>,
{
use structopt::StructOpt;
use sc_cli::{CliConfiguration, SubstrateCli};
let mut tokio_runtime = build_runtime()?;
let task_executor = task_executor(tokio_runtime.handle().clone());
// parse cli args
let cmd = <polkadot_cli::Cli as StructOpt>::from_args();
// set up logging
let filters = cmd.run.base.log_filters()?;
let logger = sc_tracing::logging::LoggerBuilder::new(filters);
logger.init()?;
// set up the test-runner
let config = cmd.create_configuration(&cmd.run.base, task_executor)?;
sc_cli::print_node_infos::<polkadot_cli::Cli>(&config);
let (rpc, task_manager, client, pool, command_sink, backend) =
client_parts::<PolkadotChainInfo>(ConfigOrChainSpec::Config(config))?;
let node = Node::<PolkadotChainInfo>::new(rpc, task_manager, client, pool, command_sink, backend);
// hand off node.
tokio_runtime.block_on(callback(node))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sp_keyring::sr25519::Keyring::Alice;
use sp_runtime::{MultiSigner, traits::IdentifyAccount};
use polkadot_service::chain_spec::polkadot_development_config;
#[test]
fn test_runner() {
let mut runtime = build_runtime().unwrap();
let task_executor = task_executor(runtime.handle().clone());
let (rpc, task_manager, client, pool, command_sink, backend) =
client_parts::<PolkadotChainInfo>(
ConfigOrChainSpec::ChainSpec(Box::new(polkadot_development_config().unwrap()), task_executor)
).unwrap();
let node = Node::<PolkadotChainInfo>::new(rpc, task_manager, client, pool, command_sink, backend);
runtime.block_on(async {
// seals blocks
node.seal_blocks(1).await;
// submit extrinsics
let alice = MultiSigner::from(Alice.public()).into_account();
node.submit_extrinsic(system::Call::remark((b"hello world").to_vec()), alice)
.await
.unwrap();
// look ma, I can read state.
let _events = node.with_state(|| system::Pallet::<Runtime>::events());
// get access to the underlying client.
let _client = node.client();
});
}
}