Skip to content

Commit

Permalink
add mock code that mock fork number
Browse files Browse the repository at this point in the history
  • Loading branch information
jackzhhuang committed Jan 26, 2024
1 parent 55bdf16 commit 832cd35
Show file tree
Hide file tree
Showing 23 changed files with 197 additions and 104 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions chain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ starcoin-network-rpc-api = { workspace = true }
[features]
default = []
fuzzing = ["proptest", "proptest-derive", "starcoin-types/fuzzing"]
testing = []

[package]
authors = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions chain/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ starcoin-config = { workspace = true }

[features]
mock = []
testing = []

[package]
authors = { workspace = true }
Expand Down
2 changes: 2 additions & 0 deletions chain/api/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub enum ChainRequest {
GetDagBlockChildren {
block_ids: Vec<HashValue>,
},
GetDagForkNumber,
}

impl ServiceRequest for ChainRequest {
Expand Down Expand Up @@ -91,4 +92,5 @@ pub enum ChainResponse {
HashVec(Vec<HashValue>),
TransactionProof(Box<Option<TransactionInfoWithProof>>),
BlockInfoVec(Box<Vec<Option<BlockInfo>>>),
DagForkNumber(BlockNumber),
}
9 changes: 9 additions & 0 deletions chain/api/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ pub trait ChainAsyncService:

async fn get_block_infos(&self, hashes: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>>;
async fn get_dag_block_children(&self, hashes: Vec<HashValue>) -> Result<Vec<HashValue>>;
async fn dag_fork_number(&self) -> Result<BlockNumber>;
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -449,4 +450,12 @@ where
bail!("get dag block children error")
}
}

async fn dag_fork_number(&self) -> Result<BlockNumber> {
if let ChainResponse::DagForkNumber(fork_number) = self.send(ChainRequest::GetDagForkNumber).await?? {
Ok(fork_number)
} else {
bail!("Get dag form number response error.")
}
}
}
5 changes: 3 additions & 2 deletions chain/mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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 }
Expand Down
16 changes: 10 additions & 6 deletions chain/mock/src/mock_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<HashValue>) -> Result<MockChain> {
let chain = self.fork_new_branch(head_id)?;
Ok(Self {
Expand Down Expand Up @@ -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<Option<BlockNumber>> {
self.storage.get_dag_fork_number()
}
}
3 changes: 3 additions & 0 deletions chain/service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
3 changes: 2 additions & 1 deletion chain/service/src/chain_service.rs
Original file line number Diff line number Diff line change
@@ -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::{
Expand Down Expand Up @@ -243,6 +243,7 @@ impl ServiceHandler<Self, ChainRequest> 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())),
}
}
}
Expand Down
24 changes: 12 additions & 12 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ pub struct BlockChain {
epoch: Epoch,
vm_metrics: Option<VMMetrics>,
dag: BlockDAG,
dag_fork_number: BlockNumber,
}

impl BlockChain {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()?;
Expand Down Expand Up @@ -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()
}

Expand All @@ -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()
}
}
Expand Down
4 changes: 1 addition & 3 deletions chain/tests/test_txn_info_and_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,9 @@ pub fn gen_txns(seq_num: &mut u64) -> Result<Vec<SignedUserTransaction>> {

#[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: <std::prelude::v1::Result<_, anyhow::Error> 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();
Expand Down Expand Up @@ -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(())
}

Expand Down
4 changes: 3 additions & 1 deletion flexidag/dag/src/blockdag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
13 changes: 10 additions & 3 deletions node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ 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;
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;
Expand Down Expand Up @@ -183,7 +184,7 @@ impl NodeHandle {
}

/// Just for test
pub fn generate_block(&self) -> Result<Block> {
pub fn generate_block(&self) -> Result<(Block, bool)> {
let registry = &self.registry;
block_on(async move {
let bus = registry.service_ref::<BusService>().await?;
Expand Down Expand Up @@ -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(
Expand Down
18 changes: 18 additions & 0 deletions storage/src/chain_info/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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<Option<BlockNumber>> {
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(
Expand Down
12 changes: 12 additions & 0 deletions storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -258,6 +259,9 @@ pub trait BlockStore {
fn get_dag_state(&self) -> Result<Option<DagState>>;

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<Option<BlockNumber>>;
}

pub trait BlockTransactionInfoStore {
Expand Down Expand Up @@ -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<Option<BlockNumber>> {
self.chain_info_storage.get_dag_fork_number()
}
}

impl BlockInfoStore for Storage {
Expand Down
8 changes: 6 additions & 2 deletions sync/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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 }
Expand Down
Loading

0 comments on commit 832cd35

Please sign in to comment.