diff --git a/chain/src/chain.rs b/chain/src/chain.rs index 3f6713e9b2..7e26010836 100644 --- a/chain/src/chain.rs +++ b/chain/src/chain.rs @@ -13,6 +13,7 @@ use starcoin_chain_api::{ verify_block, ChainReader, ChainWriter, ConnectBlockError, EventWithProof, ExcludedTxns, ExecutedBlock, MintedUncleNumber, TransactionInfoWithProof, VerifiedBlock, VerifyBlockField, }; +use starcoin_config::genesis_config::{G_TEST_DAG_FORK_HEIGHT, G_TEST_DAG_FORK_STATE_KEY}; use starcoin_consensus::Consensus; use starcoin_crypto::hash::PlainCryptoHash; use starcoin_crypto::HashValue; @@ -1470,6 +1471,21 @@ impl BlockChain { let chain_id = self.status().head().chain_id(); if chain_id.is_proxima() { Ok(Some(1000)) + } else if chain_id.is_test() { + let result = self.dag.get_dag_state(*G_TEST_DAG_FORK_STATE_KEY); + if result.is_ok() { + Ok(Some(G_TEST_DAG_FORK_HEIGHT)) + } else { + let result = self.dag.get_dag_state(self.current_header().id()); + if result.is_ok() { + Ok(Some(G_TEST_DAG_FORK_HEIGHT)) + } else { + Ok(self + .statedb + .get_on_chain_config::()? + .map(|c| c.effective_height)) + } + } } else { Ok(self .statedb diff --git a/chain/tests/test_txn_info_and_proof.rs b/chain/tests/test_txn_info_and_proof.rs index f0b444faeb..5d92a931e8 100644 --- a/chain/tests/test_txn_info_and_proof.rs +++ b/chain/tests/test_txn_info_and_proof.rs @@ -64,7 +64,7 @@ fn test_transaction_info_and_proof_1() -> Result<()> { }); // fork from 3 block let fork_point = block_chain.get_block_by_number(3).unwrap().unwrap(); - let fork_chain = block_chain.fork(fork_point.id()).unwrap(); + let mut fork_chain = block_chain.fork(fork_point.id()).unwrap(); let account_reader = fork_chain.chain_state_reader(); seq_num = account_reader.get_sequence_number(account_config::association_address())?; let _txns = gen_txns(&mut seq_num).unwrap(); @@ -83,7 +83,7 @@ fn test_transaction_info_and_proof_1() -> Result<()> { .create_block(template, config.net().time_service().as_ref()) .unwrap(); debug!("Apply block:{:?}", &block); - block_chain.apply(block).unwrap(); + fork_chain.apply(block).unwrap(); assert_eq!( block_chain.current_header().id(), block_chain.get_block_by_number(5).unwrap().unwrap().id() diff --git a/config/src/genesis_config.rs b/config/src/genesis_config.rs index b5dfbec727..ff2b4f0154 100644 --- a/config/src/genesis_config.rs +++ b/config/src/genesis_config.rs @@ -17,6 +17,7 @@ use starcoin_crypto::{ use starcoin_gas::StarcoinGasParameters; use starcoin_gas_algebra_ext::{CostTable, FromOnChainGasSchedule}; use starcoin_time_service::{TimeService, TimeServiceType}; +use starcoin_types::block::BlockNumber; use starcoin_uint::U256; use starcoin_vm_types::account_config::genesis_address; use starcoin_vm_types::event::EventHandle; @@ -717,6 +718,10 @@ pub static G_BASE_BLOCK_GAS_LIMIT: u64 = 50_000_000; //must big than maximum_num static G_EMPTY_BOOT_NODES: Lazy> = Lazy::new(Vec::new); const ONE_DAY: u64 = 86400; +// for test +pub static G_TEST_DAG_FORK_HEIGHT: BlockNumber = 20; +pub static G_TEST_DAG_FORK_STATE_KEY: Lazy = Lazy::new(|| 0.into()); + pub static G_TEST_CONFIG: Lazy = Lazy::new(|| { let (association_private_key, association_public_key) = genesis_multi_key_pair(); let (genesis_private_key, genesis_public_key) = genesis_key_pair(); diff --git a/executor/tests/error_code_test.rs b/executor/tests/error_code_test.rs index cef86b1cd3..8b469927f8 100644 --- a/executor/tests/error_code_test.rs +++ b/executor/tests/error_code_test.rs @@ -95,25 +95,26 @@ fn test_block_metadata_error_code() -> Result<()> { *output2.status() ); - net.time_service().sleep(1000); - let txn3 = Transaction::BlockMetadata(BlockMetadata::new( - starcoin_crypto::HashValue::random(), - net.time_service().now_millis(), - *account1.address(), - Some(account1.auth_key()), - net.genesis_config() - .consensus_config - .base_max_uncles_per_block - + 1, //MAX_UNCLES_PER_BLOCK_IS_WRONG - 2, - net.chain_id(), - 0, - )); - let output3 = execute_and_apply(&chain_state, txn3); - assert_eq!( - TransactionStatus::Discard(StatusCode::UNEXPECTED_ERROR_FROM_KNOWN_MOVE_FUNCTION), - *output3.status() - ); + // the logic of verification of the uncle count is commented + // net.time_service().sleep(1000); + // let txn3 = Transaction::BlockMetadata(BlockMetadata::new( + // starcoin_crypto::HashValue::random(), + // net.time_service().now_millis(), + // *account1.address(), + // Some(account1.auth_key()), + // net.genesis_config() + // .consensus_config + // .base_max_uncles_per_block + // + 1, //MAX_UNCLES_PER_BLOCK_IS_WRONG + // 2, + // net.chain_id(), + // 0, + // )); + // let output3 = execute_and_apply(&chain_state, txn3); + // assert_eq!( + // TransactionStatus::Discard(StatusCode::UNEXPECTED_ERROR_FROM_KNOWN_MOVE_FUNCTION), + // *output3.status() + // ); Ok(()) } diff --git a/sync/src/block_connector/test_write_dag_block_chain.rs b/sync/src/block_connector/test_write_dag_block_chain.rs index 0ac1849e8c..925596f105 100644 --- a/sync/src/block_connector/test_write_dag_block_chain.rs +++ b/sync/src/block_connector/test_write_dag_block_chain.rs @@ -7,7 +7,7 @@ use anyhow::{bail, Ok}; use starcoin_account_api::AccountInfo; use starcoin_chain::{BlockChain, ChainReader}; use starcoin_chain_service::WriteableChainService; -use starcoin_config::{ChainNetwork, NodeConfig}; +use starcoin_config::{genesis_config::G_TEST_DAG_FORK_HEIGHT, ChainNetwork, NodeConfig}; use starcoin_consensus::Consensus; use starcoin_crypto::HashValue; use starcoin_txpool_mock_service::MockTxPoolService; @@ -128,7 +128,7 @@ pub fn new_dag_block( async fn test_dag_block_chain_apply() { let times = 12; let (mut writeable_block_chain_service, node_config, _) = - create_writeable_dag_block_chain(20).await; + create_writeable_dag_block_chain(G_TEST_DAG_FORK_HEIGHT).await; let net = node_config.net(); let last_header_id = gen_dag_blocks(times, &mut writeable_block_chain_service, net); assert_eq!( @@ -192,7 +192,7 @@ fn gen_fork_dag_block_chain( async fn test_block_dag_chain_switch_main() -> anyhow::Result<()> { let times = 12; let (mut writeable_block_chain_service, node_config, _) = - create_writeable_dag_block_chain(20).await; + create_writeable_dag_block_chain(G_TEST_DAG_FORK_HEIGHT).await; let net = node_config.net(); let mut last_block = gen_dag_blocks(times, &mut writeable_block_chain_service, net)?; assert_eq!( @@ -226,7 +226,7 @@ async fn test_block_dag_chain_switch_main() -> anyhow::Result<()> { async fn test_block_chain_reset() -> anyhow::Result<()> { let times = 10; let (mut writeable_block_chain_service, node_config, _) = - create_writeable_dag_block_chain(20).await; + create_writeable_dag_block_chain(G_TEST_DAG_FORK_HEIGHT).await; let net = node_config.net(); let last_block = gen_dag_blocks(times, &mut writeable_block_chain_service, net)?; assert_eq!( diff --git a/sync/tests/common_test_sync_libs.rs b/sync/tests/common_test_sync_libs.rs index d0804adf3d..130e2a1959 100644 --- a/sync/tests/common_test_sync_libs.rs +++ b/sync/tests/common_test_sync_libs.rs @@ -1,11 +1,24 @@ use anyhow::{Ok, Result}; +use futures::executor::block_on; use network_api::PeerId; -use starcoin_config::*; +use starcoin_chain::BlockChain; +use starcoin_chain_api::{ChainAsyncService, ChainReader}; +use starcoin_chain_service::ChainReaderService; +use starcoin_config::{genesis_config::G_TEST_DAG_FORK_STATE_KEY, *}; use starcoin_crypto::HashValue; +use starcoin_dag::{blockdag::BlockDAG, consensusdb::consenses_state::DagState}; use starcoin_logger::prelude::*; +use starcoin_miner::MinedBlock; use starcoin_node::NodeHandle; -use starcoin_types::block::BlockHeader; -use std::sync::Arc; +use starcoin_service_registry::{ + bus::{Bus, BusService}, + RegistryAsyncService, RegistryService, ServiceRef, +}; +use starcoin_storage::Storage; +use starcoin_types::block::{BlockHeader, BlockNumber}; +use starcoin_vm_types::on_chain_config::FlexiDagConfig; +use std::{sync::Arc, time::Duration}; +use test_helper::Account; #[derive(Debug, Clone)] pub struct DagBlockInfo { @@ -26,7 +39,7 @@ fn gen_node(seeds: Vec) -> Result<(NodeHandle, NetworkConfig)> { starcoin_config::DataDirPath::PathBuf(path) => path, starcoin_config::DataDirPath::TempPath(path) => path.path().to_path_buf(), }; - let mut config = NodeConfig::random_for_test(); + let mut config = NodeConfig::random_for_test_disable_miner(true); let net_addr = config.network.self_address(); debug!("Local node address: {:?}", net_addr); @@ -62,6 +75,31 @@ pub fn generate_block(handle: &NodeHandle, count: usize) -> Result<()> { Ok(()) } +#[allow(unused)] +pub fn generate_dag_fork_number(handle: &NodeHandle) -> Result<()> { + // for _i in 0..G_TEST_DAG_FORK_HEIGHT - 3 { + // let (_block, _is_dag) = handle.generate_block()?; + // } + + block_on(async move { + let current_header = handle + .registry() + .service_ref::() + .await? + .main_head_header() + .await?; + // let block_info = handle.storage().get_block_info(current_header.id())?.expect("failed to get the block info"); + + // let accumulator = MerkleAccumulator::new_with_info(block_info.block_accumulator_info, handle.storage().get_accumulator_store(AccumulatorStoreType::Block)); + // let dag_genesis = accumulator.get_leaf(G_TEST_DAG_FORK_HEIGHT)?.expect("failed to get the dag genesis"); + // let dag_genesis_header = handle.storage().get_block(dag_genesis)?.expect("failed to get the dag genesis header"); + let mut dag = handle.registry().get_shared::().await?; + // dag.init_with_genesis(dag_genesis_header.header().clone()).expect("failed to initialize dag"); + // Ok(()) + dag.save_dag_state(*G_TEST_DAG_FORK_STATE_KEY, DagState { tips: vec![] }) + }) +} + #[allow(unused)] pub fn generate_dag_block(handle: &NodeHandle, count: usize) -> Result> { let mut result = vec![]; @@ -101,3 +139,83 @@ pub fn init_two_node() -> Result<(NodeHandle, NodeHandle, PeerId)> { }; Ok((local_handle, target_handle, target_peer_id)) } + +/// Just for test +#[allow(unused)] +pub fn execute_dag_poll_block( + registry: ServiceRef, + fork_number: BlockNumber, +) -> Result { + let timestamp = block_on(async move { + let node_config = registry + .get_shared::>() + .await + .expect("Failed to get node config"); + let time_service = node_config.net().time_service(); + let chain_service = registry + .service_ref::() + .await + .expect("failed to get chain reader service"); + let header_hash = chain_service + .main_head_header() + .await + .expect("failed to get header hash") + .id(); + let storage = registry + .get_shared::>() + .await + .expect("failed to get storage"); + let dag = registry + .get_shared::() + .await + .expect("failed to get dag"); + let mut chain = BlockChain::new(time_service, header_hash, storage, None, dag) + .expect("failed to get new the chain"); + let net = node_config.net(); + let current_number = chain.status().head().number(); + chain = test_helper::dao::modify_on_chain_config_by_dao_block( + Account::new(), + chain, + net, + test_helper::dao::vote_flexi_dag_config(net, fork_number), + test_helper::dao::on_chain_config_type_tag(FlexiDagConfig::type_tag()), + test_helper::dao::execute_script_on_chain_config(net, FlexiDagConfig::type_tag(), 0u64), + ) + .expect("failed to execute script for poll"); + + let bus = registry + .service_ref::() + .await + .expect("failed to get bus service"); + // broadcast poll blocks + for block_number in current_number + 1..=chain.status().head().number() { + let block = chain + .get_block_by_number(block_number) + .expect("failed to get block by number") + .unwrap(); + let block_info = chain + .get_block_info(Some(block.id())) + .expect("failed to get block info") + .unwrap(); + bus.broadcast(MinedBlock(Arc::new(block))) + .expect("failed to broadcast new head block"); + } + + loop { + if chain_service + .main_head_block() + .await + .expect("failed to get main head block") + .header() + .number() + == chain.status().head().number() + { + break; + } else { + async_std::task::sleep(Duration::from_millis(500)).await; + } + } + chain.time_service().now_millis() + }); + Ok(timestamp) +} diff --git a/sync/tests/full_sync_test.rs b/sync/tests/full_sync_test.rs index 852d4764ad..bc0ac758c0 100644 --- a/sync/tests/full_sync_test.rs +++ b/sync/tests/full_sync_test.rs @@ -4,25 +4,18 @@ mod test_sync; use anyhow::{Ok, Result}; use futures::executor::block_on; use rand::random; -use starcoin_chain::BlockChain; -use starcoin_chain_api::{ChainAsyncService, ChainReader, ExecutedBlock}; +use starcoin_chain_api::ChainAsyncService; use starcoin_chain_service::ChainReaderService; use starcoin_config::NodeConfig; use starcoin_crypto::HashValue; -use starcoin_dag::blockdag::BlockDAG; use starcoin_logger::prelude::*; use starcoin_node::NodeHandle; -use starcoin_service_registry::bus::{Bus, BusService}; -use starcoin_service_registry::{ActorService, RegistryAsyncService, ServiceRef}; -use starcoin_storage::Storage; +use starcoin_service_registry::{ActorService, ServiceRef}; use starcoin_sync::sync::SyncService; -use starcoin_types::block::BlockNumber; -use starcoin_types::system_events::NewHeadBlock; -use starcoin_vm_types::on_chain_config::FlexiDagConfig; use std::sync::Arc; use std::thread::sleep; use std::time::Duration; -use test_helper::{run_node_by_config, Account}; +use test_helper::run_node_by_config; #[stest::test(timeout = 120)] fn test_full_sync() { @@ -146,14 +139,11 @@ async fn check_synced( chain_service: ServiceRef, ) -> Result { loop { - if target_hash - == chain_service - .main_head_block() - .await - .expect("failed to get main head block") - .id() + if chain_service + .get_block_info_by_hash(&target_hash) + .await? + .is_some() { - debug!("succeed to sync main block id: {:?}", target_hash); break; } else { debug!("waiting for sync, now sleep 60 second"); @@ -163,97 +153,15 @@ async fn check_synced( Ok(true) } -/// Just for test -pub fn execute_dag_poll_block(node_handle: &NodeHandle, fork_number: BlockNumber) -> Result { - let timestamp = block_on(async move { - let registry = node_handle.registry(); - let node_config = registry - .get_shared::>() - .await - .expect("Failed to get node config"); - let time_service = node_config.net().time_service(); - let chain_service = registry - .service_ref::() - .await - .expect("failed to get chain reader service"); - let header_hash = chain_service - .main_head_header() - .await - .expect("failed to get header hash") - .id(); - let storage = registry - .get_shared::>() - .await - .expect("failed to get storage"); - let dag = registry - .get_shared::() - .await - .expect("failed to get dag"); - let mut chain = BlockChain::new(time_service, header_hash, storage, None, dag) - .expect("failed to get new the chain"); - let net = node_config.net(); - let current_number = chain.status().head().number(); - chain = test_helper::dao::modify_on_chain_config_by_dao_block( - Account::new(), - chain, - net, - test_helper::dao::vote_flexi_dag_config(net, fork_number), - test_helper::dao::on_chain_config_type_tag(FlexiDagConfig::type_tag()), - test_helper::dao::execute_script_on_chain_config(net, FlexiDagConfig::type_tag(), 0u64), - ) - .expect("failed to execute script for poll"); - - let bus = registry - .service_ref::() - .await - .expect("failed to get bus service"); - // broadcast poll blocks - for block_number in current_number + 1..=chain.status().head().number() { - let block = chain - .get_block_by_number(block_number) - .expect("failed to get block by number") - .unwrap(); - let block_info = chain - .get_block_info(Some(block.id())) - .expect("failed to get block info") - .unwrap(); - bus.broadcast(NewHeadBlock { - executed_block: Arc::new(ExecutedBlock::new(block, block_info)), - }) - .expect("failed to broadcast new head block"); - } - - loop { - if chain_service - .main_head_block() - .await - .expect("failed to get main head block") - .header() - .number() - == chain.status().head().number() - { - break; - } else { - async_std::task::sleep(Duration::from_millis(500)).await; - } - } - chain.time_service().now_millis() - }); - Ok(timestamp) -} - #[stest::test(timeout = 720)] -fn test_multiple_node_sync() { - let nodes = - common_test_sync_libs::init_multiple_node(5).expect("failed to initialize multiple nodes"); - - // for node in &nodes { - // execute_dag_poll_block(node, 20).expect("execute poll block failed"); - // } - - let main_node = &nodes.first().expect("failed to get main node"); +fn test_multiple_node_sync() -> Result<()> { + let node_count = 5; + let nodes = common_test_sync_libs::init_multiple_node(node_count) + .expect("failed to initialize multiple nodes"); - common_test_sync_libs::generate_block(main_node, 20).expect("failed to generate dag block"); + let main_node = nodes.first().expect("failed to get main node"); + common_test_sync_libs::generate_dag_fork_number(main_node) + .expect("failed to generate dag block"); let main_node_chain_service = main_node .chain_service() @@ -313,5 +221,6 @@ fn test_multiple_node_sync() { .stop() .expect("failed to shutdown the node normally!"); }); - }); + Ok(()) + }) } diff --git a/sync/tests/test_rpc_client.rs b/sync/tests/test_rpc_client.rs index 05fda697f7..d74d9f6aa2 100644 --- a/sync/tests/test_rpc_client.rs +++ b/sync/tests/test_rpc_client.rs @@ -10,10 +10,13 @@ use starcoin_sync::verified_rpc_client::VerifiedRpcClient; #[stest::test] fn test_verified_client_for_dag() { - starcoin_types::block::set_test_flexidag_fork_height(10); let (local_handle, target_handle, target_peer_id) = common_test_sync_libs::init_two_node() .expect("failed to initalize the local and target node"); + // common_test_sync_libs::execute_dag_poll_block(target_handle.registry().clone(), 20).expect("failed to execute the dag poll block"); + common_test_sync_libs::generate_dag_fork_number(&target_handle) + .expect("failed to execute the dag fork number"); + let network = local_handle.network(); // PeerProvider let peer_info = block_on(network.get_peer(target_peer_id)) @@ -43,7 +46,6 @@ fn test_verified_client_for_dag() { .into_iter() .all(|child| { target_dag_block.children.contains(&child) })); }); - starcoin_types::block::reset_test_custom_fork_height(); target_handle.stop().unwrap(); local_handle.stop().unwrap(); } diff --git a/types/src/block/mod.rs b/types/src/block/mod.rs index db88fa520a..0b946d44d3 100644 --- a/types/src/block/mod.rs +++ b/types/src/block/mod.rs @@ -869,33 +869,33 @@ impl Block { ); } - if !self.header.is_legacy() && !self.header.is_single() { - BlockMetadata::new_with_parents( - self.header.parent_hash(), - self.header.timestamp, - self.header.author, - self.header.author_auth_key, - uncles, - self.header.number, - self.header.chain_id, - parent_gas_used, - self.header - .parents_hash - .clone() - .expect("Parents must exist"), - ) - } else { - BlockMetadata::new( - self.header.parent_hash(), - self.header.timestamp, - self.header.author, - self.header.author_auth_key, - uncles, - self.header.number, - self.header.chain_id, - parent_gas_used, - ) - } + // if !self.header.is_legacy() && !self.header.is_single() { + BlockMetadata::new_with_parents( + self.header.parent_hash(), + self.header.timestamp, + self.header.author, + self.header.author_auth_key, + uncles, + self.header.number, + self.header.chain_id, + parent_gas_used, + self.header + .parents_hash + .clone() + .expect("Parents must exist"), + ) + // } else { + // BlockMetadata::new( + // self.header.parent_hash(), + // self.header.timestamp, + // self.header.author, + // self.header.author_auth_key, + // uncles, + // self.header.number, + // self.header.chain_id, + // parent_gas_used, + // ) + // } } pub fn random() -> Self {