Skip to content

Commit

Permalink
Merge 8fe5b09 into 561bf86
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjiao authored Jun 4, 2024
2 parents 561bf86 + 8fe5b09 commit f81af62
Show file tree
Hide file tree
Showing 18 changed files with 104 additions and 125 deletions.
1 change: 1 addition & 0 deletions chain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ starcoin-force-upgrade = { workspace = true }
default = []
fuzzing = ["proptest", "proptest-derive", "starcoin-types/fuzzing"]
force-deploy = ["starcoin-vm-runtime/force-deploy", "starcoin-vm-runtime", "starcoin-executor/force-deploy"]
sync-dag-test = []

[package]
authors = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions chain/mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ proptest-derive = { workspace = true }
[features]
default = []
fuzzing = ["proptest", "proptest-derive", "starcoin-types/fuzzing"]
sync-dag-test = ["starcoin-chain/sync-dag-test"]

[package]
authors = { workspace = true }
Expand Down
67 changes: 41 additions & 26 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ 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 @@ -812,13 +811,17 @@ impl BlockChain {
let final_block_gas_limit = block_gas_limit
.map(|block_gas_limit| min(block_gas_limit, on_chain_block_gas_limit))
.unwrap_or(on_chain_block_gas_limit);
let (_, tips_hash) = if current_number <= self.dag_fork_height()?.unwrap_or(u64::MAX) {
(None, None)
let dag_fork_height = self.dag_fork_height()?;
let tips_hash = if current_number <= dag_fork_height.unwrap_or(u64::MAX) {
None
} else if tips.is_some() {
(Some(self.get_block_dag_genesis(&previous_header)?), tips)
tips
} else {
let result = self.current_tips_hash(&previous_header)?.expect("the block number is larger than the dag fork number but the state data doese not exis");
(Some(result.0), Some(result.1))
Some(
self.current_tips_hash(&previous_header)?
.map(|r| r.1)
.expect("Creating a Dag block but tips don't exist"),
)
};
let strategy = epoch.strategy();
let difficulty = strategy.calculate_next_difficulty(self)?;
Expand Down Expand Up @@ -852,8 +855,8 @@ impl BlockChain {
}
};
debug!(
"Blue blocks:{:?} in chain/create_block_template_by_header",
blue_blocks
"current_number: {}/{:?}, Blue blocks:{:?} tips_hash {:?} in chain/create_block_template_by_header",
current_number, dag_fork_height, blue_blocks, tips_hash
);
let mut opened_block = OpenedBlock::new(
self.storage.clone(),
Expand Down Expand Up @@ -1713,25 +1716,27 @@ impl BlockChain {
use std::cmp::Ordering;

let dag_height = self.dag_fork_height()?.unwrap_or(u64::MAX);
if header.is_genesis() {
return Ok(DagHeaderType::Single);
}
let no_parents = header.parents_hash().unwrap_or_default().is_empty();

match (no_parents, header.number().cmp(&dag_height)) {
(true, Ordering::Greater) => {
Err(anyhow!("block header with suitable height but no parents"))
}
(true, Ordering::Greater) => Err(anyhow!(
"block header with suitable height {}/{} but no parents",
header.number(),
dag_height
)),
(false, Ordering::Greater) => Ok(DagHeaderType::Normal),

(true, Ordering::Equal) => Ok(DagHeaderType::Genesis),
(false, Ordering::Equal) => Err(anyhow!(
"block header with dag genesis height but having parents"
"block header with dag genesis height {} but having parents",
dag_height
)),

(true, Ordering::Less) => Ok(DagHeaderType::Single),
(false, Ordering::Less) => Err(anyhow!(
"block header with smaller height but having parents"
"block header with smaller height {}/{} but having parents",
header.number(),
dag_height
)),
}
}
Expand Down Expand Up @@ -2344,30 +2349,40 @@ impl BlockChain {
Ok(executed_block)
}

// todo: please remove me.
// Try to set custom dag_effective_height for `test` network for different test cases,
// or using different features to set the height.
#[cfg(feature = "sync-dag-test")]
pub fn dag_fork_height(&self) -> Result<Option<BlockNumber>> {
use starcoin_config::genesis_config::{G_TEST_DAG_FORK_HEIGHT, G_TEST_DAG_FORK_STATE_KEY};
use starcoin_state_api::StateReaderExt;
use starcoin_vm_types::on_chain_config::FlexiDagConfig;

let chain_id = self.status().head().chain_id();
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))
}
Ok(Some(u64::MAX))
}
} else {
} else if chain_id.is_dev() {
Ok(self
.statedb
.get_on_chain_config::<FlexiDagConfig>()?
.map(|c| c.effective_height))
} else {
Ok(Some(u64::MAX))
}
}

#[cfg(not(feature = "sync-dag-test"))]
pub fn dag_fork_height(&self) -> Result<Option<BlockNumber>> {
Ok(self
.statedb
.get_on_chain_config::<FlexiDagConfig>()?
.map(|c| c.effective_height))
}
}

impl ChainWriter for BlockChain {
Expand Down
20 changes: 10 additions & 10 deletions chain/src/verifier/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,16 +428,6 @@ impl BlockVerifier for DagVerifier {
//TODO: Implement it.
pub struct DagBasicVerifier;
impl BlockVerifier for DagBasicVerifier {
fn verify_uncles<R>(
_current_chain: &R,
_uncles: &[BlockHeader],
_header: &BlockHeader,
) -> Result<()>
where
R: ChainReader,
{
Ok(())
}
fn verify_header<R>(current_chain: &R, new_block_header: &BlockHeader) -> Result<()>
where
R: ChainReader,
Expand Down Expand Up @@ -468,4 +458,14 @@ impl BlockVerifier for DagBasicVerifier {
Ok(())
// ConsensusVerifier::verify_header(current_chain, new_block_header)
}
fn verify_uncles<R>(
_current_chain: &R,
_uncles: &[BlockHeader],
_header: &BlockHeader,
) -> Result<()>
where
R: ChainReader,
{
Ok(())
}
}
44 changes: 16 additions & 28 deletions chain/tests/test_block_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,20 +145,21 @@ fn test_block_chain() -> Result<()> {
}

#[stest::test(timeout = 480)]
fn test_halley_consensus() {
let mut mock_chain =
MockChain::new(ChainNetwork::new_builtin(BuiltinNetworkID::Halley)).unwrap();
fn test_halley_consensus() -> Result<()> {
let mut mock_chain = MockChain::new(ChainNetwork::new_builtin(BuiltinNetworkID::Halley))?;
let times = 20;
mock_chain.produce_and_apply_times(times).unwrap();
mock_chain.produce_and_apply_times(times)?;
assert_eq!(mock_chain.head().current_header().number(), times);
Ok(())
}

#[stest::test(timeout = 240)]
fn test_dev_consensus() {
let mut mock_chain = MockChain::new(ChainNetwork::new_builtin(BuiltinNetworkID::Dev)).unwrap();
fn test_dev_consensus() -> Result<()> {
let mut mock_chain = MockChain::new(ChainNetwork::new_builtin(BuiltinNetworkID::Dev))?;
let times = 20;
mock_chain.produce_and_apply_times(times).unwrap();
mock_chain.produce_and_apply_times(times)?;
assert_eq!(mock_chain.head().current_header().number(), times);
Ok(())
}

#[stest::test]
Expand All @@ -175,6 +176,7 @@ fn test_find_ancestor_genesis() -> Result<()> {
}

#[stest::test]
#[ignore]
fn test_find_ancestor_fork() -> Result<()> {
let mut mock_chain = MockChain::new(ChainNetwork::new_test())?;
mock_chain.produce_and_apply_times(3)?;
Expand Down Expand Up @@ -219,6 +221,7 @@ fn product_a_block(branch: &BlockChain, miner: &AccountInfo, uncles: Vec<BlockHe
}

#[stest::test(timeout = 120)]
#[ignore]
fn test_uncle() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner();
Expand All @@ -238,6 +241,7 @@ fn test_uncle() {
}

#[stest::test(timeout = 120)]
#[ignore]
fn test_uncle_exist() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();
Expand All @@ -262,6 +266,7 @@ fn test_uncle_exist() {
}

#[stest::test(timeout = 120)]
#[ignore]
fn test_uncle_son() {
let (mut mock_chain, mut fork_block_chain, _) = gen_uncle();
let miner = mock_chain.miner();
Expand All @@ -278,6 +283,7 @@ fn test_uncle_son() {
}

#[stest::test(timeout = 120)]
#[ignore]
fn test_random_uncle() {
let (mut mock_chain, _, _) = gen_uncle();
let miner = mock_chain.miner();
Expand All @@ -290,6 +296,7 @@ fn test_random_uncle() {
}

#[stest::test(timeout = 480)]
#[ignore]
fn test_switch_epoch() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();
Expand Down Expand Up @@ -328,6 +335,7 @@ fn test_switch_epoch() {
}

#[stest::test(timeout = 480)]
#[ignore]
fn test_uncle_in_diff_epoch() {
let (mut mock_chain, _, uncle_block_header) = gen_uncle();
let miner = mock_chain.miner().clone();
Expand Down Expand Up @@ -361,6 +369,7 @@ fn test_uncle_in_diff_epoch() {
/// ╭--> b3(t2)
/// Genesis--> b1--> b2(t2)
///
#[ignore]
fn test_block_chain_txn_info_fork_mapping() -> Result<()> {
let config = Arc::new(NodeConfig::random_for_test());
let mut block_chain = test_helper::gen_blockchain_for_test(config.net())?;
Expand Down Expand Up @@ -522,27 +531,6 @@ fn test_get_blocks_by_number() -> Result<()> {
Ok(())
}

#[stest::test]
fn test_block_chain_for_dag_fork() -> Result<()> {
let mut mock_chain = MockChain::new(ChainNetwork::new_test())?;

// generate the fork chain
mock_chain.produce_and_apply_times(3).unwrap();
let fork_id = mock_chain.head().current_header().id();

// create the dag chain
mock_chain.produce_and_apply_times(10).unwrap();

// create the dag chain at the fork chain
let mut fork_block_chain = mock_chain.fork_new_branch(Some(fork_id)).unwrap();
for _ in 0..15 {
let block = product_a_block(&fork_block_chain, mock_chain.miner(), Vec::new());
fork_block_chain.apply(block)?;
}

Ok(())
}

#[stest::test]
fn test_gen_dag_chain() -> Result<()> {
let fork_number = 11u64;
Expand Down
39 changes: 15 additions & 24 deletions chain/tests/test_txn_info_and_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ use rand::Rng;
use starcoin_account_api::AccountInfo;
use starcoin_accumulator::Accumulator;
use starcoin_chain_api::{ChainReader, ChainWriter};
use starcoin_config::genesis_config::{G_TEST_DAG_FORK_HEIGHT, G_TEST_DAG_FORK_STATE_KEY};
use starcoin_config::NodeConfig;
use starcoin_config::{BuiltinNetworkID, ChainNetwork, NodeConfig};
use starcoin_consensus::Consensus;
use starcoin_crypto::HashValue;
use starcoin_dag::consensusdb::consenses_state::DagState;
use starcoin_logger::prelude::debug;
use starcoin_transaction_builder::{peer_to_peer_txn_sent_as_association, DEFAULT_EXPIRATION_TIME};
use starcoin_types::account_config;
Expand Down Expand Up @@ -45,19 +43,15 @@ pub fn gen_txns(seq_num: &mut u64) -> Result<Vec<SignedUserTransaction>> {

#[stest::test(timeout = 480)]
fn test_transaction_info_and_proof_1() -> Result<()> {
let config = Arc::new(NodeConfig::random_for_test());
let mut block_chain = test_helper::gen_blockchain_for_test(config.net())?;

// set the flexidag fork height to G_TEST_DAG_FORK_HEIGHT
block_chain
.dag()
.save_dag_state(*G_TEST_DAG_FORK_STATE_KEY, DagState { tips: vec![] })?;
let net = ChainNetwork::new_builtin(BuiltinNetworkID::Dev);
let mut block_chain = test_helper::gen_blockchain_for_test(&net)?;
let test_dag_fork_height = block_chain.dag_fork_height()?.unwrap();

let _current_header = block_chain.current_header();
let miner_account = AccountInfo::random();
let mut seq_num = 0;
// generate G_TEST_DAG_FORK_HEIGHT + 5 blocks
let block_count = G_TEST_DAG_FORK_HEIGHT
// generate TEST_DAG_FORK_HEIGHT + 5 blocks
let block_count = test_dag_fork_height
.checked_add(5)
.ok_or_else(|| format_err!("overflow in calculation of the block count"))?;
(0..block_count).for_each(|_| {
Expand All @@ -67,20 +61,17 @@ fn test_transaction_info_and_proof_1() -> Result<()> {
.unwrap();
let block = block_chain
.consensus()
.create_block(template, config.net().time_service().as_ref())
.create_block(template, net.time_service().as_ref())
.unwrap();
debug!("apply block:{:?}", &block);
block_chain.apply(block).unwrap();
});
// fork from G_TEST_DAG_FORK_HEIGHT + 3 block
let fork_count = G_TEST_DAG_FORK_HEIGHT
// fork from TEST_DAG_FORK_HEIGHT + 3 block
let fork_count = test_dag_fork_height
.checked_add(3)
.ok_or_else(|| format_err!("overflow in calculation of the fork count"))?;
let fork_point = block_chain
.get_block_by_number(fork_count)
.unwrap()
.unwrap();
let mut fork_chain = block_chain.fork(fork_point.id()).unwrap();
let fork_point = block_chain.get_block_by_number(fork_count)?.unwrap();
let mut fork_chain = block_chain.fork(fork_point.id())?;
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();
Expand All @@ -96,15 +87,15 @@ fn test_transaction_info_and_proof_1() -> Result<()> {
.unwrap();
let block = fork_chain
.consensus()
.create_block(template, config.net().time_service().as_ref())
.create_block(template, net.time_service().as_ref())
.unwrap();
debug!("Apply block:{:?}", &block);
fork_chain.apply(block).unwrap();
assert_eq!(
block_chain.current_header().id(),
block_chain
.get_block_by_number(
G_TEST_DAG_FORK_HEIGHT
test_dag_fork_height
.checked_add(5)
.ok_or_else(|| format_err!("failed add the block number for overflow"))?
)
Expand All @@ -121,15 +112,15 @@ fn test_transaction_info_and_proof_1() -> Result<()> {
.unwrap();
let block = block_chain
.consensus()
.create_block(template, config.net().time_service().as_ref())
.create_block(template, net.time_service().as_ref())
.unwrap();
debug!("Apply latest block:{:?}", &block);
block_chain.apply(block).unwrap();
assert_eq!(
block_chain.current_header().id(),
block_chain
.get_block_by_number(
G_TEST_DAG_FORK_HEIGHT
test_dag_fork_height
.checked_add(6)
.ok_or_else(|| format_err!("overflow in calulation of the latest number"))?
)
Expand Down
Loading

0 comments on commit f81af62

Please sign in to comment.