Skip to content

Commit

Permalink
fix sync test case
Browse files Browse the repository at this point in the history
  • Loading branch information
jackzhhuang committed May 13, 2024
1 parent 56fc431 commit 8115e53
Show file tree
Hide file tree
Showing 7 changed files with 197 additions and 144 deletions.
16 changes: 16 additions & 0 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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::<FlexiDagConfig>()?
.map(|c| c.effective_height))
}
}
} else {
Ok(self
.statedb
Expand Down
5 changes: 5 additions & 0 deletions config/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Vec<MultiaddrWithPeerId>> = 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<HashValue> = Lazy::new(|| 0.into());

pub static G_TEST_CONFIG: Lazy<GenesisConfig> = Lazy::new(|| {
let (association_private_key, association_public_key) = genesis_multi_key_pair();
let (genesis_private_key, genesis_public_key) = genesis_key_pair();
Expand Down
8 changes: 4 additions & 4 deletions sync/src/block_connector/test_write_dag_block_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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!(
Expand Down
129 changes: 125 additions & 4 deletions sync/tests/common_test_sync_libs.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
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 {
Expand All @@ -26,7 +42,7 @@ fn gen_node(seeds: Vec<NetworkConfig>) -> 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);

Expand Down Expand Up @@ -62,6 +78,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::<ChainReaderService>()
.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::<BlockDAG>().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<Vec<DagBlockInfo>> {
let mut result = vec![];
Expand Down Expand Up @@ -101,3 +142,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<RegistryService>,
fork_number: BlockNumber,
) -> Result<u64> {
let timestamp = block_on(async move {
let node_config = registry
.get_shared::<Arc<NodeConfig>>()
.await
.expect("Failed to get node config");
let time_service = node_config.net().time_service();
let chain_service = registry
.service_ref::<ChainReaderService>()
.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::<Arc<Storage>>()
.await
.expect("failed to get storage");
let dag = registry
.get_shared::<BlockDAG>()
.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::<BusService>()
.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)
}
Loading

0 comments on commit 8115e53

Please sign in to comment.