openethereum/ethcore/src/engines/instant_seal.rs

143 lines
3.8 KiB
Rust
Raw Normal View History

// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum 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.
// Parity Ethereum 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 Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
Move more types out of ethcore (#10880) * WIP move errors, pod_account and state account to own crates * Sort out dependencies, fix broken code and tests Remove botched ethcore-error crate * remove template line * fix review feedback * Remove test-only AccountDBMut::new * Extract AccountDB to account-db * Move Substate to state-account – wip * Add lib.rs * cleanup * test failure * test failure 2 * third time's the charm * Add factories crate * Use new factories crate * Use factories crate * Extract trace * Fix tests * Sort out parity-util-mem and parking_lot * cleanup * WIP port over the rest of state from ethcore * Collect all impls for Machine * some notes * Rename pod-account to pod * Move PodState to pod crate * Use PodState from pod crate * Fix use clause for json tests * Sort out evmbin * Add missing code and use PodState * Move code that depends on Machine and Executive to own module * Sort out cloning errors, fix ethcore to use new state crate * Do without funky From impls * Fix ethcore tests * Fixes around the project to use new state crate * Add back the more specific impls of StateOrBlock From conversions * Move execute to freestanding function and remove it from trait Sort out the error handling in executive_state by moving the result types from state to ethcore Undo the verbose code added to work around the StateOrBlock From conversions * cleanup * Fix "error: enum variants on type aliases are experimental" * Bring back the state tests Fix whitespace * remove ethcore/state/mod.rs * cleanup * cleanup * Cleanup state-account errors * Fix more todos Add module docs * Add error.rs * Fixup Cargo.lock * Smaller ethcore API is fine * Add `to-pod-full` feature to state-account Fix evmbin * Fix a few more test failures * Fix RPC test build * Baptize the new trait * Remove resolved TODOs * Rename state-account to account-state * Do not re-export the trace crate * Don't export state_db from ethcore * Let private-tx use StateDB. :( * Remove ethcore/src/pod_state.rs * Inner type does not need to be pub/pub(crate) * optimise imports * Revert "Inner type does not need to be pub/pub(crate)" This reverts commit 2f839f8a0f72f71334da64620f57e6dd6039f06b. * Move DatabaseExtras to ethcore-blockchain * Add database_extra module to ethcore-blockchain * Remove to-pod-full feature * cosmetics * New crate: state-db * Add new crate * Move PreverifiedBlock and BlockError to types * Sort out the merge * Add missing `license` meta data keys * wip * wip client-traits * merge conflict * verification crate type checks * Move impls for CommonParams to common_types Fix misc stuff in ethcore * Fix tests * Implement VerifyingEngine for all engines except Ethash Temporarily sort out error handling Move more types to common_types * Split Engine in two and move code around * cleanup * verification: don't rexport common_types * Use error from common_types * Consolidate error types * VerifyingEngine use Errors from common_types * verification: Use error type from common_types * SnapshotError moved to common_types * Move more code from Engne to VerifyingEngine Add a VerifyingClient trait: BlockInfo + CallContract Whitespace * Add MAX_UNCLE_AGE const * Port over remaining code from ethcore/verification * Use errors from common_types * Fix the confusing "io" naming * Move more types into common_types * Add todos * Experiment with Engine trait outside ethcore * Hook up types from common_types in ethcore Don't use verification crate Don't use client-traits crate * Revert to impl Engine for Arc<Ethash> and add note to explain why Revert moving ClientIoMessage to common_types Fix build * Remove ClientIoMessage from common_types * Cleanup * More cleanup * Sort error handling changes in the rest of parity * Remove unused code * Remove WIP types * Cleanup todos not tackled here * remove cruft * Fix some whitespace and a merge error * ethcore tests * test failures * Restore Engine impls to master to make review a bit easier * cleanup * whitespace * applied review suggestions * types does not depend on rustc-hex * ethash engine moved to engine module * applied review suggestion
2019-07-18 12:27:08 +02:00
use engines::{Engine, Seal};
use machine::{
ExecutedBlock,
Machine
};
Move more types out of ethcore (#10880) * WIP move errors, pod_account and state account to own crates * Sort out dependencies, fix broken code and tests Remove botched ethcore-error crate * remove template line * fix review feedback * Remove test-only AccountDBMut::new * Extract AccountDB to account-db * Move Substate to state-account – wip * Add lib.rs * cleanup * test failure * test failure 2 * third time's the charm * Add factories crate * Use new factories crate * Use factories crate * Extract trace * Fix tests * Sort out parity-util-mem and parking_lot * cleanup * WIP port over the rest of state from ethcore * Collect all impls for Machine * some notes * Rename pod-account to pod * Move PodState to pod crate * Use PodState from pod crate * Fix use clause for json tests * Sort out evmbin * Add missing code and use PodState * Move code that depends on Machine and Executive to own module * Sort out cloning errors, fix ethcore to use new state crate * Do without funky From impls * Fix ethcore tests * Fixes around the project to use new state crate * Add back the more specific impls of StateOrBlock From conversions * Move execute to freestanding function and remove it from trait Sort out the error handling in executive_state by moving the result types from state to ethcore Undo the verbose code added to work around the StateOrBlock From conversions * cleanup * Fix "error: enum variants on type aliases are experimental" * Bring back the state tests Fix whitespace * remove ethcore/state/mod.rs * cleanup * cleanup * Cleanup state-account errors * Fix more todos Add module docs * Add error.rs * Fixup Cargo.lock * Smaller ethcore API is fine * Add `to-pod-full` feature to state-account Fix evmbin * Fix a few more test failures * Fix RPC test build * Baptize the new trait * Remove resolved TODOs * Rename state-account to account-state * Do not re-export the trace crate * Don't export state_db from ethcore * Let private-tx use StateDB. :( * Remove ethcore/src/pod_state.rs * Inner type does not need to be pub/pub(crate) * optimise imports * Revert "Inner type does not need to be pub/pub(crate)" This reverts commit 2f839f8a0f72f71334da64620f57e6dd6039f06b. * Move DatabaseExtras to ethcore-blockchain * Add database_extra module to ethcore-blockchain * Remove to-pod-full feature * cosmetics * New crate: state-db * Add new crate * Move PreverifiedBlock and BlockError to types * Sort out the merge * Add missing `license` meta data keys * wip * wip client-traits * merge conflict * verification crate type checks * Move impls for CommonParams to common_types Fix misc stuff in ethcore * Fix tests * Implement VerifyingEngine for all engines except Ethash Temporarily sort out error handling Move more types to common_types * Split Engine in two and move code around * cleanup * verification: don't rexport common_types * Use error from common_types * Consolidate error types * VerifyingEngine use Errors from common_types * verification: Use error type from common_types * SnapshotError moved to common_types * Move more code from Engne to VerifyingEngine Add a VerifyingClient trait: BlockInfo + CallContract Whitespace * Add MAX_UNCLE_AGE const * Port over remaining code from ethcore/verification * Use errors from common_types * Fix the confusing "io" naming * Move more types into common_types * Add todos * Experiment with Engine trait outside ethcore * Hook up types from common_types in ethcore Don't use verification crate Don't use client-traits crate * Revert to impl Engine for Arc<Ethash> and add note to explain why Revert moving ClientIoMessage to common_types Fix build * Remove ClientIoMessage from common_types * Cleanup * More cleanup * Sort error handling changes in the rest of parity * Remove unused code * Remove WIP types * Cleanup todos not tackled here * remove cruft * Fix some whitespace and a merge error * ethcore tests * test failures * Restore Engine impls to master to make review a bit easier * cleanup * whitespace * applied review suggestions * types does not depend on rustc-hex * ethash engine moved to engine module * applied review suggestion
2019-07-18 12:27:08 +02:00
use types::{
header::Header,
engines::{
SealingState,
params::CommonParams,
},
errors::EthcoreError as Error,
};
/// `InstantSeal` params.
#[derive(Default, Debug, PartialEq)]
pub struct InstantSealParams {
/// Whether to use millisecond timestamp
pub millisecond_timestamp: bool,
}
impl From<::ethjson::spec::InstantSealParams> for InstantSealParams {
fn from(p: ::ethjson::spec::InstantSealParams) -> Self {
InstantSealParams {
millisecond_timestamp: p.millisecond_timestamp,
}
}
}
/// An engine which does not provide any consensus mechanism, just seals blocks internally.
/// Only seals blocks which have transactions.
pub struct InstantSeal {
params: InstantSealParams,
machine: Machine,
}
impl InstantSeal {
/// Returns new instance of InstantSeal over the given state machine.
pub fn new(params: InstantSealParams, machine: Machine) -> Self {
InstantSeal {
params,
machine,
}
}
}
impl Engine for InstantSeal {
fn name(&self) -> &str {
"InstantSeal"
}
fn machine(&self) -> &Machine { &self.machine }
fn sealing_state(&self) -> SealingState { SealingState::Ready }
fn generate_seal(&self, block: &ExecutedBlock, _parent: &Header) -> Seal {
if block.transactions.is_empty() {
Seal::None
} else {
Seal::Regular(Vec::new())
}
}
fn verify_local_seal(&self, _header: &Header) -> Result<(), Error> {
Ok(())
}
fn open_block_header_timestamp(&self, parent_timestamp: u64) -> u64 {
use std::{time, cmp};
let dur = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap_or_default();
let mut now = dur.as_secs();
if self.params.millisecond_timestamp {
now = now * 1000 + dur.subsec_millis() as u64;
}
cmp::max(now, parent_timestamp)
}
fn is_timestamp_valid(&self, header_timestamp: u64, parent_timestamp: u64) -> bool {
header_timestamp >= parent_timestamp
}
Move more types out of ethcore (#10880) * WIP move errors, pod_account and state account to own crates * Sort out dependencies, fix broken code and tests Remove botched ethcore-error crate * remove template line * fix review feedback * Remove test-only AccountDBMut::new * Extract AccountDB to account-db * Move Substate to state-account – wip * Add lib.rs * cleanup * test failure * test failure 2 * third time's the charm * Add factories crate * Use new factories crate * Use factories crate * Extract trace * Fix tests * Sort out parity-util-mem and parking_lot * cleanup * WIP port over the rest of state from ethcore * Collect all impls for Machine * some notes * Rename pod-account to pod * Move PodState to pod crate * Use PodState from pod crate * Fix use clause for json tests * Sort out evmbin * Add missing code and use PodState * Move code that depends on Machine and Executive to own module * Sort out cloning errors, fix ethcore to use new state crate * Do without funky From impls * Fix ethcore tests * Fixes around the project to use new state crate * Add back the more specific impls of StateOrBlock From conversions * Move execute to freestanding function and remove it from trait Sort out the error handling in executive_state by moving the result types from state to ethcore Undo the verbose code added to work around the StateOrBlock From conversions * cleanup * Fix "error: enum variants on type aliases are experimental" * Bring back the state tests Fix whitespace * remove ethcore/state/mod.rs * cleanup * cleanup * Cleanup state-account errors * Fix more todos Add module docs * Add error.rs * Fixup Cargo.lock * Smaller ethcore API is fine * Add `to-pod-full` feature to state-account Fix evmbin * Fix a few more test failures * Fix RPC test build * Baptize the new trait * Remove resolved TODOs * Rename state-account to account-state * Do not re-export the trace crate * Don't export state_db from ethcore * Let private-tx use StateDB. :( * Remove ethcore/src/pod_state.rs * Inner type does not need to be pub/pub(crate) * optimise imports * Revert "Inner type does not need to be pub/pub(crate)" This reverts commit 2f839f8a0f72f71334da64620f57e6dd6039f06b. * Move DatabaseExtras to ethcore-blockchain * Add database_extra module to ethcore-blockchain * Remove to-pod-full feature * cosmetics * New crate: state-db * Add new crate * Move PreverifiedBlock and BlockError to types * Sort out the merge * Add missing `license` meta data keys * wip * wip client-traits * merge conflict * verification crate type checks * Move impls for CommonParams to common_types Fix misc stuff in ethcore * Fix tests * Implement VerifyingEngine for all engines except Ethash Temporarily sort out error handling Move more types to common_types * Split Engine in two and move code around * cleanup * verification: don't rexport common_types * Use error from common_types * Consolidate error types * VerifyingEngine use Errors from common_types * verification: Use error type from common_types * SnapshotError moved to common_types * Move more code from Engne to VerifyingEngine Add a VerifyingClient trait: BlockInfo + CallContract Whitespace * Add MAX_UNCLE_AGE const * Port over remaining code from ethcore/verification * Use errors from common_types * Fix the confusing "io" naming * Move more types into common_types * Add todos * Experiment with Engine trait outside ethcore * Hook up types from common_types in ethcore Don't use verification crate Don't use client-traits crate * Revert to impl Engine for Arc<Ethash> and add note to explain why Revert moving ClientIoMessage to common_types Fix build * Remove ClientIoMessage from common_types * Cleanup * More cleanup * Sort error handling changes in the rest of parity * Remove unused code * Remove WIP types * Cleanup todos not tackled here * remove cruft * Fix some whitespace and a merge error * ethcore tests * test failures * Restore Engine impls to master to make review a bit easier * cleanup * whitespace * applied review suggestions * types does not depend on rustc-hex * ethash engine moved to engine module * applied review suggestion
2019-07-18 12:27:08 +02:00
fn params(&self) -> &CommonParams {
self.machine.params()
}
}
Move more types out of ethcore (#10880) * WIP move errors, pod_account and state account to own crates * Sort out dependencies, fix broken code and tests Remove botched ethcore-error crate * remove template line * fix review feedback * Remove test-only AccountDBMut::new * Extract AccountDB to account-db * Move Substate to state-account – wip * Add lib.rs * cleanup * test failure * test failure 2 * third time's the charm * Add factories crate * Use new factories crate * Use factories crate * Extract trace * Fix tests * Sort out parity-util-mem and parking_lot * cleanup * WIP port over the rest of state from ethcore * Collect all impls for Machine * some notes * Rename pod-account to pod * Move PodState to pod crate * Use PodState from pod crate * Fix use clause for json tests * Sort out evmbin * Add missing code and use PodState * Move code that depends on Machine and Executive to own module * Sort out cloning errors, fix ethcore to use new state crate * Do without funky From impls * Fix ethcore tests * Fixes around the project to use new state crate * Add back the more specific impls of StateOrBlock From conversions * Move execute to freestanding function and remove it from trait Sort out the error handling in executive_state by moving the result types from state to ethcore Undo the verbose code added to work around the StateOrBlock From conversions * cleanup * Fix "error: enum variants on type aliases are experimental" * Bring back the state tests Fix whitespace * remove ethcore/state/mod.rs * cleanup * cleanup * Cleanup state-account errors * Fix more todos Add module docs * Add error.rs * Fixup Cargo.lock * Smaller ethcore API is fine * Add `to-pod-full` feature to state-account Fix evmbin * Fix a few more test failures * Fix RPC test build * Baptize the new trait * Remove resolved TODOs * Rename state-account to account-state * Do not re-export the trace crate * Don't export state_db from ethcore * Let private-tx use StateDB. :( * Remove ethcore/src/pod_state.rs * Inner type does not need to be pub/pub(crate) * optimise imports * Revert "Inner type does not need to be pub/pub(crate)" This reverts commit 2f839f8a0f72f71334da64620f57e6dd6039f06b. * Move DatabaseExtras to ethcore-blockchain * Add database_extra module to ethcore-blockchain * Remove to-pod-full feature * cosmetics * New crate: state-db * Add new crate * Move PreverifiedBlock and BlockError to types * Sort out the merge * Add missing `license` meta data keys * wip * wip client-traits * merge conflict * verification crate type checks * Move impls for CommonParams to common_types Fix misc stuff in ethcore * Fix tests * Implement VerifyingEngine for all engines except Ethash Temporarily sort out error handling Move more types to common_types * Split Engine in two and move code around * cleanup * verification: don't rexport common_types * Use error from common_types * Consolidate error types * VerifyingEngine use Errors from common_types * verification: Use error type from common_types * SnapshotError moved to common_types * Move more code from Engne to VerifyingEngine Add a VerifyingClient trait: BlockInfo + CallContract Whitespace * Add MAX_UNCLE_AGE const * Port over remaining code from ethcore/verification * Use errors from common_types * Fix the confusing "io" naming * Move more types into common_types * Add todos * Experiment with Engine trait outside ethcore * Hook up types from common_types in ethcore Don't use verification crate Don't use client-traits crate * Revert to impl Engine for Arc<Ethash> and add note to explain why Revert moving ClientIoMessage to common_types Fix build * Remove ClientIoMessage from common_types * Cleanup * More cleanup * Sort error handling changes in the rest of parity * Remove unused code * Remove WIP types * Cleanup todos not tackled here * remove cruft * Fix some whitespace and a merge error * ethcore tests * test failures * Restore Engine impls to master to make review a bit easier * cleanup * whitespace * applied review suggestions * types does not depend on rustc-hex * ethash engine moved to engine module * applied review suggestion
2019-07-18 12:27:08 +02:00
#[cfg(test)]
mod tests {
2017-07-29 21:56:42 +02:00
use std::sync::Arc;
use ethereum_types::{H520, Address};
Private transactions integration pr (#6422) * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Private tx execution * Test update * Renamed some methods * Fixed some tests * Reverted submodules * Fixed build * Private transaction message added * Empty line removed * Private transactions logic removed from client into the separate module * Fixed compilation after merge with head * Signed private transaction message added as well * Comments after the review fixed * Encrypted private transaction message and signed reply added * Private tx execution * Test update * Main scenario completed * Merged with the latest head * Private transactions API * Comments after review fixed * Parameters for private transactions added to parity arguments * New files added * New API methods added * Do not process packets from unconfirmed peers * Merge with ptm_ss branch * Encryption and permissioning with key server added * Fixed compilation after merge * Version of Parity protocol incremented in order to support private transactions * Doc strings for constants added * Proper format for doc string added * fixed some encryptor.rs grumbles * Private transactions functionality moved to the separate crate * Refactoring in order to remove late initialisation * Tests fixed after moving to the separate crate * Fetch method removed * Sync test helpers refactored * Interaction with encryptor refactored * Contract address retrieving via substate removed * Sensible gas limit for private transactions implemented * New private contract with nonces added * Parsing of the response from key server fixed * Build fixed after the merge, native contracts removed * Crate renamed * Tests moved to the separate directory * Handling of errors reworked in order to use error chain * Encodable macro added, new constructor replaced with default * Native ethabi usage removed * Couple conversions optimized * Interactions with client reworked * Errors omitting removed * Fix after merge * Fix after the merge * private transactions improvements in progress * private_transactions -> ethcore/private-tx * making private transactions more idiomatic * private-tx encryptor uses shared FetchClient and is more idiomatic * removed redundant tests, moved integration tests to tests/ dir * fixed failing service test * reenable add_notify on private tx provider * removed private_tx tests from sync module * removed commented out code * Use plain password instead of unlocking account manager * remove dead code * Link to the contract changed * Transaction signature chain replay protection module created * Redundant type conversion removed * Contract address returned by private provider * Test fixed * Addressing grumbles in PrivateTransactions (#8249) * Tiny fixes part 1. * A bunch of additional comments and todos. * Fix ethsync tests. * resolved merge conflicts * final private tx pr (#8318) * added cli option that enables private transactions * fixed failing test * fixed failing test * fixed failing test * fixed failing test
2018-04-09 16:14:33 +02:00
use test_helpers::get_temp_state_db;
use crate::spec;
use types::header::Header;
use block::*;
2016-12-08 12:03:34 +01:00
use engines::Seal;
#[test]
fn instant_can_seal() {
let spec = spec::new_instant();
let engine = &*spec.engine;
2017-04-06 19:26:17 +02:00
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
let genesis_header = spec.genesis_header();
let last_hashes = Arc::new(vec![genesis_header.hash()]);
let b = OpenBlock::new(engine, Default::default(), false, db, &genesis_header, last_hashes, Address::zero(), (3141562.into(), 31415620.into()), vec![], false).unwrap();
let b = b.close_and_lock().unwrap();
if let Seal::Regular(seal) = engine.generate_seal(&b, &genesis_header) {
2016-12-08 12:03:34 +01:00
assert!(b.try_seal(engine, seal).is_ok());
}
}
#[test]
fn instant_cant_verify() {
let engine = spec::new_instant().engine;
let mut header: Header = Header::default();
assert!(engine.verify_block_basic(&header).is_ok());
header.set_seal(vec![::rlp::encode(&H520::default())]);
assert!(engine.verify_block_unordered(&header).is_ok());
}
}