Unverified Commit 8cadebb7 authored by Bastian Köcher's avatar Bastian Köcher Committed by GitHub
Browse files

Adds test parachain adder collator (#1864)



* start working on building the real overseer

Unfortunately, this fails to compile right now due to an upstream
failure to compile which is probably brought on by a recent upgrade
to rustc v1.47.

* fill in AllSubsystems internal constructors

* replace fn make_metrics with Metrics::attempt_to_register

* update to account for #1740

* remove Metrics::register, rename Metrics::attempt_to_register

* add 'static bounds to real_overseer type params

* pass authority_discovery and network_service to real_overseer

It's not straightforwardly obvious that this is the best way to handle
the case when there is no authority discovery service, but it seems
to be the best option available at the moment.

* select a proper database configuration for the availability store db

* use subdirectory for av-store database path

* apply Basti's patch which avoids needing to parameterize everything on Block

* simplify path extraction

* get all tests to compile

* Fix Prometheus double-registry error

for debugging purposes, added this to node/subsystem-util/src/lib.rs:472-476:

```rust
Some(registry) => Self::try_register(registry).map_err(|err| {
	eprintln!("PrometheusError calling {}::register: {:?}", std::any::type_name::<Self>(), err);
	err
}),
```

That pointed out where the registration was failing, which led to
this fix. The test still doesn't pass, but it now fails in a new
and different way!

* authorities must have authority discovery, but not necessarily overseer handlers

* fix broken SpawnedSubsystem impls

detailed logging determined that using the `Box::new` style of
future generation, the `self.run` method was never being called,
leading to dropped receivers / closed senders for those subsystems,
causing the overseer to shut down immediately.

This is not the final fix needed to get things working properly,
but it's a good start.

* use prometheus properly

Prometheus lets us register simple counters, which aren't very
interesting. It also allows us to register CounterVecs, which are.
With a CounterVec, you can provide a set of labels, which can
later be used to filter the counts.

We were using them wrong, though. This pattern was repeated in a
variety of places in the code:

```rust
// panics with an cardinality mismatch
let my_counter = register(CounterVec::new(opts, &["succeeded", "failed"])?, registry)?;
my_counter.with_label_values(&["succeeded"]).inc()
```

The problem is that the labels provided in the constructor are not
the set of legal values which can be annotated, but a set of individual
label names which can have individual, arbitrary values.

This commit fixes that.

* get av-store subsystem to actually run properly and not die on first signal

* typo fix: incomming -> incoming

* don't disable authority discovery in test nodes

* Fix rococo-v1 missing session keys

* Update node/core/av-store/Cargo.toml

* try dummying out av-store on non-full-nodes

* overseer and subsystems are required only for full nodes

* Reduce the amount of warnings on browser target

* Fix two more warnings

* InclusionInherent should actually have an Inherent module on rococo

* Ancestry: don't return genesis' parent hash

* Update Cargo.lock

* fix broken test

* update test script: specify chainspec as script argument

* Apply suggestions from code review
Co-authored-by: default avatarBastian Köcher <bkchr@users.noreply.github.com>

* Update node/service/src/lib.rs
Co-authored-by: default avatarBastian Köcher <bkchr@users.noreply.github.com>

* node/service/src/lib: Return error via ? operator

* post-merge blues

* add is_collator flag

* prevent occasional av-store test panic

* simplify fix; expand application

* run authority_discovery in Role::Discover when collating

* distinguish between proposer closed channel errors

* add IsCollator enum, remove is_collator CLI flag

* improve formatting

* remove nop loop

* Fix some stuff

* Adds test parachain adder collator

* Add sudo to Rococo, change session length to 30 seconds and some renaming

* Update to the latest changes on master

* Some fixes

* Fix compilation

* Update parachain/test-parachains/adder/collator/src/lib.rs
Co-authored-by: Sergey Pepyakin's avatarSergei Shulepov <sergei@parity.io>

* Review comments

* Downgrade transaction version

* Fixes

* MOARE

* Register notification protocols

* utils: remove unused error

* av-store: more resilient to some errors

* address review nits

* address more review nits
Co-authored-by: default avatarPeter Goodspeed-Niklaus <peter.r.goodspeedniklaus@gmail.com>
Co-authored-by: Andronik Ordian's avatarAndronik Ordian <write@reusable.software>
Co-authored-by: Fedor Sakharov's avatarFedor Sakharov <fedor.sakharov@gmail.com>
Co-authored-by: default avatarRobert Habermeier <robert@Roberts-MBP.lan1>
Co-authored-by: default avatarPeter Goodspeed-Niklaus <coriolinus@users.noreply.github.com>
Co-authored-by: default avatarMax Inden <mail@max-inden.de>
Co-authored-by: Sergey Pepyakin's avatarSergey Shulepov <s.pepyakin@gmail.com>
Co-authored-by: Sergey Pepyakin's avatarSergei Shulepov <sergei@parity.io>
parent 20a8a61e
Pipeline #112848 failed with stages
in 9 minutes and 46 seconds
This diff is collapsed.
......@@ -34,7 +34,7 @@ members = [
"runtime/parachains",
"runtime/polkadot",
"runtime/kusama",
"runtime/rococo-v1",
"runtime/rococo",
"runtime/westend",
"runtime/test-runtime",
"statement-table",
......@@ -69,6 +69,7 @@ members = [
"node/test/service",
"parachain/test-parachains",
"parachain/test-parachains/adder",
"parachain/test-parachains/adder/collator",
]
[badges]
......
......@@ -56,8 +56,6 @@ mod columns {
#[derive(Debug, Error)]
enum Error {
#[error(transparent)]
RuntimeAPI(#[from] RuntimeApiError),
#[error(transparent)]
ChainAPI(#[from] ChainApiError),
#[error(transparent)]
......@@ -65,13 +63,30 @@ enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Oneshot(#[from] oneshot::Canceled),
ChainApiChannelIsClosed(#[from] oneshot::Canceled),
#[error(transparent)]
Subsystem(#[from] SubsystemError),
#[error(transparent)]
Time(#[from] SystemTimeError),
}
/// Class of errors which we should handle more gracefully.
/// An occurrence of this error should not bring down the subsystem.
#[derive(Debug, Error)]
enum NonFatalError {
/// A Runtime API error occurred.
#[error(transparent)]
RuntimeApi(#[from] RuntimeApiError),
/// The receiver's end of the channel is closed.
#[error(transparent)]
Oneshot(#[from] oneshot::Canceled),
/// Overseer channel's buffer is full.
#[error(transparent)]
OverseerOutOfCapacity(#[from] SubsystemError),
}
/// A wrapper type for delays.
#[derive(Debug, Decode, Encode, Eq)]
enum PruningDelay {
......@@ -582,7 +597,13 @@ async fn process_block_activated<Context>(
where
Context: SubsystemContext<Message=AvailabilityStoreMessage>
{
let events = request_candidate_events(ctx, hash).await?;
let events = match request_candidate_events(ctx, hash).await {
Ok(events) => events,
Err(err) => {
log::debug!(target: LOG_TARGET, "requesting candidate events failed due to {}", err);
return Ok(());
}
};
log::trace!(target: LOG_TARGET, "block activated {}", hash);
let mut included = HashSet::new();
......@@ -626,7 +647,7 @@ where
async fn request_candidate_events<Context>(
ctx: &mut Context,
hash: Hash,
) -> Result<Vec<CandidateEvent>, Error>
) -> Result<Vec<CandidateEvent>, NonFatalError>
where
Context: SubsystemContext<Message=AvailabilityStoreMessage>
{
......@@ -651,44 +672,49 @@ where
Context: SubsystemContext<Message=AvailabilityStoreMessage>
{
use AvailabilityStoreMessage::*;
fn log_send_error(request: &'static str) {
log::debug!(target: LOG_TARGET, "error sending a response to {}", request);
}
match msg {
QueryAvailableData(hash, tx) => {
tx.send(available_data(&subsystem.inner, &hash).map(|d| d.data))
.map_err(|_| oneshot::Canceled)?;
.unwrap_or_else(|_| log_send_error("QueryAvailableData"));
}
QueryDataAvailability(hash, tx) => {
tx.send(available_data(&subsystem.inner, &hash).is_some())
.map_err(|_| oneshot::Canceled)?;
.unwrap_or_else(|_| log_send_error("QueryDataAvailability"));
}
QueryChunk(hash, id, tx) => {
tx.send(get_chunk(subsystem, &hash, id)?)
.map_err(|_| oneshot::Canceled)?;
.unwrap_or_else(|_| log_send_error("QueryChunk"));
}
QueryChunkAvailability(hash, id, tx) => {
tx.send(get_chunk(subsystem, &hash, id)?.is_some())
.map_err(|_| oneshot::Canceled)?;
.unwrap_or_else(|_| log_send_error("QueryChunkAvailability"));
}
StoreChunk { candidate_hash, relay_parent, validator_index, chunk, tx } => {
// Current block number is relay_parent block number + 1.
let block_number = get_block_number(ctx, relay_parent).await? + 1;
match store_chunk(subsystem, &candidate_hash, validator_index, chunk, block_number) {
Err(e) => {
tx.send(Err(())).map_err(|_| oneshot::Canceled)?;
tx.send(Err(())).unwrap_or_else(|_| log_send_error("StoreChunk (Err)"));
return Err(e);
}
Ok(()) => {
tx.send(Ok(())).map_err(|_| oneshot::Canceled)?;
tx.send(Ok(())).unwrap_or_else(|_| log_send_error("StoreChunk (Ok)"));
}
}
}
StoreAvailableData(hash, id, n_validators, av_data, tx) => {
match store_available_data(subsystem, &hash, id, n_validators, av_data) {
Err(e) => {
tx.send(Err(())).map_err(|_| oneshot::Canceled)?;
tx.send(Err(())).unwrap_or_else(|_| log_send_error("StoreAvailableData (Err)"));
return Err(e);
}
Ok(()) => {
tx.send(Ok(())).map_err(|_| oneshot::Canceled)?;
tx.send(Ok(())).unwrap_or_else(|_| log_send_error("StoreAvailableData (Ok)"));
}
}
}
......
......@@ -101,12 +101,12 @@ impl CollatorProtocolSubsystem {
Context: SubsystemContext<Message = CollatorProtocolMessage>,
{
match self.protocol_side {
ProtocolSide::Validator(metrics) => validator_side::run(
ProtocolSide::Validator(metrics) => validator_side::run(
ctx,
REQUEST_TIMEOUT,
metrics,
).await,
ProtocolSide::Collator(id, metrics) => collator_side::run(
ProtocolSide::Collator(id, metrics) => collator_side::run(
ctx,
id,
metrics,
......
......@@ -73,7 +73,7 @@ polkadot-node-subsystem-util = { path = "../subsystem-util" }
polkadot-runtime = { path = "../../runtime/polkadot" }
kusama-runtime = { path = "../../runtime/kusama" }
westend-runtime = { path = "../../runtime/westend" }
rococo-runtime = { package = "rococo-v1-runtime", path = "../../runtime/rococo-v1" }
rococo-runtime = { path = "../../runtime/rococo" }
# Polkadot Subsystems
polkadot-availability-bitfield-distribution = { path = "../network/bitfield-distribution", optional = true }
......
......@@ -768,6 +768,9 @@ fn rococo_staging_testnet_config_genesis(wasm_binary: &[u8]) -> rococo_runtime::
keys: vec![],
}),
pallet_staking: Some(Default::default()),
pallet_sudo: Some(rococo_runtime::SudoConfig {
key: endowed_accounts[0].clone(),
}),
}
}
......@@ -1176,7 +1179,7 @@ pub fn westend_testnet_genesis(
pub fn rococo_testnet_genesis(
wasm_binary: &[u8],
initial_authorities: Vec<(AccountId, AccountId, BabeId, GrandpaId, ImOnlineId, ValidatorId, AuthorityDiscoveryId)>,
_root_key: AccountId,
root_key: AccountId,
endowed_accounts: Option<Vec<AccountId>>,
) -> rococo_runtime::GenesisConfig {
let endowed_accounts: Vec<AccountId> = endowed_accounts.unwrap_or_else(testnet_accounts);
......@@ -1208,6 +1211,7 @@ pub fn rococo_testnet_genesis(
keys: vec![],
}),
pallet_staking: Some(Default::default()),
pallet_sudo: Some(rococo_runtime::SudoConfig { key: root_key }),
}
}
......
......@@ -503,6 +503,8 @@ pub fn new_full<RuntimeApi, Executor>(
let (shared_voter_state, finality_proof_provider) = rpc_setup;
config.network.notifications_protocols.extend(polkadot_network_bridge::notifications_protocol_info());
let (network, network_status_sinks, system_rpc_tx, network_starter) =
service::build_network(service::BuildNetworkParams {
config: &config,
......
......@@ -28,7 +28,7 @@
#![warn(missing_docs)]
use polkadot_node_subsystem::{
errors::{ChainApiError, RuntimeApiError},
errors::RuntimeApiError,
messages::{AllMessages, RuntimeApiMessage, RuntimeApiRequest, RuntimeApiSender},
FromOverseer, SpawnedSubsystem, Subsystem, SubsystemContext, SubsystemError, SubsystemResult,
};
......@@ -99,9 +99,6 @@ pub enum Error {
/// A subsystem error
#[error(transparent)]
Subsystem(#[from] SubsystemError),
/// An error in the Chain API.
#[error(transparent)]
ChainApi(#[from] ChainApiError),
/// An error in the Runtime API.
#[error(transparent)]
RuntimeApi(#[from] RuntimeApiError),
......
......@@ -15,10 +15,10 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-wasm-interface = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
polkadot-core-primitives = { path = "../core-primitives", default-features = false }
derive_more = { version = "0.99.11" }
# all optional crates.
thiserror = { version = "1.0.21", optional = true }
derive_more = { version = "0.99.11", optional = true }
serde = { version = "1.0.102", default-features = false, features = [ "derive" ], optional = true }
sp-externalities = { git = "https://github.com/paritytech/substrate", branch = "master", optional = true }
sc-executor = { git = "https://github.com/paritytech/substrate", branch = "master", optional = true }
......@@ -36,7 +36,6 @@ wasm-api = []
std = [
"codec/std",
"thiserror",
"derive_more",
"serde/std",
"sp-std/std",
"sp-runtime/std",
......
......@@ -34,31 +34,19 @@ use polkadot_core_primitives::Hash;
pub use polkadot_core_primitives::BlockNumber as RelayChainBlockNumber;
/// Parachain head data included in the chain.
#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Encode, Decode, RuntimeDebug)]
#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Encode, Decode, RuntimeDebug, derive_more::From)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Default, Hash))]
pub struct HeadData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl From<Vec<u8>> for HeadData {
fn from(head: Vec<u8>) -> Self {
HeadData(head)
}
}
/// Parachain validation code.
#[derive(Default, PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
#[derive(Default, PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, derive_more::From)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash))]
pub struct ValidationCode(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
impl From<Vec<u8>> for ValidationCode {
fn from(code: Vec<u8>) -> Self {
ValidationCode(code)
}
}
/// Parachain block data.
///
/// Contains everything required to validate para-block, may contain block and witness data.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
#[derive(PartialEq, Eq, Clone, Encode, Decode, derive_more::From)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Debug))]
pub struct BlockData(#[cfg_attr(feature = "std", serde(with="bytes"))] pub Vec<u8>);
......
[package]
name = "test-parachain-adder-collator"
version = "0.7.26"
authors = ["Parity Technologies <admin@parity.io>"]
description = "Collator for the adder test parachain"
edition = "2018"
[[bin]]
name = "adder-collator"
path = "src/main.rs"
[dependencies]
codec = { package = "parity-scale-codec", version = "1.3.4", default-features = false, features = ["derive"] }
futures = "0.3.4"
log = "0.4.8"
structopt = "0.3.8"
test-parachain-adder = { path = ".." }
polkadot-primitives = { path = "../../../../primitives" }
polkadot-cli = { path = "../../../../cli" }
polkadot-service = { path = "../../../../node/service" }
polkadot-node-primitives = { path = "../../../../node/primitives" }
polkadot-node-subsystem = { path = "../../../../node/subsystem" }
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
[dev-dependencies]
polkadot-parachain = { path = "../../.." }
// 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/>.
//! Collator for the adder test parachain.
use std::{pin::Pin, sync::{Arc, Mutex}};
use test_parachain_adder::{hash_state, BlockData, HeadData, execute};
use futures::{Future, FutureExt};
use polkadot_primitives::v1::{ValidationData, PoV, Hash};
use polkadot_node_primitives::Collation;
use codec::Encode;
/// The amount we add when producing a new block.
///
/// This is a constant to make tests easily reproducible.
const ADD: u64 = 2;
/// The state of the adder parachain.
struct State {
genesis_state: HeadData,
last_head: HeadData,
state: u64,
}
impl State {
/// Init the genesis state.
fn genesis() -> Self {
let genesis_state = HeadData {
number: 0,
parent_hash: Default::default(),
post_state: hash_state(0),
};
let last_head = genesis_state.clone();
Self {
genesis_state,
last_head,
state: 0,
}
}
/// Advance the state and produce a new block.
///
/// Returns the new [`BlockData`] and the new [`HeadData`].
fn advance(&mut self) -> (BlockData, HeadData) {
let block = BlockData {
state: self.state,
add: ADD,
};
let new_head = execute(self.last_head.hash(), self.last_head.clone(), &block)
.expect("Produces valid block");
self.last_head = new_head.clone();
self.state = self.state.wrapping_add(ADD);
(block, new_head)
}
}
/// The collator of the adder parachain.
pub struct Collator {
state: Arc<Mutex<State>>,
}
impl Collator {
/// Create a new collator instance with the state initialized as genesis.
pub fn new() -> Self {
Self {
state: Arc::new(Mutex::new(State::genesis())),
}
}
/// Get the SCALE encoded genesis head of the adder parachain.
pub fn genesis_head(&self) -> Vec<u8> {
self.state.lock().unwrap().genesis_state.encode()
}
/// Get the validation code of the adder parachain.
pub fn validation_code(&self) -> &[u8] {
test_parachain_adder::wasm_binary_unwrap()
}
/// Create the collation function.
///
/// This collation function can be plugged into the overseer to generate collations for the adder parachain.
pub fn create_collation_function(
&self,
) -> Box<dyn Fn(Hash, &ValidationData) -> Pin<Box<dyn Future<Output = Option<Collation>> + Send>> + Send + Sync> {
let state = self.state.clone();
Box::new(move |_, _| {
let (block_data, head_data) = state.lock().unwrap().advance();
let collation = Collation {
upward_messages: Vec::new(),
new_validation_code: None,
head_data: head_data.encode().into(),
proof_of_validity: PoV { block_data: block_data.encode().into() },
processed_downward_messages: 0,
};
async move { Some(collation) }.boxed()
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::executor::block_on;
use polkadot_parachain::{primitives::ValidationParams, wasm_executor::ExecutionMode};
use codec::Decode;
#[test]
fn collator_works() {
let collator = Collator::new();
let collation_function = collator.create_collation_function();
for _ in 0..5 {
let parent_head = collator.state.lock().unwrap().last_head.clone();
let collation = block_on(collation_function(Default::default(), &Default::default())).unwrap();
validate_collation(&collator, parent_head, collation);
}
}
fn validate_collation(collator: &Collator, parent_head: HeadData, collation: Collation) {
let ret = polkadot_parachain::wasm_executor::validate_candidate(
collator.validation_code(),
ValidationParams {
parent_head: parent_head.encode().into(),
block_data: collation.proof_of_validity.block_data,
relay_chain_height: 1,
hrmp_mqc_heads: Vec::new(),
dmq_mqc_head: Default::default(),
},
&ExecutionMode::InProcess,
sp_core::testing::TaskExecutor::new(),
).unwrap();
let new_head = HeadData::decode(&mut &ret.head_data.0[..]).unwrap();
assert_eq!(collator.state.lock().unwrap().last_head, new_head);
}
}
// 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/>.
//! Collator for the adder test parachain.
use sc_cli::{Result, Role, SubstrateCli};
use polkadot_cli::Cli;
use polkadot_node_subsystem::messages::{CollatorProtocolMessage, CollationGenerationMessage};
use polkadot_node_primitives::CollationGenerationConfig;
use polkadot_primitives::v1::{CollatorPair, Id as ParaId};
use test_parachain_adder_collator::Collator;
use sp_core::{Pair, hexdisplay::HexDisplay};
const PARA_ID: ParaId = ParaId::new(100);
fn main() -> Result<()> {
let cli = Cli::from_args();
if cli.subcommand.is_some() {
return Err("Subcommands are not supported".into())
}
let runner = cli.create_runner(&cli.run.base)?;
runner.run_node_until_exit(|config| async move {
let role = config.role.clone();
match role {
Role::Light => Err("Light client not supported".into()),
_ => {
let collator_key = CollatorPair::generate().0;
let full_node = polkadot_service::build_full(
config,
polkadot_service::IsCollator::Yes(collator_key.public()),
None,
)?;
let mut overseer_handler = full_node.overseer_handler
.expect("Overseer handler should be initialized for collators");
let collator = Collator::new();
let genesis_head_hex = format!("0x{:?}", HexDisplay::from(&collator.genesis_head()));
let validation_code_hex = format!("0x{:?}", HexDisplay::from(&collator.validation_code()));
log::info!("Running adder collator for parachain id: {}", PARA_ID);
log::info!("Genesis state: {}", genesis_head_hex);
log::info!("Validation code: {}", validation_code_hex);
let config = CollationGenerationConfig {
key: collator_key,
collator: collator.create_collation_function(),
para_id: PARA_ID,
};
overseer_handler
.send_msg(CollationGenerationMessage::Initialize(config))
.await
.expect("Registers collator");
overseer_handler
.send_msg(CollatorProtocolMessage::CollateOn(PARA_ID))
.await
.expect("Collates on");
Ok(full_node.task_manager)
},
}
})
}
......@@ -33,15 +33,15 @@ static ALLOC: dlmalloc::GlobalDlmalloc = dlmalloc::GlobalDlmalloc;
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
#[cfg(feature = "std")]
/// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics.
#[cfg(feature = "std")]
pub fn wasm_binary_unwrap() -> &'static [u8] {
WASM_BINARY.expect("Development wasm binary is not available. Testing is only \
supported with the flag disabled.")
}
/// Head data for this parachain.
#[derive(Default, Clone, Hash, Eq, PartialEq, Encode, Decode)]
#[derive(Default, Clone, Hash, Eq, PartialEq, Encode, Decode, Debug)]
pub struct HeadData {
/// Block number
pub number: u64,
......@@ -62,7 +62,7 @@ impl HeadData {
pub struct BlockData {
/// State to begin from.
pub state: u64,
/// Amount to add (overflowing)
/// Amount to add (wrapping)
pub add: u64,
}
......@@ -81,13 +81,13 @@ pub fn execute(
parent_head: HeadData,
block_data: &BlockData,
) -> Result<HeadData, StateMismatch> {
debug_assert_eq!(parent_hash, parent_head.hash());
assert_eq!(parent_hash, parent_head.hash());
if hash_state(block_data.state) != parent_head.post_state {
return Err(StateMismatch);
}
let new_state = block_data.state.overflowing_add(block_data.add).0;