Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: try remove stack overflow #98

Merged
merged 5 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/server/grpc/p2pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,13 @@ where S: ShareChain
.await
.map_err(|error| Status::internal(format!("failed to get new tip block {error:?}")))?)
.clone();
dbg!(&new_tip_block.height, &new_tip_block.hash);
// dbg!(&new_tip_block.height, &new_tip_block.hash);
let shares = share_chain
.generate_shares(&new_tip_block)
.await
.map_err(|error| Status::internal(format!("failed to generate shares {error:?}")))?;

dbg!(&shares);
// dbg!(&shares);

let mut response = self
.client
Expand Down
12 changes: 8 additions & 4 deletions src/server/p2p/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,14 +641,14 @@ where S: ShareChain

// Don't add unless we've already synced.

info!(target: LOG_TARGET, squad = &self.config.squad; "🆕 New block from broadcast: {:?}", &payload.new_blocks.iter().map(|b| b.0.to_string()).join(","));
debug!(target: LOG_TARGET, squad = &self.config.squad; "🆕 New block from broadcast: {:?}", &payload.new_blocks.iter().map(|b| b.0.to_string()).join(","));
let algo = payload.algo();
let share_chain = match algo {
PowAlgorithm::RandomX => self.share_chain_random_x.clone(),
PowAlgorithm::Sha3x => self.share_chain_sha3x.clone(),
};
if share_chain.tip_height().await.unwrap_or_default() == 0 {
warn!(target: LOG_TARGET, squad = &self.config.squad; "Share chain tip height is None, skipping block until we have synced");
debug!(target: LOG_TARGET, squad = &self.config.squad; "Share chain tip height is None, skipping block until we have synced");
return;
}
let mut missing_blocks = vec![];
Expand Down Expand Up @@ -907,7 +907,7 @@ where S: ShareChain
}

if !self.network_peer_store.is_whitelisted(&peer) {
warn!(target: LOG_TARGET, squad = &self.config.squad; "Peer is not whitelisted, will still try to sync");
debug!(target: LOG_TARGET, squad = &self.config.squad; "Peer is not whitelisted, will still try to sync");
// return;
}

Expand Down Expand Up @@ -1420,8 +1420,12 @@ where S: ShareChain
.open(format!("{}_blocks_{}.txt", prefix, time))
.unwrap();

file.write(b"@startuml\n").unwrap();
// file.write(b"@startuml\n").unwrap();
file.write(b"digraph B {\n").unwrap();
if let Some(tip) = chain.get_tip().await.unwrap() {
file.write(&format!("comment=\"{} - {}\"\n", tip.0, &tip.1.to_hex()[0..8]).into_bytes())
.unwrap();
}
let blocks = chain.all_blocks().await.expect("errored");
for b in blocks {
file.write(
Expand Down
15 changes: 14 additions & 1 deletion src/sharechain/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ impl InMemoryShareChain {
}

Ok(Self {
p2_chain: Box::new(Arc::new(RwLock::new(P2Chain::new_empty(MAX_BLOCKS_COUNT, SHARE_WINDOW)))),
p2_chain: Box::new(Arc::new(RwLock::new(P2Chain::new_empty(
MAX_BLOCKS_COUNT,
SHARE_WINDOW,
)))),
pow_algo,
block_validation_params,
consensus_manager,
Expand Down Expand Up @@ -354,6 +357,16 @@ impl ShareChain for InMemoryShareChain {
Ok(tip_level)
}

async fn get_tip(&self) -> Result<Option<(u64, FixedHash)>, Error> {
let bl = self.p2_chain.read().await;
let tip_level = bl.get_tip();
if let Some(tip_level) = tip_level {
Ok(Some((tip_level.height, tip_level.chain_block)))
} else {
Ok(None)
}
}

async fn generate_shares(&self, new_tip_block: &P2Block) -> Result<Vec<NewBlockCoinbase>, Error> {
let mut chain_read_lock = self.p2_chain.read().await;
// first check if there is a cached hashmap of shares
Expand Down
3 changes: 3 additions & 0 deletions src/sharechain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ pub(crate) trait ShareChain: Send + Sync + 'static {
/// Returns the tip of height in chain (from original Tari block header)
async fn tip_height(&self) -> Result<u64, Error>;

/// Returns the tip of the chain.
async fn get_tip(&self) -> Result<Option<(u64, FixedHash)>, Error>;

/// Generate shares based on the previous blocks.
async fn generate_shares(&self, new_tip_block: &P2Block) -> Result<Vec<NewBlockCoinbase>, Error>;

Expand Down
61 changes: 47 additions & 14 deletions src/sharechain/p2chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::{
sync::Arc,
};

use log::info;
use log::{debug, info};
use tari_common_types::types::FixedHash;
use tari_core::proof_of_work::{lwma_diff::LinearWeightedMovingAverage, AccumulatedDifficulty, Difficulty};

Expand Down Expand Up @@ -171,6 +171,40 @@ impl P2Chain {
}

fn verify_chain(&mut self, new_block_height: u64, hash: FixedHash) -> Result<(), Error> {
let mut next_level = Some((new_block_height, hash));
let mut missing_parents = vec![];
while let Some((next_height, next_hash)) = next_level {
match self.verify_chain_inner(next_height, next_hash, 0) {
Ok((missing_parents2, do_next_level)) => {
if !missing_parents2.is_empty() {
missing_parents.extend_from_slice(&missing_parents2);
// return Err(Error::BlockParentDoesNotExist {
// missing_parents: missing_parents2,
// });
}
next_level = do_next_level;
// if let Some((height, hash)) = do_next_level {
// self.verify_chain_inner(vec![], height, hash, 0)?;
// }
},
Err(e) => return Err(e),
}
}
if !missing_parents.is_empty() {
return Err(Error::BlockParentDoesNotExist { missing_parents });
}

Ok(())
}

fn verify_chain_inner(
&mut self,
new_block_height: u64,
hash: FixedHash,
recursion_depth: usize,
) -> Result<(Vec<(u64, FixedHash)>, Option<(u64, FixedHash)>), Error> {
// dbg!("Verify chain", new_block_height);
// dbg!(recursion_depth);
// we should validate what we can if a block is invalid, we should delete it.
let mut missing_parents = Vec::new();
let block = self
Expand Down Expand Up @@ -211,7 +245,7 @@ impl P2Chain {
// the newly added block == 0
if self.get_tip().map(|tip| tip.height).unwrap_or(0) == 0 && new_block_height == 0 {
self.set_new_tip(new_block_height, hash)?;
return Ok(());
return Ok((missing_parents, None));
}

// if !missing_parents.is_empty() {
Expand Down Expand Up @@ -241,7 +275,7 @@ impl P2Chain {
info!(target: LOG_TARGET, "[{:?}] Block building on tip: {:?}", algo, new_block_height);
self.set_new_tip(new_block_height, hash)?;
} else {
info!(target: LOG_TARGET, "[{:?}] Block is not building on tip: {:?}", algo, new_block_height);
debug!(target: LOG_TARGET, "[{:?}] Block is not building on tip: {:?}", algo, new_block_height);
// lets check if we need to reorg here
let block = self
.get_block_at_height(new_block_height, &hash)
Expand Down Expand Up @@ -350,27 +384,26 @@ impl P2Chain {
}
}

let mut next_level_data = None;

// let see if we already have a block that builds on top of this
if let Some(next_level) = self.level_at_height(new_block_height + 1).cloned() {
if let Some(next_level) = self.level_at_height(new_block_height + 1) {
// we have a height here, lets check the blocks
for block in next_level.blocks.iter() {
if block.1.prev_hash == hash {
info!(target: LOG_TARGET, "[{:?}] Found block building on top of block: {:?}", algo, new_block_height);
// we have a parent here
match self.verify_chain(next_level.height, block.0.clone()) {
Err(Error::BlockParentDoesNotExist {
missing_parents: mut missing,
}) => missing_parents.append(&mut missing),
Err(e) => return Err(e),
Ok(_) => (),
}
next_level_data = Some((next_level.height, block.0.clone()));
}
}
}
if let Some(next_level) = next_level_data {
debug!(target: LOG_TARGET, "[{:?}] Found block building on top of block: {:?}", algo, new_block_height);
// we have a parent here
return Ok((missing_parents, Some(next_level)));
}
if !missing_parents.is_empty() {
return Err(Error::BlockParentDoesNotExist { missing_parents });
}
Ok(())
Ok((missing_parents, None))
}

fn add_block(&mut self, block: Arc<P2Block>) -> Result<(), Error> {
Expand Down
Loading