diff --git a/Cargo.lock b/Cargo.lock index 007c5cd1fe..141cf80da4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10269,6 +10269,7 @@ dependencies = [ "starcoin-account-api", "starcoin-account-service", "starcoin-block-relayer", + "starcoin-chain-api", "starcoin-chain-notify", "starcoin-chain-service", "starcoin-config", diff --git a/chain/Cargo.toml b/chain/Cargo.toml index e5b41bfea9..04891e96f3 100644 --- a/chain/Cargo.toml +++ b/chain/Cargo.toml @@ -48,6 +48,7 @@ starcoin-network-rpc-api = { workspace = true } [features] default = [] fuzzing = ["proptest", "proptest-derive", "starcoin-types/fuzzing"] +testing = [] [package] authors = { workspace = true } diff --git a/chain/api/Cargo.toml b/chain/api/Cargo.toml index 71c6c01818..3be7166734 100644 --- a/chain/api/Cargo.toml +++ b/chain/api/Cargo.toml @@ -22,6 +22,7 @@ starcoin-config = { workspace = true } [features] mock = [] +testing = [] [package] authors = { workspace = true } diff --git a/chain/api/src/message.rs b/chain/api/src/message.rs index 7324d42a86..508bdbb3ef 100644 --- a/chain/api/src/message.rs +++ b/chain/api/src/message.rs @@ -63,6 +63,7 @@ pub enum ChainRequest { GetDagBlockChildren { block_ids: Vec, }, + GetDagForkNumber, } impl ServiceRequest for ChainRequest { @@ -91,4 +92,5 @@ pub enum ChainResponse { HashVec(Vec), TransactionProof(Box>), BlockInfoVec(Box>>), + DagForkNumber(BlockNumber), } diff --git a/chain/api/src/service.rs b/chain/api/src/service.rs index a898ced214..acff76f07a 100644 --- a/chain/api/src/service.rs +++ b/chain/api/src/service.rs @@ -141,6 +141,7 @@ pub trait ChainAsyncService: async fn get_block_infos(&self, hashes: Vec) -> Result>>; async fn get_dag_block_children(&self, hashes: Vec) -> Result>; + async fn dag_fork_number(&self) -> Result; } #[async_trait::async_trait] @@ -449,4 +450,12 @@ where bail!("get dag block children error") } } + + async fn dag_fork_number(&self) -> Result { + if let ChainResponse::DagForkNumber(fork_number) = self.send(ChainRequest::GetDagForkNumber).await?? { + Ok(fork_number) + } else { + bail!("Get dag form number response error.") + } + } } diff --git a/chain/mock/Cargo.toml b/chain/mock/Cargo.toml index cb89288f27..7cc3b1d3e5 100644 --- a/chain/mock/Cargo.toml +++ b/chain/mock/Cargo.toml @@ -11,7 +11,7 @@ proptest = { default-features = false, optional = true, workspace = true } proptest-derive = { default-features = false, optional = true, workspace = true } starcoin-account-api = { workspace = true } starcoin-accumulator = { package = "starcoin-accumulator", workspace = true } -starcoin-chain = { workspace = true } +starcoin-chain = { workspace = true, features = ["testing"] } starcoin-config = { workspace = true } starcoin-consensus = { workspace = true } starcoin-executor = { package = "starcoin-executor", workspace = true } @@ -27,11 +27,12 @@ starcoin-dag = { workspace = true } [dev-dependencies] proptest = { workspace = true } proptest-derive = { workspace = true } -starcoin-chain = { workspace = true } +starcoin-chain = { workspace = true, features = ["testing"] } [features] default = [] fuzzing = ["proptest", "proptest-derive", "starcoin-types/fuzzing"] +testing = [] [package] authors = { workspace = true } diff --git a/chain/mock/src/mock_chain.rs b/chain/mock/src/mock_chain.rs index 5134dfeeca..5cb24db969 100644 --- a/chain/mock/src/mock_chain.rs +++ b/chain/mock/src/mock_chain.rs @@ -10,11 +10,11 @@ use starcoin_crypto::HashValue; use starcoin_dag::blockdag::BlockDAG; use starcoin_genesis::Genesis; use starcoin_logger::prelude::*; -use starcoin_storage::Storage; +use starcoin_storage::{BlockStore, Storage}; +use starcoin_types::block::BlockNumber; use starcoin_types::block::{Block, BlockHeader}; use starcoin_types::startup_info::ChainInfo; use std::sync::Arc; -use starcoin_types::block::BlockNumber; pub struct MockChain { net: ChainNetwork, @@ -106,10 +106,6 @@ impl MockChain { ) } - pub fn set_test_flexidag_fork_height(&mut self, fork_number: BlockNumber) { - self.head.set_test_flexidag_fork_height(fork_number); - } - pub fn fork(&self, head_id: Option) -> Result { let chain = self.fork_new_branch(head_id)?; Ok(Self { @@ -202,4 +198,12 @@ impl MockChain { pub fn miner(&self) -> &AccountInfo { &self.miner } + + pub fn set_dag_fork_number(&self, number: BlockNumber) -> Result<()> { + self.storage.save_dag_fork_number(number) + } + + pub fn get_dag_fork_number(&self) -> Result> { + self.storage.get_dag_fork_number() + } } diff --git a/chain/service/Cargo.toml b/chain/service/Cargo.toml index 120c0b1acc..db135ded67 100644 --- a/chain/service/Cargo.toml +++ b/chain/service/Cargo.toml @@ -27,9 +27,12 @@ starcoin-accumulator = { package = "starcoin-accumulator", workspace = true } [dev-dependencies] stest = { workspace = true } test-helper = { workspace = true } +starcoin-chain-api = { workspace = true, features = ["testing"] } +starcoin-chain = { workspace = true, features = ["testing"] } [features] mock = [] +testing = [] [package] authors = { workspace = true } diff --git a/chain/service/src/chain_service.rs b/chain/service/src/chain_service.rs index 1b6f7e9f85..f68815c876 100644 --- a/chain/service/src/chain_service.rs +++ b/chain/service/src/chain_service.rs @@ -1,7 +1,7 @@ // Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 -use anyhow::{format_err, Error, Result}; +use anyhow::{format_err, Error, Ok, Result}; use starcoin_chain::BlockChain; use starcoin_chain_api::message::{ChainRequest, ChainResponse}; use starcoin_chain_api::{ @@ -243,6 +243,7 @@ impl ServiceHandler for ChainReaderService { ChainRequest::GetDagBlockChildren { block_ids } => Ok(ChainResponse::HashVec( self.inner.get_dag_block_children(block_ids)?, )), + ChainRequest::GetDagForkNumber => Ok(ChainResponse::DagForkNumber(self.inner.main.dag_fork_height())), } } } diff --git a/chain/src/chain.rs b/chain/src/chain.rs index 7e9f3762d6..e677d8147c 100644 --- a/chain/src/chain.rs +++ b/chain/src/chain.rs @@ -63,7 +63,6 @@ pub struct BlockChain { epoch: Epoch, vm_metrics: Option, dag: BlockDAG, - dag_fork_number: BlockNumber, } impl BlockChain { @@ -124,7 +123,6 @@ impl BlockChain { epoch, vm_metrics, dag, - dag_fork_number: TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH, }; watch(CHAIN_WATCH_NAME, "n1251"); match uncles { @@ -182,10 +180,6 @@ impl BlockChain { self.dag.clone() } - pub fn set_test_flexidag_fork_height(&mut self, fork_number: BlockNumber) { - self.dag_fork_number = fork_number; - } - //TODO lazy init uncles cache. fn update_uncle_cache(&mut self) -> Result<()> { self.uncles = self.epoch_uncles()?; @@ -1138,17 +1132,22 @@ impl ChainReader for BlockChain { self.dag.has_dag_block(hash) } - #[cfg(not(test))] - fn dag_fork_height(&self) -> BlockNumber { - 100000 - } + // #[cfg(not(feature = "testing"))] + // fn dag_fork_height(&self) -> BlockNumber { + // TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH + // } - #[cfg(test)] fn dag_fork_height(&self) -> BlockNumber { - self.dag_fork_number + let fork_number = match self.storage.get_dag_fork_number().expect("failed to read dag fork number") { + Some(fork_number) => fork_number, + None => TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH, + }; + println!("jacktest: in is_dag, dag fork height: {:?}", fork_number); + fork_number } fn is_dag(&self, block_header: &BlockHeader) -> bool { + println!("jacktest: in is_dag, dag fork height: {:?}", self.dag_fork_height()); block_header.number() > self.dag_fork_height() } @@ -1157,6 +1156,7 @@ impl ChainReader for BlockChain { } fn is_dag_genesis(&self, block_header: &BlockHeader) -> bool { + println!("jacktest: in is_dag_genesis, dag fork height: {:?}", self.dag_fork_height()); block_header.number() == self.dag_fork_height() } } diff --git a/chain/tests/test_txn_info_and_proof.rs b/chain/tests/test_txn_info_and_proof.rs index f8f9c9ab9f..dddd03cd3c 100644 --- a/chain/tests/test_txn_info_and_proof.rs +++ b/chain/tests/test_txn_info_and_proof.rs @@ -43,10 +43,9 @@ pub fn gen_txns(seq_num: &mut u64) -> Result> { #[stest::test(timeout = 480)] fn test_transaction_info_and_proof_1() -> Result<()> { - starcoin_types::block::set_test_flexidag_fork_height(2); // generate 5 block let config = Arc::new(NodeConfig::random_for_test()); - let mut block_chain = test_helper::gen_blockchain_for_test(config.net())?; + let mut block_chain: as Try>::Output = test_helper::gen_blockchain_for_test(config.net())?; block_chain.set_test_flexidag_fork_height(2); let _current_header = block_chain.current_header(); let miner_account = AccountInfo::random(); @@ -106,7 +105,6 @@ fn test_transaction_info_and_proof_1() -> Result<()> { block_chain.current_header().id(), block_chain.get_block_by_number(6).unwrap().unwrap().id() ); - starcoin_types::block::reset_test_custom_fork_height(); Ok(()) } diff --git a/flexidag/dag/src/blockdag.rs b/flexidag/dag/src/blockdag.rs index 5e20d5091e..eff29ff8b2 100644 --- a/flexidag/dag/src/blockdag.rs +++ b/flexidag/dag/src/blockdag.rs @@ -169,7 +169,9 @@ mod tests { use super::*; use crate::consensusdb::prelude::FlexiDagStorageConfig; use starcoin_config::RocksdbConfig; - use starcoin_types::block::{BlockHeader, BlockHeaderBuilder, TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG}; + use starcoin_types::block::{ + BlockHeader, BlockHeaderBuilder, TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG, + }; use std::{env, fs}; fn build_block_dag(k: KType) -> BlockDAG { diff --git a/node/Cargo.toml b/node/Cargo.toml index da0aa8bdb5..32822aa65a 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -49,8 +49,15 @@ timeout-join-handler = { workspace = true } tokio = { features = ["full"], workspace = true } num_cpus = { workspace = true } starcoin-dag = { workspace = true } +starcoin-chain-api = { workspace = true, features = ["testing"] } + [dev-dependencies] stest = { workspace = true } +starcoin-chain-service = { workspace = true, features = ["testing"] } +starcoin-chain-api = { workspace = true, features = ["testing"] } + +[features] +testing = [] [package] authors = { workspace = true } diff --git a/node/src/lib.rs b/node/src/lib.rs index 271fe5f6c1..7e4381a974 100644 --- a/node/src/lib.rs +++ b/node/src/lib.rs @@ -18,7 +18,7 @@ use starcoin_node_api::node_service::NodeAsyncService; use starcoin_rpc_server::service::RpcService; use starcoin_service_registry::bus::{Bus, BusService}; use starcoin_service_registry::{RegistryAsyncService, RegistryService, ServiceInfo, ServiceRef}; -use starcoin_storage::Storage; +use starcoin_storage::{BlockStore, Storage}; use starcoin_sync::sync::SyncService; use starcoin_txpool::TxPoolService; use starcoin_types::block::Block; @@ -26,6 +26,7 @@ use starcoin_types::system_events::{GenerateBlockEvent, NewHeadBlock}; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Runtime; +use starcoin_types::block::BlockNumber; pub mod crash_handler; mod genesis_parameter_resolve; @@ -183,7 +184,7 @@ impl NodeHandle { } /// Just for test - pub fn generate_block(&self) -> Result { + pub fn generate_block(&self) -> Result<(Block, bool)> { let registry = &self.registry; block_on(async move { let bus = registry.service_ref::().await?; @@ -211,9 +212,15 @@ impl NodeHandle { bail!("Wait timeout for generate_block") } }; - Ok(block) + + let is_dag_block = chain_service.dag_fork_number().await? < block.header().number(); + Ok((block, is_dag_block)) }) } + + pub fn set_dag_fork_number(&self, fork_number: BlockNumber) -> Result<()> { + self.storage().save_dag_fork_number(fork_number) + } } pub fn run_node_by_opt( diff --git a/storage/src/chain_info/mod.rs b/storage/src/chain_info/mod.rs index 43da404fd5..4937bbdda4 100644 --- a/storage/src/chain_info/mod.rs +++ b/storage/src/chain_info/mod.rs @@ -4,7 +4,9 @@ use crate::storage::{ColumnFamily, InnerStorage, KVStore}; use crate::{StorageVersion, CHAIN_INFO_PREFIX_NAME}; use anyhow::Result; +use bcs_ext::BCSCodec; use starcoin_crypto::HashValue; +use starcoin_types::block::BlockNumber; use starcoin_types::startup_info::{BarnardHardFork, DagState, SnapshotRange, StartupInfo}; use std::convert::{TryFrom, TryInto}; @@ -29,6 +31,22 @@ impl ChainInfoStorage { const SNAPSHOT_RANGE_KEY: &'static str = "snapshot_height"; const BARNARD_HARD_FORK: &'static str = "barnard_hard_fork"; const DAG_STATE_KEY: &'static str = "dag_state"; + const DAG_FORK_NUMBER: &'static str = "dag_fork_number"; + + pub fn save_dag_fork_number(&self, fork_number: BlockNumber) -> Result<()> { + self.put_sync( + Self::DAG_FORK_NUMBER.as_bytes().to_vec(), + fork_number.encode()?, + ) + } + + pub fn get_dag_fork_number(&self) -> Result> { + self.get(Self::DAG_FORK_NUMBER.as_bytes()) + .and_then(|bytes| match bytes { + Some(bytes) => Ok(Some(BlockNumber::decode(bytes.as_slice())?)), + None => Ok(None), + }) + } pub fn save_dag_state(&self, dag_state: DagState) -> Result<()> { self.put_sync( diff --git a/storage/src/lib.rs b/storage/src/lib.rs index db7c3c79fa..f2fc3f33f1 100644 --- a/storage/src/lib.rs +++ b/storage/src/lib.rs @@ -21,6 +21,7 @@ use starcoin_accumulator::node::AccumulatorStoreType; use starcoin_accumulator::AccumulatorTreeStore; use starcoin_crypto::HashValue; use starcoin_state_store_api::{StateNode, StateNodeStore}; +use starcoin_types::block::BlockNumber; use starcoin_types::contract_event::ContractEvent; use starcoin_types::startup_info::{ChainInfo, ChainStatus, DagState, SnapshotRange}; use starcoin_types::transaction::{RichTransactionInfo, Transaction}; @@ -258,6 +259,9 @@ pub trait BlockStore { fn get_dag_state(&self) -> Result>; fn save_dag_state(&self, dag_state: DagState) -> Result<()>; + + fn save_dag_fork_number(&self, fork_number: BlockNumber) -> Result<()>; + fn get_dag_fork_number(&self) -> Result>; } pub trait BlockTransactionInfoStore { @@ -512,6 +516,14 @@ impl BlockStore for Storage { fn save_dag_state(&self, dag_state: DagState) -> Result<()> { self.chain_info_storage.save_dag_state(dag_state) } + + fn save_dag_fork_number(&self, fork_number: BlockNumber) -> Result<()> { + self.chain_info_storage.save_dag_fork_number(fork_number) + } + + fn get_dag_fork_number(&self) -> Result> { + self.chain_info_storage.get_dag_fork_number() + } } impl BlockInfoStore for Storage { diff --git a/sync/Cargo.toml b/sync/Cargo.toml index c11ccecf7a..38e76f00e5 100644 --- a/sync/Cargo.toml +++ b/sync/Cargo.toml @@ -46,15 +46,16 @@ starcoin-consensus = { workspace = true } timeout-join-handler = { workspace = true } starcoin-flexidag = { workspace = true } starcoin-dag = { workspace = true } +starcoin-chain-mock = { workspace = true, features = ["testing"] } [dev-dependencies] hex = { workspace = true } starcoin-miner = { workspace = true } starcoin-account-api = { workspace = true } starcoin-block-relayer = { workspace = true } -starcoin-chain-mock = { workspace = true } +starcoin-chain-mock = { workspace = true, features = ["testing"] } starcoin-consensus = { workspace = true } -starcoin-node = { workspace = true } +starcoin-node = { workspace = true, features = ["testing"] } starcoin-state-service = { workspace = true } starcoin-statedb = { workspace = true } starcoin-txpool-mock-service = { workspace = true } @@ -63,6 +64,9 @@ test-helper = { workspace = true } tokio = { features = ["full"], workspace = true } starcoin-genesis = { workspace = true } +[features] +testing = [] + [package] authors = { workspace = true } edition = { workspace = true } diff --git a/sync/src/tasks/mock.rs b/sync/src/tasks/mock.rs index 526f7b280b..da385812fb 100644 --- a/sync/src/tasks/mock.rs +++ b/sync/src/tasks/mock.rs @@ -243,10 +243,6 @@ impl SyncNodeMocker { } } - pub fn set_test_flexidag_fork_height(&mut self, fork_number: BlockNumber) { - self.chain_mocker.set_test_flexidag_fork_height(fork_number); - } - pub fn peer_info(&self) -> PeerInfo { PeerInfo::new( self.peer_id.clone(), @@ -341,6 +337,14 @@ impl SyncNodeMocker { .select_peer() .ok_or_else(|| format_err!("No peers for send request.")) } + + pub fn set_dag_fork_number(&self, fork_number: BlockNumber) -> Result<()> { + self.chain_mocker.set_dag_fork_number(fork_number) + } + + // pub fn get_dag_fork_number(&self) -> Result> { + // self.chain_mocker.get_dag_fork_number() + // } } impl PeerOperator for SyncNodeMocker { diff --git a/sync/src/tasks/test_tools.rs b/sync/src/tasks/test_tools.rs index 405b5b68b5..89ecc864aa 100644 --- a/sync/src/tasks/test_tools.rs +++ b/sync/src/tasks/test_tools.rs @@ -23,6 +23,8 @@ use starcoin_storage::Storage; // use starcoin_txpool_mock_service::MockTxPoolService; #[cfg(test)] use starcoin_txpool_mock_service::MockTxPoolService; +use starcoin_types::block::BlockNumber; +use starcoin_types::U256; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -130,11 +132,11 @@ impl SyncTestSystem { #[cfg(test)] pub async fn full_sync_new_node(fork_number: BlockNumber) -> Result<()> { - use starcoin_types::block::BlockNumber; - + let count_blocks = 10; + assert!(fork_number < count_blocks, ""); let net1 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); let mut node1 = SyncNodeMocker::new(net1, 300, 0)?; - node1.set_test_flexidag_fork_height(fork_number); + node1.set_dag_fork_number(fork_number)?; node1.produce_block(10)?; let mut arc_node1 = Arc::new(node1); @@ -142,7 +144,7 @@ pub async fn full_sync_new_node(fork_number: BlockNumber) -> Result<()> { let net2 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); let node2 = SyncNodeMocker::new(net2.clone(), 300, 0)?; - node2.set_test_flexidag_fork_height(fork_number); + node2.set_dag_fork_number(fork_number)?; let target = arc_node1.sync_target(); @@ -214,6 +216,65 @@ pub async fn full_sync_new_node(fork_number: BlockNumber) -> Result<()> { Ok(()) } +#[cfg(test)] +pub async fn sync_invalid_target(fork_number: BlockNumber) -> Result<()> { + use stream_task::TaskError; + + use crate::verified_rpc_client::RpcVerifyError; + + let net1 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); + let mut node1 = SyncNodeMocker::new(net1, 300, 0)?; + node1.set_dag_fork_number(fork_number)?; + node1.produce_block(10)?; + + let arc_node1 = Arc::new(node1); + + let net2 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); + + let node2 = SyncNodeMocker::new(net2.clone(), 300, 0)?; + node2.set_dag_fork_number(fork_number)?; + let dag = node2.chain().dag(); + let mut target = arc_node1.sync_target(); + + target.block_info.total_difficulty = U256::max_value(); + + let current_block_header = node2.chain().current_header(); + + let storage = node2.chain().get_storage(); + let (sender_1, receiver_1) = unbounded(); + let (sender_2, _receiver_2) = unbounded(); + let (sync_task, _task_handle, _task_event_counter) = full_sync_task( + current_block_header.id(), + target.clone(), + false, + net2.time_service(), + storage.clone(), + sender_1, + arc_node1.clone(), + sender_2, + DummyNetworkService::default(), + 15, + None, + None, + dag, + )?; + let _join_handle = node2.process_block_connect_event(receiver_1).await; + let sync_result = sync_task.await; + assert!(sync_result.is_err()); + let err = sync_result.err().unwrap(); + debug!("task_error: {:?}", err); + assert!(err.is_break_error()); + if let TaskError::BreakError(err) = err { + let verify_err = err.downcast::().unwrap(); + assert_eq!(verify_err.peers[0].clone(), arc_node1.peer_id); + debug!("{:?}", verify_err) + } else { + panic!("Expect BreakError, but got: {:?}", err) + } + + Ok(()) +} + // #[cfg(test)] // pub async fn generate_red_dag_block() -> Result { // let net = ChainNetwork::new_builtin(BuiltinNetworkID::Test); diff --git a/sync/src/tasks/tests.rs b/sync/src/tasks/tests.rs index 5e38c9930f..8be23fb450 100644 --- a/sync/src/tasks/tests.rs +++ b/sync/src/tasks/tests.rs @@ -8,7 +8,6 @@ use crate::tasks::{ full_sync_task, AccumulatorCollector, AncestorCollector, BlockAccumulatorSyncTask, BlockCollector, BlockFetcher, BlockLocalStore, BlockSyncTask, FindAncestorTask, SyncFetcher, }; -use crate::verified_rpc_client::RpcVerifyError; use anyhow::{format_err, Result}; use anyhow::{Context, Ok}; use futures::channel::mpsc::unbounded; @@ -30,76 +29,27 @@ use starcoin_genesis::Genesis; use starcoin_logger::prelude::*; use starcoin_storage::{BlockStore, Storage}; use starcoin_sync_api::SyncTarget; +use starcoin_types::block::TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH; use starcoin_types::{ block::{Block, BlockBody, BlockHeaderBuilder, BlockIdAndNumber, BlockInfo}, U256, }; use std::collections::HashMap; use std::sync::{Arc, Mutex}; -use stream_task::{ - DefaultCustomErrorHandle, Generator, TaskError, TaskEventCounterHandle, TaskGenerator, -}; +use stream_task::{DefaultCustomErrorHandle, Generator, TaskEventCounterHandle, TaskGenerator}; use test_helper::DummyNetworkService; -use super::test_tools::{full_sync_new_node, SyncTestSystem}; +use super::test_tools::{full_sync_new_node, sync_invalid_target, SyncTestSystem}; use super::BlockConnectedEvent; #[stest::test(timeout = 120)] pub async fn test_full_sync_new_node() -> Result<()> { - full_sync_new_node(false).await + full_sync_new_node(TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH).await } #[stest::test] pub async fn test_sync_invalid_target() -> Result<()> { - let net1 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); - let mut node1 = SyncNodeMocker::new(net1, 300, 0)?; - node1.produce_block(10)?; - - let arc_node1 = Arc::new(node1); - - let net2 = ChainNetwork::new_builtin(BuiltinNetworkID::Test); - - let node2 = SyncNodeMocker::new(net2.clone(), 300, 0)?; - let dag = node2.chain().dag(); - let mut target = arc_node1.sync_target(); - - target.block_info.total_difficulty = U256::max_value(); - - let current_block_header = node2.chain().current_header(); - - let storage = node2.chain().get_storage(); - let (sender_1, receiver_1) = unbounded(); - let (sender_2, _receiver_2) = unbounded(); - let (sync_task, _task_handle, _task_event_counter) = full_sync_task( - current_block_header.id(), - target.clone(), - false, - net2.time_service(), - storage.clone(), - sender_1, - arc_node1.clone(), - sender_2, - DummyNetworkService::default(), - 15, - None, - None, - dag, - )?; - let _join_handle = node2.process_block_connect_event(receiver_1).await; - let sync_result = sync_task.await; - assert!(sync_result.is_err()); - let err = sync_result.err().unwrap(); - debug!("task_error: {:?}", err); - assert!(err.is_break_error()); - if let TaskError::BreakError(err) = err { - let verify_err = err.downcast::().unwrap(); - assert_eq!(verify_err.peers[0].clone(), arc_node1.peer_id); - debug!("{:?}", verify_err) - } else { - panic!("Expect BreakError, but got: {:?}", err) - } - - Ok(()) + sync_invalid_target(TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH).await } #[stest::test] diff --git a/sync/src/tasks/tests_dag.rs b/sync/src/tasks/tests_dag.rs index 018431aee8..3f8a6cace1 100644 --- a/sync/src/tasks/tests_dag.rs +++ b/sync/src/tasks/tests_dag.rs @@ -19,7 +19,7 @@ use test_helper::DummyNetworkService; #[stest::test(timeout = 120)] pub async fn test_full_sync_new_node_dag() { - full_sync_new_node(true) + full_sync_new_node(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG) .await .expect("dag full sync should success"); } @@ -103,10 +103,10 @@ async fn test_sync_single_chain_to_dag_chain() -> Result<()> { let test_system = super::test_tools::SyncTestSystem::initialize_sync_system().await?; test_system .target_node - .set_test_flexidag_fork_height(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG); + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG)?; test_system .local_node - .set_test_flexidag_fork_height(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG); + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG)?; let (_local_node, _target_node) = sync_block_in_block_connection_service_mock( Arc::new(test_system.target_node), Arc::new(test_system.local_node), @@ -117,17 +117,17 @@ async fn test_sync_single_chain_to_dag_chain() -> Result<()> { Ok(()) } -#[stest::test(timeout = 600)] +#[stest::test(timeout = 120)] async fn test_sync_red_blocks_dag() -> Result<()> { let test_system = super::test_tools::SyncTestSystem::initialize_sync_system() .await .expect("failed to init system"); test_system .target_node - .set_test_flexidag_fork_height(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG); + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG)?; test_system .local_node - .set_test_flexidag_fork_height(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG); + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG)?; let mut target_node = Arc::new(test_system.target_node); let local_node = Arc::new(test_system.local_node); Arc::get_mut(&mut target_node) diff --git a/sync/tests/test_rpc_client.rs b/sync/tests/test_rpc_client.rs index d9f493d142..53549f4ce4 100644 --- a/sync/tests/test_rpc_client.rs +++ b/sync/tests/test_rpc_client.rs @@ -9,7 +9,7 @@ use starcoin_crypto::HashValue; use starcoin_logger::prelude::*; use starcoin_node::NodeHandle; use starcoin_sync::verified_rpc_client::VerifiedRpcClient; -use starcoin_types::block::BlockHeader; +use starcoin_types::block::{BlockHeader, TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG}; use std::sync::Arc; #[derive(Debug, Clone)] @@ -23,6 +23,13 @@ fn test_verified_client_for_dag() { let (local_handle, target_handle, target_peer_id) = init_two_node().expect("failed to initalize the local and target node"); + target_handle + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG) + .expect("set fork number error"); + local_handle + .set_dag_fork_number(TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG) + .expect("set fork number error"); + let network = local_handle.network(); // PeerProvider let peer_info = block_on(network.get_peer(target_peer_id)) @@ -79,8 +86,8 @@ fn generate_dag_block(handle: &NodeHandle, count: usize) -> Result>; //TODO: make sure height -pub static TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG: BlockNumber = 8; -pub static TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH: BlockNumber = 100000; +pub static TEST_FLEXIDAG_FORK_HEIGHT_FOR_DAG: BlockNumber = 4; +pub static TEST_FLEXIDAG_FORK_HEIGHT_NEVER_REACH: BlockNumber = 10000; // static DEV_FLEXIDAG_FORK_HEIGHT: BlockNumber = 2; // static PROXIMA_FLEXIDAG_FORK_HEIGHT: BlockNumber = 10000; // static HALLEY_FLEXIDAG_FORK_HEIGHT: BlockNumber = 10000;