Skip to content

Commit

Permalink
Use optimistic block to create block
Browse files Browse the repository at this point in the history
  • Loading branch information
VanBarbascu committed Jan 20, 2025
1 parent a9d51fd commit 66b73c5
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 11 deletions.
1 change: 1 addition & 0 deletions chain/chain/src/tests/simple_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ fn build_chain_with_orphans() {
CryptoHash::default(),
clock,
None,
None,
);
assert_matches!(chain.process_block_test(&None, block).unwrap_err(), Error::Orphan);
assert_matches!(
Expand Down
11 changes: 9 additions & 2 deletions chain/client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,10 @@ impl Client {
&mut self,
optimistic_block: &OptimisticBlock,
) -> Result<(), Error> {
if let Some((height, block)) = self.optimistic_blocks_cache.push(optimistic_block.inner.block_height, optimistic_block.clone()) {
if let Some((height, block)) = self
.optimistic_blocks_cache
.push(optimistic_block.inner.block_height, optimistic_block.clone())
{
if height == optimistic_block.inner.block_height {
warn!(target: "client",
height=height,
Expand Down Expand Up @@ -730,7 +733,10 @@ impl Client {
let validator_signer = self.validator_signer.get().ok_or_else(|| {
Error::BlockProducer("Called without block producer info.".to_string())
})?;

let optimistic_block = self.optimistic_blocks_cache.get(&height).filter(|ob| {
// Make sure that the optimistic block is produced on the same previous block.
ob.inner.prev_block_hash == prev_hash
});
// Check that we are were called at the block that we are producer for.
let epoch_id = self.epoch_manager.get_epoch_id_from_prev_block(&prev_hash).unwrap();

Expand Down Expand Up @@ -933,6 +939,7 @@ impl Client {
block_merkle_root,
self.clock.clone(),
sandbox_delta_time,
optimistic_block,
);

// Update latest known even before returning block out, to prevent race conditions.
Expand Down
1 change: 1 addition & 0 deletions chain/client/src/sync/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,7 @@ mod test {
block_merkle_tree.root(),
clock.clock(),
None,
None,
);
block_merkle_tree.insert(*block.hash());
chain2.process_block_header(block.header(), &mut Vec::new()).unwrap(); // just to validate
Expand Down
1 change: 1 addition & 0 deletions chain/client/src/test_utils/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ pub fn create_chunk(
block_merkle_tree.root(),
client.clock.clone(),
None,
None,
);
(
ProduceChunkResult {
Expand Down
1 change: 1 addition & 0 deletions chain/client/src/tests/query_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ fn query_status_not_crash() {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);
let timestamp = next_block.header().timestamp();
next_block
Expand Down
1 change: 1 addition & 0 deletions chain/network/src/network_protocol/testonly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub fn make_block(
CryptoHash::default(),
clock,
None,
None,
)
}

Expand Down
1 change: 1 addition & 0 deletions core/primitives/benches/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ fn create_block() -> Block {
CryptoHash::default(),
Clock::real(),
None,
None,
)
}

Expand Down
36 changes: 27 additions & 9 deletions core/primitives/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::congestion_info::{BlockCongestionInfo, ExtendedCongestionInfo};
use crate::hash::CryptoHash;
use crate::merkle::{merklize, verify_path, MerklePath};
use crate::num_rational::Rational32;
use crate::optimistic_block::OptimisticBlock;
use crate::sharding::{ChunkHashHeight, ShardChunkHeader, ShardChunkHeaderV1};
use crate::types::{Balance, BlockHeight, EpochId, Gas};
use crate::version::{ProtocolVersion, SHARD_CHUNK_HEADER_UPGRADE_VERSION};
Expand Down Expand Up @@ -305,6 +306,7 @@ impl Block {
block_merkle_root: CryptoHash,
clock: near_time::Clock,
sandbox_delta_time: Option<near_time::Duration>,
optimistic_block: Option<OptimisticBlock>,
) -> Self {
use itertools::Itertools;
use near_primitives_core::version::ProtocolFeature;
Expand Down Expand Up @@ -340,15 +342,31 @@ impl Block {
);

let new_total_supply = prev.total_supply() + minted_amount.unwrap_or(0) - balance_burnt;
let now = clock.now_utc().unix_timestamp_nanos() as u64;
#[cfg(feature = "sandbox")]
let now = now + sandbox_delta_time.unwrap().whole_nanoseconds() as u64;
#[cfg(not(feature = "sandbox"))]
debug_assert!(sandbox_delta_time.is_none());
let time = if now <= prev.raw_timestamp() { prev.raw_timestamp() + 1 } else { now };

let (vrf_value, vrf_proof) = signer.compute_vrf_with_proof(prev.random_value().as_ref());
let random_value = hash(vrf_value.0.as_ref());

// Use the optimistic block data if available, otherwise compute it.
let (time, vrf_value, vrf_proof, random_value) = optimistic_block
.as_ref()
.map(|ob| {
(
ob.inner.block_timestamp,
ob.inner.vrf_value,
ob.inner.vrf_proof,
ob.inner.random_value,
)
})
.unwrap_or_else(|| {
let now = clock.now_utc().unix_timestamp_nanos() as u64;
#[cfg(feature = "sandbox")]
let now = now + sandbox_delta_time.unwrap().whole_nanoseconds() as u64;
#[cfg(not(feature = "sandbox"))]
debug_assert!(sandbox_delta_time.is_none());
let time = if now <= prev.raw_timestamp() { prev.raw_timestamp() + 1 } else { now };

let (vrf_value, vrf_proof) =
signer.compute_vrf_with_proof(prev.random_value().as_ref());
let random_value = hash(vrf_value.0.as_ref());
(time, vrf_value, vrf_proof, random_value)
});

let last_ds_final_block =
if height == prev.height() + 1 { prev.hash() } else { prev.last_ds_final_block() };
Expand Down
1 change: 1 addition & 0 deletions core/primitives/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,7 @@ impl TestBlockBuilder {
self.block_merkle_root,
self.clock,
None,
None,
)
}
}
Expand Down
2 changes: 2 additions & 0 deletions integration-tests/src/tests/client/challenges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ fn test_verify_block_double_sign_challenge() {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);
let epoch_id = *b1.header().epoch_id();
let valid_challenge = Challenge::produce(
Expand Down Expand Up @@ -445,6 +446,7 @@ fn test_verify_chunk_invalid_state_challenge() {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);

let challenge_body = client
Expand Down
3 changes: 3 additions & 0 deletions integration-tests/src/tests/client/process_blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ fn receive_network_block() {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);
actor_handles.client_actor.do_send(
BlockResponse { block, peer_id: PeerInfo::random().id, was_requested: false }
Expand Down Expand Up @@ -434,6 +435,7 @@ fn produce_block_with_approvals() {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);
actor_handles.client_actor.do_send(
BlockResponse {
Expand Down Expand Up @@ -631,6 +633,7 @@ fn invalid_blocks_common(is_requested: bool) {
block_merkle_tree.root(),
Clock::real(),
None,
None,
);
// Send block with invalid chunk mask
let mut block = valid_block.clone();
Expand Down

0 comments on commit 66b73c5

Please sign in to comment.