Skip to content

Commit

Permalink
Merge branch 'feat-2.0' of github.com:casper-network/casper-node into…
Browse files Browse the repository at this point in the history
… rustSDK-feat-2.0
  • Loading branch information
gRoussac committed Jul 9, 2024
2 parents 5a9b891 + baccf60 commit 3c772c7
Show file tree
Hide file tree
Showing 21 changed files with 342 additions and 166 deletions.
8 changes: 8 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ lint-smart-contracts:

.PHONY: audit-rs
audit-rs:
$(CARGO) audit --ignore RUSTSEC-2024-0344
$(CARGO) audit --ignore RUSTSEC-2024-0332 --ignore RUSTSEC-2024-0344

.PHONY: audit-as
audit-as:
Expand Down
16 changes: 12 additions & 4 deletions binary_port/src/node_status.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use casper_types::{
bytesrepr::{self, FromBytes, ToBytes},
AvailableBlockRange, BlockHash, BlockSynchronizerStatus, Digest, NextUpgrade, Peers, PublicKey,
TimeDiff, Timestamp,
AvailableBlockRange, BlockHash, BlockSynchronizerStatus, Digest, NextUpgrade, Peers,
ProtocolVersion, PublicKey, TimeDiff, Timestamp,
};

#[cfg(test)]
Expand All @@ -15,6 +15,8 @@ use crate::{minimal_block_info::MinimalBlockInfo, type_wrappers::ReactorStateNam
/// Status information about the node.
#[derive(Debug, PartialEq, Serialize)]
pub struct NodeStatus {
/// The current protocol version.
pub protocol_version: ProtocolVersion,
/// The node ID and network address of each connected peer.
pub peers: Peers,
/// The compiled node version.
Expand Down Expand Up @@ -49,6 +51,7 @@ impl NodeStatus {
#[cfg(test)]
pub(crate) fn random(rng: &mut TestRng) -> Self {
Self {
protocol_version: ProtocolVersion::from_parts(rng.gen(), rng.gen(), rng.gen()),
peers: Peers::random(rng),
build_version: rng.random_string(5..10),
chainspec_name: rng.random_string(5..10),
Expand All @@ -71,7 +74,8 @@ impl NodeStatus {

impl FromBytes for NodeStatus {
fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
let (peers, remainder) = FromBytes::from_bytes(bytes)?;
let (protocol_version, remainder) = ProtocolVersion::from_bytes(bytes)?;
let (peers, remainder) = Peers::from_bytes(remainder)?;
let (build_version, remainder) = String::from_bytes(remainder)?;
let (chainspec_name, remainder) = String::from_bytes(remainder)?;
let (starting_state_root_hash, remainder) = Digest::from_bytes(remainder)?;
Expand All @@ -87,6 +91,7 @@ impl FromBytes for NodeStatus {
let (latest_switch_block_hash, remainder) = Option::<BlockHash>::from_bytes(remainder)?;
Ok((
NodeStatus {
protocol_version,
peers,
build_version,
chainspec_name,
Expand Down Expand Up @@ -116,6 +121,7 @@ impl ToBytes for NodeStatus {

fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
let NodeStatus {
protocol_version,
peers,
build_version,
chainspec_name,
Expand All @@ -131,6 +137,7 @@ impl ToBytes for NodeStatus {
block_sync,
latest_switch_block_hash,
} = self;
protocol_version.write_bytes(writer)?;
peers.write_bytes(writer)?;
build_version.write_bytes(writer)?;
chainspec_name.write_bytes(writer)?;
Expand All @@ -148,7 +155,8 @@ impl ToBytes for NodeStatus {
}

fn serialized_length(&self) -> usize {
self.peers.serialized_length()
self.protocol_version.serialized_length()
+ self.peers.serialized_length()
+ self.build_version.serialized_length()
+ self.chainspec_name.serialized_length()
+ self.starting_state_root_hash.serialized_length()
Expand Down
29 changes: 24 additions & 5 deletions binary_port/src/type_wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use datasize::DataSize;

use casper_types::{
bytesrepr::{self, Bytes, FromBytes, ToBytes},
system::auction::DelegationRate,
EraId, ExecutionInfo, Key, PublicKey, TimeDiff, Timestamp, Transaction, ValidatorChange, U512,
};
use serde::Serialize;
Expand Down Expand Up @@ -179,12 +180,17 @@ impl GetTrieFullResult {
pub struct RewardResponse {
amount: U512,
era_id: EraId,
delegation_rate: DelegationRate,
}

impl RewardResponse {
/// Constructs new reward response.
pub fn new(amount: U512, era_id: EraId) -> Self {
Self { amount, era_id }
pub fn new(amount: U512, era_id: EraId, delegation_rate: DelegationRate) -> Self {
Self {
amount,
era_id,
delegation_rate,
}
}

/// Returns the amount of the reward.
Expand All @@ -196,6 +202,11 @@ impl RewardResponse {
pub fn era_id(&self) -> EraId {
self.era_id
}

/// Returns the delegation rate of the validator.
pub fn delegation_rate(&self) -> DelegationRate {
self.delegation_rate
}
}

impl ToBytes for RewardResponse {
Expand All @@ -206,20 +217,27 @@ impl ToBytes for RewardResponse {
}

fn serialized_length(&self) -> usize {
self.amount.serialized_length() + self.era_id.serialized_length()
self.amount.serialized_length()
+ self.era_id.serialized_length()
+ self.delegation_rate.serialized_length()
}

fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
self.amount.write_bytes(writer)?;
self.era_id.write_bytes(writer)
self.era_id.write_bytes(writer)?;
self.delegation_rate.write_bytes(writer)
}
}

impl FromBytes for RewardResponse {
fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
let (amount, remainder) = FromBytes::from_bytes(bytes)?;
let (era_id, remainder) = FromBytes::from_bytes(remainder)?;
Ok((RewardResponse::new(amount, era_id), remainder))
let (delegation_rate, remainder) = FromBytes::from_bytes(remainder)?;
Ok((
RewardResponse::new(amount, era_id, delegation_rate),
remainder,
))
}
}

Expand Down Expand Up @@ -436,6 +454,7 @@ mod tests {
bytesrepr::test_serialization_roundtrip(&RewardResponse::new(
rng.gen(),
EraId::random(rng),
rng.gen(),
));
}

Expand Down
1 change: 1 addition & 0 deletions ci/nightly-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ run_test_and_count 'start_run_teardown "swap_validator_set.sh"'
run_test_and_count 'start_run_teardown "sync_upgrade_test.sh node=6 era=5 timeout=500"'
run_test_and_count 'start_run_teardown "validators_disconnect.sh"'
run_test_and_count 'start_run_teardown "event_stream.sh"'
run_test_and_count 'start_run_teardown "regression_4771.sh"'
# Without start_run_teardown - these ones perform their own assets setup, network start and teardown
run_test_and_count 'source "$SCENARIOS_DIR/upgrade_after_emergency_upgrade_test_pre_1.5.sh"'
run_test_and_count 'source "$SCENARIOS_DIR/regression_3976.sh"'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5536,9 +5536,10 @@ fn credits_are_considered_when_determining_validators() {

// Add a credit for node 1 artificially (assume it has proposed a block with a transaction and
// received credit).
let credit_amount = U512::from(2001);
let add_credit = HandleFeeMode::credit(
Box::new(ACCOUNT_1_PK.clone()),
U512::from(2001),
credit_amount,
INITIAL_ERA_ID,
);
builder.handle_fee(
Expand Down Expand Up @@ -5566,8 +5567,9 @@ fn credits_are_considered_when_determining_validators() {
Some(&U512::from(ACCOUNT_2_BOND))
);
assert!(!new_validator_weights.contains_key(&BID_ACCOUNT_1_PK));
let expected_amount = credit_amount.saturating_add(U512::from(ACCOUNT_1_BOND));
assert_eq!(
new_validator_weights.get(&ACCOUNT_1_PK),
Some(&U512::from(ACCOUNT_1_BOND))
Some(&expected_amount)
);
}
22 changes: 16 additions & 6 deletions node/src/components/binary_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,7 @@ where
};

let status = NodeStatus {
protocol_version,
peers: Peers::from(peers),
build_version: crate::VERSION_STRING.clone(),
chainspec_name: network_name.into(),
Expand Down Expand Up @@ -939,22 +940,31 @@ where
let Some(validator_rewards) = block_rewards.get(&validator) else {
return BinaryResponse::new_empty(protocol_version);
};
match auction::reward(

let seigniorage_recipient = snapshot
.get(&header.era_id())
.and_then(|era| era.get(&validator));
let reward = auction::reward(
&validator,
delegator.as_deref(),
header.era_id(),
validator_rewards,
&snapshot,
) {
Ok(Some(reward)) => {
let response = RewardResponse::new(reward, header.era_id());
);
match (reward, seigniorage_recipient) {
(Ok(Some(reward)), Some(seigniorage_recipient)) => {
let response = RewardResponse::new(
reward,
header.era_id(),
*seigniorage_recipient.delegation_rate(),
);
BinaryResponse::from_value(response, protocol_version)
}
Ok(None) => BinaryResponse::new_empty(protocol_version),
Err(error) => {
(Err(error), _) => {
warn!(%error, "failed when calculating rewards");
BinaryResponse::new_error(ErrorCode::InternalError, protocol_version)
}
_ => BinaryResponse::new_empty(protocol_version),
}
}
}
Expand Down
34 changes: 28 additions & 6 deletions node/src/components/contract_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ use tracing::{debug, error, info, trace};
use casper_execution_engine::engine_state::{EngineConfigBuilder, ExecutionEngineV1};
use casper_storage::{
data_access_layer::{
AddressableEntityRequest, BlockStore, DataAccessLayer, EntryPointsRequest,
ExecutionResultsChecksumRequest, FlushRequest, FlushResult, GenesisRequest, GenesisResult,
TrieRequest,
AddressableEntityRequest, AddressableEntityResult, BlockStore, DataAccessLayer,
EntryPointsRequest, ExecutionResultsChecksumRequest, FlushRequest, FlushResult,
GenesisRequest, GenesisResult, TrieRequest,
},
global_state::{
state::{lmdb::LmdbGlobalState, CommitProvider, StateProvider},
Expand All @@ -42,7 +42,8 @@ use casper_storage::{
tracking_copy::TrackingCopyError,
};
use casper_types::{
ActivationPoint, Chainspec, ChainspecRawBytes, ChainspecRegistry, EraId, PublicKey,
account::AccountHash, ActivationPoint, Chainspec, ChainspecRawBytes, ChainspecRegistry,
EntityAddr, EraId, Key, PublicKey,
};

use crate::{
Expand Down Expand Up @@ -386,16 +387,37 @@ impl ContractRuntime {
}
ContractRuntimeRequest::GetAddressableEntity {
state_root_hash,
key,
entity_addr,
responder,
} => {
trace!(?state_root_hash, "get addressable entity");
let metrics = Arc::clone(&self.metrics);
let data_access_layer = Arc::clone(&self.data_access_layer);
async move {
let start = Instant::now();
let request = AddressableEntityRequest::new(state_root_hash, key);
let entity_key = match entity_addr {
EntityAddr::SmartContract(_) | EntityAddr::System(_) => Key::AddressableEntity(entity_addr),
EntityAddr::Account(account) => Key::Account(AccountHash::new(account)),
};
let request = AddressableEntityRequest::new(state_root_hash, entity_key);
let result = data_access_layer.addressable_entity(request);
let result = match &result {
AddressableEntityResult::ValueNotFound(msg) => {
if entity_addr.is_contract() {
trace!(%msg, "can not read addressable entity by Key::AddressableEntity or Key::Account, will try by Key::Hash");
let entity_key = Key::Hash(entity_addr.value());
let request = AddressableEntityRequest::new(state_root_hash, entity_key);
data_access_layer.addressable_entity(request)
}
else {
result
}
},
AddressableEntityResult::RootNotFound |
AddressableEntityResult::Success { .. } |
AddressableEntityResult::Failure(_) => result,
};

metrics
.addressable_entity
.observe(start.elapsed().as_secs_f64());
Expand Down
Loading

0 comments on commit 3c772c7

Please sign in to comment.