Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drew.merge upstream #9

Merged
merged 112 commits into from
Jun 23, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
f2c8b88
Fix typo: eror -> error (#6293)
subsocialdev Jun 8, 2020
cc5b3a6
Fix typo: PRORITY -> PRIORITY (#6291)
subsocialdev Jun 8, 2020
e287915
Intent to release rc3 (#6290)
gnunicorn Jun 8, 2020
85cd556
Fix transaction pool & network issues (#6288)
NikVolf Jun 8, 2020
863611e
Use `sign_with` for signing grandpa's outgoing message (#6178)
rakanalh Jun 9, 2020
a8bf260
Revalidation tweak & logging for transaction pool (#6258)
NikVolf Jun 9, 2020
feb334d
Update README.md
gavofyork Jun 9, 2020
1853b9a
Allow adding a prefix to the informant (#6174)
cecton Jun 9, 2020
65fe00b
Transaction pool added missed comment (#6308)
bkchr Jun 9, 2020
a3a5160
Add a test for lots of nodes connecting at the same time (#6247)
tomaka Jun 9, 2020
4b1d862
Introduce frozen indices. (#6307)
gavofyork Jun 9, 2020
6c01b10
new crate sc-light (#6235)
seunlanlege Jun 9, 2020
9c39e2c
Fix ui tests for latest rust stable (#6310)
bkchr Jun 9, 2020
b1038c8
Expose light client. (#6313)
dvc94ch Jun 10, 2020
571cfc1
Fix nits in rpc error display. (#6302)
seerscode Jun 10, 2020
e2a6c3e
"OR gate" for EnsureOrigin (#6237)
shaunxw Jun 10, 2020
69034ef
New CI image (#6223)
TriplEight Jun 10, 2020
a684e83
Add a feature to create automatically a random temporary directory fo…
cecton Jun 10, 2020
f06d5f0
Add a [prefix]_process_start_time_seconds metric (#6315)
tomaka Jun 10, 2020
8aeda51
Make NumberOrHex a common primitive. (#6321)
pepyakin Jun 10, 2020
70cfeff
Avoid self-lookups in Authority Discovery (#6317)
romanb Jun 10, 2020
606c56d
Fix quadratic iterations in transaction pool ready set (#6256)
NikVolf Jun 10, 2020
164fb3b
Find the alive incoming entry on disconnect. (#6320)
romanb Jun 11, 2020
99708c0
Impl Debug and Display for Ss58AddressFormat when compiled with std (…
cecton Jun 11, 2020
0a169d4
transaction-pool: expose blocking api for tx submission (#6325)
andresilva Jun 11, 2020
f893506
Pruned and resubmitted metrics in transaction pool (#6322)
NikVolf Jun 11, 2020
4bd0785
Enable wasmtime on node-template (#6336)
shawntabrizi Jun 11, 2020
75113aa
Adds support for storage parameter types (#6296)
bkchr Jun 11, 2020
883c89a
Basic documentation for Scheduler pallet (#6338)
danforbes Jun 12, 2020
6b45e24
Fix check-line-width CI script (#6326)
athei Jun 12, 2020
0dc6634
client: use appropriate ExecutionContext for initial sync / regular i…
andresilva Jun 12, 2020
384be7e
Fix transaction pool event sending (#6341)
bkchr Jun 12, 2020
afdf5ef
Deprecate FunctionOf and remove its users (#6340)
athei Jun 12, 2020
d735e4d
Add events for balance reserve and unreserve functions (#6330)
joepetrowski Jun 12, 2020
1a31f43
Update contributing guide with new label policy (#6333)
apopiak Jun 13, 2020
7401153
adding a ss58 format for Stafi Network (#6347)
Tore19 Jun 14, 2020
f837c39
add extend_lock for StorageLock (#6323)
wangjj9219 Jun 15, 2020
0db70ea
Introduce in-origin filtering (#6318)
gui1117 Jun 15, 2020
4368fc6
pallet-evm add get(fn) to AccountStorages (#6279)
tgmichel Jun 15, 2020
6907018
Add IPC support (#6348)
Demi-Marie Jun 16, 2020
9e999b2
expose constants of pallet_recovery trait (#6363)
wangjj9219 Jun 16, 2020
b29e467
Impl integrity test for runtime (#6356)
gui1117 Jun 16, 2020
1095920
historical slashing w ocw w adhoc tree creation (#6220)
drahnr Jun 16, 2020
1f536e9
[CI] Auto-label new PRs according to draft status (#6361)
s3krit Jun 16, 2020
6199d86
Split the service initialisation up into seperate functions (#6332)
expenses Jun 16, 2020
54d1c5c
[CI] Add label enforcement (#6365)
s3krit Jun 16, 2020
24cbfc4
vesting: Force Vested Transfer (#6368)
gavofyork Jun 16, 2020
288ead0
client/authority-discovery: Don't add own address to priority group (…
mxinden Jun 16, 2020
74efab4
.gitlab-ci.yml: Run promtool on Prometheus alerting rules (#6344)
mxinden Jun 16, 2020
1823782
Use /dns/ instead of /dns4/ (#6369)
tomaka Jun 16, 2020
02e77d2
add system_dryRun (#6300)
xlc Jun 16, 2020
db8916a
fix BlockAttributes encoding (#6281)
svyatonik Jun 16, 2020
bdae39f
Allow Sudo to do anything (#6375)
gavofyork Jun 17, 2020
17be6fd
Stored call in multisig (#6319)
gavofyork Jun 17, 2020
0c42ced
Fix the broken weight multiplier update function (#6334)
kianenigma Jun 17, 2020
8e1f753
Restrict remove_proxies (#6383)
gavofyork Jun 18, 2020
a2653e8
Remove penalty on duplicate Status message (#6377)
tomaka Jun 18, 2020
d6d688c
`decl_module!` print better error on duplicate reserved keyword (#6384)
bkchr Jun 18, 2020
f8afa52
FixedPointNumber: zero is not positive. (#6385)
shaunxw Jun 18, 2020
b02101e
Allow empty values in the storage (#6364)
arkpar Jun 18, 2020
bd72cb6
Pallet: Atomic Swap (#6349)
sorpaas Jun 18, 2020
81ba3e2
Runtime interface to add support for tracing from wasm (#6381)
mattrutherford Jun 18, 2020
9a5892e
Block packet size limit
arkpar Jun 18, 2020
0bb3001
Revert "Block packet size limit"
arkpar Jun 18, 2020
9402334
Update s3 artifact url (#6399)
ddorgan Jun 18, 2020
44978b9
Increase network buffer sizes even more (#6080)
tomaka Jun 18, 2020
cb83391
Remove pallet-balances from non-dev-deps (#6407)
gnunicorn Jun 18, 2020
9b08492
Babe VRF Signing in keystore (#6225)
rakanalh Jun 18, 2020
caf9fbe
Update `libp2p-ping`. (#6412)
twittner Jun 18, 2020
7a4bd76
Remove --legacy-network-protocol CLI flag (#6411)
tomaka Jun 18, 2020
4f0b601
Scale and increase validator count (#6417)
gavofyork Jun 19, 2020
369f9fc
Expose constants from Proxy Pallet (#6420)
shawntabrizi Jun 19, 2020
31c3e06
.maintain/monitoring: Add alerting rule tests (#6343)
mxinden Jun 19, 2020
31af203
[CI] Label PRs if polkadot companion build fails (#6410)
s3krit Jun 19, 2020
3ca1d91
Print bad mandatory error (#6416)
bkchr Jun 19, 2020
9758376
Track last blocks in informant display (#6429)
bkchr Jun 19, 2020
2bb79cb
Simple Docs for Atomic Swap Pallet (#6434)
danforbes Jun 19, 2020
a2c493d
More descriptive error message when invalid slot duration is used (#6…
cecton Jun 19, 2020
d343bfc
Root origin use no filter by default. Scheduler and Democracy dispatc…
gui1117 Jun 19, 2020
111b628
llow decl-module to have a where clause with trailing comma (#6431)
gui1117 Jun 19, 2020
18707b3
.gitlab-ci.yml: Use promtool from paritytech/tools:latest image (#6425)
mxinden Jun 19, 2020
26aec42
Update sync chain info on own block import (#6424)
bkchr Jun 19, 2020
4c67aee
client/authority-discovery: Compare PeerIds and not Multihashes (#6414)
mxinden Jun 19, 2020
c8c16d1
add network propagated metrics (#6438)
NikVolf Jun 19, 2020
f9d4d30
change (ci): add interruptible to kubernetes jobs (#6441)
TriplEight Jun 19, 2020
9cbda1e
Avoid multisig reentrancy (#6445)
gavofyork Jun 19, 2020
d0ab405
Validate encoding of extrinsics passed to runtime (#6442)
arkpar Jun 19, 2020
8032321
Fix Babe secondary plain slots claiming (#6451)
bkchr Jun 19, 2020
1fae45f
sp-npos-elections should not depend on itself (#6444)
bkchr Jun 20, 2020
6c16d15
Don't autolabel insubstantial PRs 'pleasereview' (#6447)
s3krit Jun 20, 2020
ef2a6c1
change everything to transaction (#6440)
NikVolf Jun 21, 2020
41970e7
node: spawn block authoring and grandpa voter as blocking tasks (#6446)
andresilva Jun 21, 2020
a5bcfed
pallet-atomic-swap: generialized swap action (#6421)
sorpaas Jun 21, 2020
6f86bdd
Fix issues with `Operational` transactions validity and prioritizatio…
tomusdrw Jun 21, 2020
3bf25c2
`pallet-staking`: Expose missing consts (#6456)
bkchr Jun 22, 2020
8329dbd
update collective events docs to be consistent with changes (#6463)
apopiak Jun 22, 2020
94b3812
[CI] Don't tag PRs on companion job cancels (#6470)
s3krit Jun 22, 2020
50eb257
network: remove unused variable (#6460)
andresilva Jun 22, 2020
19826b9
Avoid panic on dropping a `sc_network::service::out_events::Receiver`…
romanb Jun 23, 2020
5a102f7
Implement nested storage transactions (#6269)
athei Jun 23, 2020
fed834c
Optimize offchain worker api by re-using http-client (#6454)
pscott Jun 23, 2020
cf7432a
Remove lingering runtime upgrades (#6476)
shawntabrizi Jun 23, 2020
6221146
impl Debug for sc_service::Configuration (#6400)
cecton Jun 23, 2020
c771821
Fix `sp-api` handling of multiple arguments (#6484)
bkchr Jun 23, 2020
ad7b5ef
Fix the browser node and ensure it doesn't colour the informant outpu…
expenses Jun 23, 2020
8baaa18
bound some missing bound for elevated trait (#6487)
gui1117 Jun 23, 2020
034055a
`pallet-scheduler`: Check that `when` is not in the past (#6480)
bkchr Jun 23, 2020
4c03656
client/network/service: Add primary dimension to connection metrics (…
mxinden Jun 23, 2020
d59281f
Ensure the listen addresses are consistent with the transport (#6436)
cecton Jun 23, 2020
9a9b248
pallet-contracts: migrate to nested storage transaction mechanism (#6…
pepyakin Jun 23, 2020
b1ba3a4
Update lock
drewstone Jun 23, 2020
11682ef
Another upstream merge
drewstone Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
historical slashing w ocw w adhoc tree creation (paritytech#6220)
* draft

* steps

* chore: fmt

* step by step

* more details

* make test public

* refactor: split into on and offchain

* test stab

* tabs my friend

* offchain overlay: split key into prefix and true key

Simplifies inspection and makes key actually unique.

* test: share state

* fix & test

* docs improv

* address review comments

* cleanup test chore

* refactor, abbrev link text

* chore: linewidth

* fix prefix key split fallout

* minor fallout

* minor changes

* addresses review comments

* rename historical.rs -> historical/mod.rs

* avoid shared::* wildcard import

* fix: add missing call to store_session_validator_set_to_offchain

* fix/compile: missing shared:: prefix

* fix/test: flow

* fix/review: Apply suggestions from code review

Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>

* fix/review: more review comment fixes

* fix/review: make ValidatorSet private

* fix/include: core -> sp_core

* fix/review: fallout

* fix/visbility: make them public API

Ref paritytech#6358

* fix/review: review changes fallout - again

Co-authored-by: Bernhard Schuster <bernhard@parity.io>
Co-authored-by: Tomasz Drwięga <tomusdrw@users.noreply.github.com>
  • Loading branch information
3 people authored Jun 16, 2020
commit 10959200b9f9c955a9b869130221aa8bc4642007
7 changes: 6 additions & 1 deletion client/db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,12 @@ pub struct BlockImportOperation<Block: BlockT> {

impl<Block: BlockT> BlockImportOperation<Block> {
fn apply_offchain(&mut self, transaction: &mut Transaction<DbHash>) {
for (key, value_operation) in self.offchain_storage_updates.drain() {
for ((prefix, key), value_operation) in self.offchain_storage_updates.drain() {
let key: Vec<u8> = prefix
.into_iter()
.chain(sp_core::sp_std::iter::once(b'/'))
.chain(key.into_iter())
.collect();
match value_operation {
OffchainOverlayedChange::SetValue(val) => transaction.set_from_vec(columns::OFFCHAIN, &key, val),
OffchainOverlayedChange::Remove => transaction.remove(columns::OFFCHAIN, &key),
Expand Down
6 changes: 4 additions & 2 deletions frame/session/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
serde = { version = "1.0.101", optional = true }
codec = { package = "parity-scale-codec", version = "1.3.0", default-features = false, features = ["derive"] }
sp-core = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/core" }
sp-std = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/std" }
sp-io = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/io" }
sp-runtime = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/runtime" }
sp-session = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/session" }
sp-staking = { version = "2.0.0-rc3", default-features = false, path = "../../primitives/staking" }
Expand All @@ -25,8 +27,6 @@ sp-trie = { version = "2.0.0-rc3", optional = true, default-features = false, pa
impl-trait-for-tuples = "0.1.3"

[dev-dependencies]
sp-core = { version = "2.0.0-rc3", path = "../../primitives/core" }
sp-io ={ version = "2.0.0-rc3", path = "../../primitives/io" }
sp-application-crypto = { version = "2.0.0-rc3", path = "../../primitives/application-crypto" }
lazy_static = "1.4.0"

Expand All @@ -37,7 +37,9 @@ std = [
"serde",
"codec/std",
"sp-std/std",
"sp-io/std",
"frame-support/std",
"sp-core/std",
"sp-runtime/std",
"sp-session/std",
"sp-staking/std",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ use sp_trie::{MemoryDB, Trie, TrieMut, Recorder, EMPTY_PREFIX};
use sp_trie::trie_types::{TrieDBMut, TrieDB};
use super::{SessionIndex, Module as SessionModule};

mod shared;
pub mod offchain;
pub mod onchain;

/// Trait necessary for the historical module.
pub trait Trait: super::Trait {
/// Full identification of the validator.
Expand Down Expand Up @@ -116,6 +120,7 @@ impl<T: Trait, I> crate::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T
where I: SessionManager<T::ValidatorId, T::FullIdentification>
{
fn new_session(new_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {

StoredRange::mutate(|range| {
range.get_or_insert_with(|| (new_index, new_index)).1 = new_index + 1;
});
Expand Down Expand Up @@ -143,18 +148,21 @@ impl<T: Trait, I> crate::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T

new_validators
}

fn start_session(start_index: SessionIndex) {
<I as SessionManager<_, _>>::start_session(start_index)
}

fn end_session(end_index: SessionIndex) {
onchain::store_session_validator_set_to_offchain::<T>(end_index);
<I as SessionManager<_, _>>::end_session(end_index)
}
}

/// A tuple of the validator's ID and their full identification.
pub type IdentificationTuple<T> = (<T as crate::Trait>::ValidatorId, <T as Trait>::FullIdentification);

/// a trie instance for checking and generating proofs.
/// A trie instance for checking and generating proofs.
pub struct ProvingTrie<T: Trait> {
db: MemoryDB<T::Hashing>,
root: T::Hash,
Expand Down Expand Up @@ -250,7 +258,6 @@ impl<T: Trait> ProvingTrie<T> {
.ok()?
.and_then(|raw| <IdentificationTuple<T>>::decode(&mut &*raw).ok())
}

}

impl<T: Trait, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyTypeId, D)>
Expand Down Expand Up @@ -311,9 +318,9 @@ impl<T: Trait, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyTy
}

#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use sp_core::crypto::key_types::DUMMY;
use sp_runtime::key_types::DUMMY;
use sp_runtime::testing::UintAuthorityId;
use crate::mock::{
NEXT_VALIDATORS, force_new_session,
Expand All @@ -323,7 +330,7 @@ mod tests {

type Historical = Module<Test>;

fn new_test_ext() -> sp_io::TestExternalities {
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
crate::GenesisConfig::<Test> {
keys: NEXT_VALIDATORS.with(|l|
Expand Down
263 changes: 263 additions & 0 deletions frame/session/src/historical/offchain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
// This file is part of Substrate.

// Copyright (C) 2019-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Off-chain logic for creating a proof based data provided by on-chain logic.
//!
//! Validator-set extracting an iterator from an off-chain worker stored list containing
//! historical validator-sets.
//! Based on the logic of historical slashing, but the validation is done off-chain.
//! Use [`fn store_current_session_validator_set_to_offchain()`](super::onchain) to store the
//! required data to the offchain validator set.
//! This is used in conjunction with [`ProvingTrie`](super::ProvingTrie) and
//! the off-chain indexing API.

use sp_runtime::{offchain::storage::StorageValueRef, KeyTypeId};
use sp_session::MembershipProof;

use super::super::{Module as SessionModule, SessionIndex};
use super::{IdentificationTuple, ProvingTrie, Trait};

use super::shared;
use sp_std::prelude::*;


/// A set of validators, which was used for a fixed session index.
struct ValidatorSet<T: Trait> {
validator_set: Vec<IdentificationTuple<T>>,
}

impl<T: Trait> ValidatorSet<T> {
/// Load the set of validators for a particular session index from the off-chain storage.
///
/// If none is found or decodable given `prefix` and `session`, it will return `None`.
/// Empty validator sets should only ever exist for genesis blocks.
pub fn load_from_offchain_db(session_index: SessionIndex) -> Option<Self> {
let derived_key = shared::derive_key(shared::PREFIX, session_index);
StorageValueRef::persistent(derived_key.as_ref())
.get::<Vec<(T::ValidatorId, T::FullIdentification)>>()
.flatten()
.map(|validator_set| Self { validator_set })
}

#[inline]
fn len(&self) -> usize {
self.validator_set.len()
}
}

/// Implement conversion into iterator for usage
/// with [ProvingTrie](super::ProvingTrie::generate_for).
impl<T: Trait> sp_std::iter::IntoIterator for ValidatorSet<T> {
type Item = (T::ValidatorId, T::FullIdentification);
type IntoIter = sp_std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.validator_set.into_iter()
}
}

/// Create a proof based on the data available in the off-chain database.
///
/// Based on the yielded `MembershipProof` the implementer may decide what
/// to do, i.e. in case of a failed proof, enqueue a transaction back on
/// chain reflecting that, with all its consequences such as i.e. slashing.
pub fn prove_session_membership<T: Trait, D: AsRef<[u8]>>(
session_index: SessionIndex,
session_key: (KeyTypeId, D),
) -> Option<MembershipProof> {
let validators = ValidatorSet::<T>::load_from_offchain_db(session_index)?;
let count = validators.len() as u32;
let trie = ProvingTrie::<T>::generate_for(validators.into_iter()).ok()?;

let (id, data) = session_key;
trie.prove(id, data.as_ref())
.map(|trie_nodes| MembershipProof {
session: session_index,
trie_nodes,
validator_count: count,
})
}


/// Attempt to prune anything that is older than `first_to_keep` session index.
///
/// Due to re-organisation it could be that the `first_to_keep` might be less
/// than the stored one, in which case the conservative choice is made to keep records
/// up to the one that is the lesser.
pub fn prune_older_than<T: Trait>(first_to_keep: SessionIndex) {
let derived_key = shared::LAST_PRUNE.to_vec();
let entry = StorageValueRef::persistent(derived_key.as_ref());
match entry.mutate(|current: Option<Option<SessionIndex>>| -> Result<_, ()> {
match current {
Some(Some(current)) if current < first_to_keep => Ok(first_to_keep),
// do not move the cursor, if the new one would be behind ours
Some(Some(current)) => Ok(current),
None => Ok(first_to_keep),
// if the storage contains undecodable data, overwrite with current anyways
// which might leak some entries being never purged, but that is acceptable
// in this context
Some(None) => Ok(first_to_keep),
}
}) {
Ok(Ok(new_value)) => {
// on a re-org this is not necessarily true, with the above they might be equal
if new_value < first_to_keep {
for session_index in new_value..first_to_keep {
let derived_key = shared::derive_key(shared::PREFIX, session_index);
let _ = StorageValueRef::persistent(derived_key.as_ref()).clear();
}
}
}
Ok(Err(_)) => {} // failed to store the value calculated with the given closure
Err(_) => {} // failed to calculate the value to store with the given closure
}
}

/// Keep the newest `n` items, and prune all items older than that.
pub fn keep_newest<T: Trait>(n_to_keep: usize) {
let session_index = <SessionModule<T>>::current_index();
let n_to_keep = n_to_keep as SessionIndex;
if n_to_keep < session_index {
prune_older_than::<T>(session_index - n_to_keep)
}
}

#[cfg(test)]
mod tests {
use super::super::{onchain, Module};
use super::*;
use crate::mock::{
force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS,
};
use codec::Encode;
use frame_support::traits::{KeyOwnerProofSystem, OnInitialize};
use sp_core::crypto::key_types::DUMMY;
use sp_core::offchain::{
testing::TestOffchainExt,
OffchainExt,
StorageKind,
};

use sp_runtime::testing::UintAuthorityId;

type Historical = Module<Test>;

pub fn new_test_ext() -> sp_io::TestExternalities {
let mut ext = frame_system::GenesisConfig::default()
.build_storage::<Test>()
.expect("Failed to create test externalities.");

crate::GenesisConfig::<Test> {
keys: NEXT_VALIDATORS.with(|l| {
l.borrow()
.iter()
.cloned()
.map(|i| (i, i, UintAuthorityId(i).into()))
.collect()
}),
}
.assimilate_storage(&mut ext)
.unwrap();


let mut ext = sp_io::TestExternalities::new(ext);

let (offchain, offchain_state) = TestOffchainExt::with_offchain_db(ext.offchain_db());

const ITERATIONS: u32 = 5u32;
let mut seed = [0u8; 32];
seed[0..4].copy_from_slice(&ITERATIONS.to_le_bytes());
offchain_state.write().seed = seed;

ext.register_extension(OffchainExt::new(offchain));
ext
}

#[test]
fn encode_decode_roundtrip() {
use codec::{Decode, Encode};
use super::super::super::Trait as SessionTrait;
use super::super::Trait as HistoricalTrait;

let sample = (
22u32 as <Test as SessionTrait>::ValidatorId,
7_777_777 as <Test as HistoricalTrait>::FullIdentification);

let encoded = sample.encode();
let decoded = Decode::decode(&mut encoded.as_slice()).expect("Must decode");
assert_eq!(sample, decoded);
}

#[test]
fn onchain_to_offchain() {
let mut ext = new_test_ext();

const DATA: &[u8] = &[7,8,9,10,11];
ext.execute_with(|| {
b"alphaomega"[..].using_encoded(|key| sp_io::offchain_index::set(key, DATA));
});

ext.persist_offchain_overlay();

ext.execute_with(|| {
let data =
b"alphaomega"[..].using_encoded(|key| {
sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, key)
});
assert_eq!(data, Some(DATA.to_vec()));
});
}


#[test]
fn historical_proof_offchain() {
let mut ext = new_test_ext();
let encoded_key_1 = UintAuthorityId(1).encode();

ext.execute_with(|| {
set_next_validators(vec![1, 2]);
force_new_session();

System::set_block_number(1);
Session::on_initialize(1);

// "on-chain"
onchain::store_current_session_validator_set_to_offchain::<Test>();
assert_eq!(<SessionModule<Test>>::current_index(), 1);

set_next_validators(vec![7, 8]);

force_new_session();
});

ext.persist_offchain_overlay();

ext.execute_with(|| {


System::set_block_number(2);
Session::on_initialize(2);
assert_eq!(<SessionModule<Test>>::current_index(), 2);

// "off-chain"
let proof = prove_session_membership::<Test, _>(1, (DUMMY, &encoded_key_1));
assert!(proof.is_some());
let proof = proof.expect("Must be Some(Proof)");

assert!(Historical::check_proof((DUMMY, &encoded_key_1[..]), proof.clone()).is_some());
});
}
}
Loading