Skip to content

Commit

Permalink
fix fmt and clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
jackzhhuang committed Apr 1, 2024
1 parent c61190a commit f57968b
Show file tree
Hide file tree
Showing 24 changed files with 489 additions and 246 deletions.
5 changes: 4 additions & 1 deletion chain/api/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ pub trait ChainReader {
access_path: Option<AccessPath>,
) -> Result<Option<TransactionInfoWithProof>>;

fn current_tips_hash(&self, header: &BlockHeader) -> Result<Option<(HashValue, Vec<HashValue>)>>;
fn current_tips_hash(
&self,
header: &BlockHeader,
) -> Result<Option<(HashValue, Vec<HashValue>)>>;
fn has_dag_block(&self, header_id: HashValue) -> Result<bool>;
}

Expand Down
7 changes: 3 additions & 4 deletions chain/api/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub trait ReadableChainService {

fn get_block_infos(&self, ids: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>>;
fn get_dag_block_children(&self, ids: Vec<HashValue>) -> Result<Vec<HashValue>>;
fn get_dag_state(&self,) -> Result<DagStateView>;
fn get_dag_state(&self) -> Result<DagStateView>;
}

/// Writeable block chain service trait
Expand Down Expand Up @@ -143,7 +143,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 get_dag_state(&self,) -> Result<DagStateView>;
async fn get_dag_state(&self) -> Result<DagStateView>;
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -453,8 +453,7 @@ where
}
}


async fn get_dag_state(&self,) -> Result<DagStateView> {
async fn get_dag_state(&self) -> Result<DagStateView> {
let response = self.send(ChainRequest::GetDagStateView).await??;
if let ChainResponse::DagStateView(dag_state) = response {
Ok(*dag_state)
Expand Down
18 changes: 11 additions & 7 deletions chain/service/src/chain_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,9 +244,9 @@ impl ServiceHandler<Self, ChainRequest> for ChainReaderService {
ChainRequest::GetDagBlockChildren { block_ids } => Ok(ChainResponse::HashVec(
self.inner.get_dag_block_children(block_ids)?,
)),
ChainRequest::GetDagStateView => Ok(ChainResponse::DagStateView(
Box::new(self.inner.get_dag_state()?),
)),
ChainRequest::GetDagStateView => Ok(ChainResponse::DagStateView(Box::new(
self.inner.get_dag_state()?,
))),
}
}
}
Expand Down Expand Up @@ -449,16 +449,20 @@ impl ReadableChainService for ChainReaderServiceInner {
}
})
}
fn get_dag_state(&self,) -> Result<DagStateView> {

fn get_dag_state(&self) -> Result<DagStateView> {
let head = self.main.current_header();
if !head.is_dag() {
bail!("The chain is still not a dag and its dag fork number is {} and the current is {}.", head.dag_fork_height(), head.number());
bail!(
"The chain is still not a dag and its dag fork number is {} and the current is {}.",
head.dag_fork_height(),
head.number()
);
}
let (dag_genesis, state) = self.main.get_dag_state_by_block(&head)?;
Ok(DagStateView {
dag_genesis,
tips: state.tips.clone(),
tips: state.tips,
})
}
}
Expand Down
51 changes: 29 additions & 22 deletions chain/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,13 +409,16 @@ impl BlockChain {
bail!("Block is not a dag block.");
}

let results = header.parents_hash().ok_or(anyhow!("dag block has no parents."))?.into_iter().map(|parent_hash| {
let header = self.storage.get_block_header_by_hash(parent_hash)?.ok_or(anyhow!("failed to find the block header in the block storage when checking the dag block exists, block hash: {:?}, number: {:?}", header.id(), header.number()))?;
let results = header.parents_hash().ok_or_else(|| anyhow!("dag block has no parents."))?.into_iter().map(|parent_hash| {
let header = self.storage.get_block_header_by_hash(parent_hash)?.ok_or_else(|| anyhow!("failed to find the block header in the block storage when checking the dag block exists, block hash: {:?}, number: {:?}", header.id(), header.number()))?;
Ok(self.get_block_dag_genesis(&header)?)
}).collect::<Result<HashSet<_>>>()?;

if results.len() == 1 {
Ok(results.into_iter().next().expect("the len of the results is larger than 1 but no the first elemen!").clone())
Ok(results
.into_iter()
.next()
.expect("the len of the results is larger than 1 but no the first elemen!"))
} else {
bail!("dag block: {:?}, number: {:?} has multiple parents whose dags are not the same one! Their dag genesis are: {:?}", header.id(), header.number(), results);
}
Expand Down Expand Up @@ -798,15 +801,18 @@ impl BlockChain {
}

pub fn get_block_dag_genesis(&self, header: &BlockHeader) -> Result<HashValue> {
let block_info = self.storage.get_block_info(header.id())?.ok_or(anyhow!("Cannot find block info by hash {:?}", header.id()))?;
let block_info = self
.storage
.get_block_info(header.id())?
.ok_or_else(|| anyhow!("Cannot find block info by hash {:?}", header.id()))?;
let block_accumulator = MerkleAccumulator::new_with_info(
block_info.get_block_accumulator_info().clone(),
self.storage
.get_accumulator_store(AccumulatorStoreType::Block),
);
let dag_genesis = block_accumulator
.get_leaf(header.dag_fork_height())?
.ok_or(anyhow!("failed to get the dag genesis"))?;
.ok_or_else(|| anyhow!("failed to get the dag genesis"))?;

Ok(dag_genesis)
}
Expand Down Expand Up @@ -1176,18 +1182,19 @@ impl ChainReader for BlockChain {
}))
}

fn current_tips_hash(&self, header: &BlockHeader) -> Result<Option<(HashValue, Vec<HashValue>)>> {
fn current_tips_hash(
&self,
header: &BlockHeader,
) -> Result<Option<(HashValue, Vec<HashValue>)>> {
let (dag_genesis, dag_state) = self.get_dag_state_by_block(header)?;
Ok(Some((dag_genesis, dag_state.tips)))
Ok(Some((dag_genesis, dag_state.tips)))
}

fn has_dag_block(&self, header_id: HashValue) -> Result<bool> {
let header = match self
.storage
.get_block_header_by_hash(header_id)? {
Some(header) => header,
None => return Ok(false),
};
let header = match self.storage.get_block_header_by_hash(header_id)? {
Some(header) => header,
None => return Ok(false),
};

let block_info = match self.storage.get_block_info(header.id())? {
Some(block_info) => block_info,
Expand All @@ -1198,22 +1205,22 @@ impl ChainReader for BlockChain {
self.storage
.get_accumulator_store(AccumulatorStoreType::Block),
);
let dag_genesis = match block_accumulator
.get_leaf(header.dag_fork_height())? {
Some(dag_genesis) => dag_genesis,
None => return Ok(false),
};
let dag_genesis = match block_accumulator.get_leaf(header.dag_fork_height())? {
Some(dag_genesis) => dag_genesis,
None => return Ok(false),
};

let current_chain_block_accumulator = MerkleAccumulator::new_with_info(
self.status.status.info.get_block_accumulator_info().clone(),
self.storage
.get_accumulator_store(AccumulatorStoreType::Block),
);
let current_chain_dag_genesis = match current_chain_block_accumulator
.get_leaf(self.status.status.head.dag_fork_height())? {
Some(dag_genesis) => dag_genesis,
None => return Ok(false),
};
.get_leaf(self.status.status.head.dag_fork_height())?
{
Some(dag_genesis) => dag_genesis,
None => return Ok(false),
};

if current_chain_dag_genesis != dag_genesis {
return Ok(false);
Expand Down
3 changes: 1 addition & 2 deletions chain/tests/test_block_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,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())?;
Expand All @@ -538,4 +537,4 @@ fn test_block_chain_for_dag_fork() -> Result<()> {
}

Ok(())
}
}
30 changes: 30 additions & 0 deletions cmd/starcoin/src/chain/get_dag_state_cmd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) The Starcoin Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::cli_state::CliState;
use crate::StarcoinOpt;
use anyhow::Result;
use clap::Parser;
use scmd::{CommandAction, ExecContext};
use starcoin_dag::consensusdb::consenses_state::DagStateView;

/// Get block info by number
#[derive(Debug, Parser)]
#[clap(name = "get-dag-state", alias = "get_dag_state")]
pub struct GetDagStateOpt {}

pub struct GetTipsStateCommand;

impl CommandAction for GetTipsStateCommand {
type State = CliState;
type GlobalOpt = StarcoinOpt;
type Opt = GetDagStateOpt;
type ReturnItem = DagStateView;

fn run(
&self,
ctx: &ExecContext<Self::State, Self::GlobalOpt, Self::Opt>,
) -> Result<Self::ReturnItem> {
ctx.state().client().get_dag_state()
}
}
2 changes: 1 addition & 1 deletion cmd/starcoin/src/chain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
mod epoch_info;
mod get_block_cmd;
mod get_block_info_cmd;
mod get_dag_state_cmd;
mod get_events_cmd;
mod get_txn_cmd;
mod get_txn_info_cmd;
Expand All @@ -12,7 +13,6 @@ mod get_txn_infos_cmd;
pub mod get_txn_proof_cmd;
mod info_cmd;
mod list_block_cmd;
mod get_dag_state_cmd;

pub use epoch_info::*;
pub use get_block_cmd::*;
Expand Down
77 changes: 52 additions & 25 deletions flexidag/dag/src/blockdag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,9 @@ impl BlockDAG {
}

pub fn check_ancestor_of(&self, ancestor: Hash, descendant: Vec<Hash>) -> anyhow::Result<bool> {
self.ghostdag_manager.check_ancestor_of(ancestor, descendant)
}
self.ghostdag_manager
.check_ancestor_of(ancestor, descendant)
}

pub fn init_with_genesis(&mut self, genesis: BlockHeader) -> anyhow::Result<()> {
let genesis_id = genesis.id();
Expand All @@ -99,9 +100,12 @@ impl BlockDAG {
// .relations_store
// .insert(origin, BlockHashes::new(vec![]))?;
self.commit(genesis, origin)?;
self.save_dag_state(genesis_id, DagState {
tips: vec![genesis_id],
})?;
self.save_dag_state(
genesis_id,
DagState {
tips: vec![genesis_id],
},
)?;
Ok(())
}
pub fn ghostdata(&self, parents: &[HashValue]) -> anyhow::Result<GhostdagData> {
Expand Down Expand Up @@ -136,9 +140,11 @@ impl BlockDAG {
Some(ghostdata) => ghostdata,
};
// Store ghostdata
process_key_already_error(self.storage
.ghost_dag_store
.insert(header.id(), ghostdata.clone()))?;
process_key_already_error(
self.storage
.ghost_dag_store
.insert(header.id(), ghostdata.clone()),
)?;

// Update reachability store
let mut reachability_store = self.storage.reachability_store.clone();
Expand All @@ -153,19 +159,35 @@ impl BlockDAG {
) {
Result::Ok(_) => (),
Err(reachability::ReachabilityError::DataInconsistency) => {
let _future_covering_set = reachability_store.get_future_covering_set(header.id())?;
info!("the key {:?} was already processed, original error message: {:?}", header.id(), reachability::ReachabilityError::DataInconsistency);
let _future_covering_set =
reachability_store.get_future_covering_set(header.id())?;
info!(
"the key {:?} was already processed, original error message: {:?}",
header.id(),
reachability::ReachabilityError::DataInconsistency
);
}
Err(reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(msg))) => {
if msg == REINDEX_ROOT_KEY.to_string() {
info!("the key {:?} was already processed, original error message: {:?}", header.id(), reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(REINDEX_ROOT_KEY.to_string())));
if msg == *REINDEX_ROOT_KEY.to_string() {
info!(
"the key {:?} was already processed, original error message: {:?}",
header.id(),
reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(
REINDEX_ROOT_KEY.to_string()
))
);
info!("now set the reindex key to origin: {:?}", origin);
// self.storage.reachability_store.set_reindex_root(origin)?;
self.set_reindex_root(origin)?;
bail!("failed to add a block when committing, e: {:?}", reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(msg)));

bail!(
"failed to add a block when committing, e: {:?}",
reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(msg))
);
} else {
bail!("failed to add a block when committing, e: {:?}", reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(msg)));
bail!(
"failed to add a block when committing, e: {:?}",
reachability::ReachabilityError::StoreError(StoreError::KeyNotFound(msg))
);
}
}
Err(e) => {
Expand All @@ -177,18 +199,24 @@ impl BlockDAG {
if header.is_dag_genesis() {
let origin = header.parent_hash();
let real_origin = Hash::sha3_256_of(&[origin, header.id()].encode()?);
process_key_already_error(self.storage
.relations_store
.insert(header.id(), BlockHashes::new(vec![real_origin])))?;
process_key_already_error(
self.storage
.relations_store
.insert(header.id(), BlockHashes::new(vec![real_origin])),
)?;
} else {
process_key_already_error(self.storage
.relations_store
.insert(header.id(), BlockHashes::new(parents)))?;
process_key_already_error(
self.storage
.relations_store
.insert(header.id(), BlockHashes::new(parents)),
)?;
}
// Store header store
process_key_already_error(self.storage
.header_store
.insert(header.id(), Arc::new(header), 0))?;
process_key_already_error(self.storage.header_store.insert(
header.id(),
Arc::new(header),
0,
))?;
Ok(())
}

Expand Down Expand Up @@ -219,4 +247,3 @@ impl BlockDAG {
Ok(())
}
}

Loading

0 comments on commit f57968b

Please sign in to comment.