Skip to content

Commit

Permalink
clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptoAtwill committed Nov 21, 2024
1 parent e4a78a4 commit 9d228b4
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 220 deletions.
18 changes: 7 additions & 11 deletions fendermint/actors/activity-tracker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use fil_actors_runtime::builtin::singletons::SYSTEM_ACTOR_ADDR;
use fil_actors_runtime::runtime::{ActorCode, Runtime};
use fil_actors_runtime::{actor_dispatch, ActorError, EAM_ACTOR_ID};
use fil_actors_runtime::{actor_error, WithCodec, DEFAULT_HAMT_CONFIG};
use fvm_ipld_encoding::{IPLD_RAW};
use fvm_ipld_encoding::IPLD_RAW;
use fvm_shared::address::{Address, Payload};
use fvm_shared::METHOD_CONSTRUCTOR;
use ipc_actors_abis::checkpointing_facet::{FullActivityRollup};
use ipc_actors_abis::checkpointing_facet::FullActivityRollup;
use num_derive::FromPrimitive;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
Expand All @@ -20,7 +20,9 @@ mod state;
#[cfg(feature = "fil-actor")]
fil_actors_runtime::wasm_trampoline!(ActivityTrackerActor);

pub fn always_fail(_: &mut [u8]) -> Result<(), getrandom::Error> { unimplemented!() }
pub fn always_fail(_: &mut [u8]) -> Result<(), getrandom::Error> {
unimplemented!()
}

getrandom::register_custom_getrandom!(always_fail);

Expand Down Expand Up @@ -71,18 +73,12 @@ trait ActivityTracker {
/// Returns the activity rollup as a Solidity ABI-encoded type, in raw byte form.
fn commit_activity(
rt: &impl Runtime,
) -> Result<
WithCodec<AbiEncodedBytes<FullActivityRollup>, IPLD_RAW>,
ActorError,
>;
) -> Result<WithCodec<AbiEncodedBytes<FullActivityRollup>, IPLD_RAW>, ActorError>;

/// Queries the activity that has been accumulated since the last commit, and is pending a flush.
fn pending_activity(
rt: &impl Runtime,
) -> Result<
WithCodec<AbiEncodedBytes<FullActivityRollup>, IPLD_RAW>,
ActorError,
>;
) -> Result<WithCodec<AbiEncodedBytes<FullActivityRollup>, IPLD_RAW>, ActorError>;
}

impl ActivityTrackerActor {
Expand Down
46 changes: 10 additions & 36 deletions fendermint/vm/interpreter/src/fvm/activity/actor.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
// Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT

use crate::fvm::activity::{ActivityDetails, ValidatorActivityTracker};
use crate::fvm::activity::{FullActivity, ValidatorActivityTracker};
use crate::fvm::state::FvmExecState;
use crate::fvm::FvmMessage;
use anyhow::Context;
use fendermint_actor_activity_tracker::{GetActivitiesResult, ValidatorData};
use ethers::abi::AbiDecode;
use fendermint_crypto::PublicKey;
use fendermint_vm_actor_interface::activity::ACTIVITY_TRACKER_ACTOR_ADDR;
use fendermint_vm_actor_interface::eam::EthAddress;
use fendermint_vm_actor_interface::system;
use fvm::executor::ApplyRet;
use fvm_ipld_blockstore::Blockstore;
use fvm_shared::address::Address;
use fvm_shared::clock::ChainEpoch;
use fendermint_crypto::PublicKey;
use ipc_actors_abis::checkpointing_facet::FullActivityRollup;

pub struct ActorActivityTracker<'a, DB: Blockstore + Clone + 'static> {
pub(crate) executor: &'a mut FvmExecState<DB>,
pub(crate) epoch: ChainEpoch,
}

impl<'a, DB: Blockstore + Clone + 'static> ValidatorActivityTracker
for ActorActivityTracker<'a, DB>
{
type ValidatorSummaryDetail = ValidatorData;

fn record_block_committed(&mut self, validator: PublicKey) -> anyhow::Result<()> {
let address: Address = EthAddress::from(validator).into();

let msg = FvmMessage {
from: system::SYSTEM_ACTOR_ADDR,
to: ACTIVITY_TRACKER_ACTOR_ADDR,
sequence: 0, // irrelevant
sequence: 0, // irrelevant
gas_limit: i64::MAX as u64, // exclude this from gas restriction
method_num: fendermint_actor_activity_tracker::Method::RecordBlockCommitted as u64,
params: fvm_ipld_encoding::RawBytes::serialize(address)?,
Expand All @@ -45,13 +42,11 @@ impl<'a, DB: Blockstore + Clone + 'static> ValidatorActivityTracker
Ok(())
}

fn commit_activity(
&mut self,
) -> anyhow::Result<ActivityDetails<Self::ValidatorSummaryDetail>> {
fn commit_activity(&mut self) -> anyhow::Result<FullActivity> {
let msg = FvmMessage {
from: system::SYSTEM_ACTOR_ADDR,
to: ACTIVITY_TRACKER_ACTOR_ADDR,
sequence: 0, // irrelevant
sequence: 0, // irrelevant
gas_limit: i64::MAX as u64, // exclude this from gas restriction
method_num: fendermint_actor_activity_tracker::Method::CommitActivity as u64,
params: fvm_ipld_encoding::RawBytes::default(),
Expand All @@ -62,30 +57,9 @@ impl<'a, DB: Blockstore + Clone + 'static> ValidatorActivityTracker
};

let (apply_ret, _) = self.executor.execute_implicit(msg)?;
let r = fvm_ipld_encoding::from_slice::<GetActivitiesResult>(
&apply_ret.msg_receipt.return_data,
)
.context("failed to parse validator activities")?;
Ok(ActivityDetails::new(r.activities, r.cycle_start))
}

fn purge_activities(&mut self) -> anyhow::Result<()> {
let msg = FvmMessage {
from: system::SYSTEM_ACTOR_ADDR,
to: ACTIVITY_TRACKER_ACTOR_ADDR,
sequence: self.epoch as u64,
// exclude this from gas restriction
gas_limit: i64::MAX as u64,
method_num: fendermint_actor_activity_tracker::Method::PurgeActivities as u64,
params: fvm_ipld_encoding::RawBytes::default(),
value: Default::default(),
version: Default::default(),
gas_fee_cap: Default::default(),
gas_premium: Default::default(),
};

self.apply_implicit_message(msg)?;
Ok(())
let r = fvm_ipld_encoding::from_slice::<Vec<u8>>(&apply_ret.msg_receipt.return_data)
.context("failed to parse validator activities")?;
Ok(FullActivity::new(FullActivityRollup::decode(r)?))
}
}

Expand Down
17 changes: 6 additions & 11 deletions fendermint/vm/interpreter/src/fvm/activity/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// SPDX-License-Identifier: Apache-2.0, MIT

use anyhow::Context;
use ipc_api::checkpoint::consensus::ValidatorData;
use ipc_api::evm::payload_to_evm_address;
use ipc_actors_abis::checkpointing_facet::ValidatorData;
use ipc_observability::lazy_static;
use merkle_tree_rs::format::Raw;
use merkle_tree_rs::standard::StandardMerkleTree;
Expand All @@ -21,20 +20,16 @@ pub(crate) struct MerkleProofGen {
}

impl MerkleProofGen {
pub fn pack_validator(v: &ValidatorData) -> Vec<String> {
vec![format!("{:?}", v.validator), v.blocks_committed.to_string()]
}

pub fn root(&self) -> Hash {
self.tree.root()
}
}

impl MerkleProofGen {
pub fn new(values: &[ValidatorData]) -> anyhow::Result<Self> {
let values = values
.iter()
.map(|t| {
payload_to_evm_address(t.validator.payload())
.map(|addr| vec![format!("{addr:?}"), t.stats.blocks_committed.to_string()])
})
.collect::<anyhow::Result<Vec<_>>>()?;
let values = values.iter().map(Self::pack_validator).collect::<Vec<_>>();

let tree = StandardMerkleTree::of(&values, &VALIDATOR_SUMMARY_FIELDS)
.context("failed to construct Merkle tree")?;
Expand Down
139 changes: 61 additions & 78 deletions fendermint/vm/interpreter/src/fvm/activity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,76 +8,60 @@ pub mod actor;
mod merkle;

use crate::fvm::activity::merkle::MerkleProofGen;
use fendermint_actor_activity_tracker::ValidatorData;
use fendermint_crypto::PublicKey;
use fvm_shared::clock::ChainEpoch;
use std::fmt::Debug;
use ipc_actors_abis::checkpointing_facet::{
CompressedActivityRollup, CompressedSummary, FullActivityRollup,
};

#[derive(Debug, Clone)]
pub struct ActivityDetails<T> {
details: Vec<T>,
cycle_start: ChainEpoch,
}
/// Wrapper for FullActivityRollup with some utility functions
pub struct FullActivity(FullActivityRollup);

/// Tracks the validator activities in the current blockchain
pub trait ValidatorActivityTracker {
type ValidatorSummaryDetail: Clone + Debug;

/// Mark the validator has mined the target block.
fn record_block_committed(&mut self, validator: PublicKey) -> anyhow::Result<()>;

/// Get the validators activities summary since the checkpoint height
fn commit_activity(
&mut self,
) -> anyhow::Result<ActivityDetails<Self::ValidatorSummaryDetail>>;

/// Purge the current validator activities summary
fn purge_activities(&mut self) -> anyhow::Result<()>;
fn commit_activity(&mut self) -> anyhow::Result<FullActivity>;
}

impl ActivityDetails<ValidatorData> {
pub fn new(mut details: Vec<ValidatorData>, cycle_start: ChainEpoch) -> Self {
details.sort_by(|a, b| {
impl FullActivity {
pub fn new(mut full: FullActivityRollup) -> Self {
full.consensus.data.sort_by(|a, b| {
let cmp = a.validator.cmp(&b.validator);
if cmp.is_eq() {
// Address will be unique, do this just in case equal
a.stats.blocks_committed.cmp(&b.stats.blocks_committed)
a.blocks_committed.cmp(&b.blocks_committed)
} else {
cmp
}
});
Self {
details,
cycle_start,
}
}

pub fn commitment(&self) -> anyhow::Result<Vec<u8>> {
let gen = MerkleProofGen::new(self.details.as_slice())?;
Ok(gen.root().to_fixed_bytes().to_vec())
}
}

impl<T> ActivityDetails<T> {
pub fn elapsed(&self, height: ChainEpoch) -> ChainEpoch {
height.saturating_sub(self.cycle_start)
Self(full)
}

pub fn active_validators(&self) -> usize {
self.details.len()
pub fn compressed(&self) -> anyhow::Result<CompressedActivityRollup> {
let gen = MerkleProofGen::new(self.0.consensus.data.as_slice())?;
Ok(CompressedActivityRollup {
consensus: CompressedSummary {
stats: self.0.consensus.stats.clone(),
data_root_commitment: gen.root().to_fixed_bytes(),
},
})
}

pub fn details(&self) -> &[T] {
self.details.as_slice()
pub fn into_inner(self) -> FullActivityRollup {
self.0
}
}

#[cfg(test)]
mod tests {
use crate::fvm::activities::ActivityDetails;
use fendermint_actor_activity_tracker::{ValidatorData, ValidatorStats};
use crate::fvm::activity::ActivityDetails;
use fendermint_vm_actor_interface::eam::EthAddress;
use fvm_shared::address::Address;
use ipc_actors_abis::checkpointing_facet::{
AggregatedStats, FullActivityRollup, FullSummary, ValidatorData,
};
use rand::prelude::SliceRandom;
use rand::thread_rng;
use std::str::FromStr;
Expand All @@ -86,57 +70,56 @@ mod tests {
fn test_commitment() {
let mut v = vec![
ValidatorData {
validator: Address::from(EthAddress::from(
ethers::types::Address::from_str("0xB29C00299756135ec5d6A140CA54Ec77790a99d6")
.unwrap(),
)),
stats: ValidatorStats {
blocks_committed: 1,
},
validator: ethers::types::Address::from_str(
"0xB29C00299756135ec5d6A140CA54Ec77790a99d6",
)
.unwrap(),
blocks_committed: 1,
},
ValidatorData {
validator: Address::from(EthAddress::from(
ethers::types::Address::from_str("0x28345a43c2fBae4412f0AbadFa06Bd8BA3f58867")
.unwrap(),
)),
stats: ValidatorStats {
blocks_committed: 2,
},
validator: ethers::types::Address::from_str(
"0x28345a43c2fBae4412f0AbadFa06Bd8BA3f58867",
)
.unwrap(),
blocks_committed: 2,
},
ValidatorData {
validator: Address::from(EthAddress::from(
ethers::types::Address::from_str("0x1A79385eAd0e873FE0C441C034636D3Edf7014cC")
.unwrap(),
)),
stats: ValidatorStats {
blocks_committed: 10,
},
validator: ethers::types::Address::from_str(
"0x1A79385eAd0e873FE0C441C034636D3Edf7014cC",
)
.unwrap(),
blocks_committed: 10,
},
ValidatorData {
validator: Address::from(EthAddress::from(
ethers::types::Address::from_str("0x76B9d5a35C46B1fFEb37aadf929f1CA63a26A829")
.unwrap(),
)),
stats: ValidatorStats {
blocks_committed: 4,
},
validator: ethers::types::Address::from_str(
"0x76B9d5a35C46B1fFEb37aadf929f1CA63a26A829",
)
.unwrap(),
blocks_committed: 4,
},
ValidatorData {
validator: Address::from(EthAddress::from(
ethers::types::Address::from_str("0x3c5cc76b07cb02a372e647887bD6780513659527")
.unwrap(),
)),
stats: ValidatorStats {
blocks_committed: 3,
},
validator: ethers::types::Address::from_str(
"0x3c5cc76b07cb02a372e647887bD6780513659527",
)
.unwrap(),
blocks_committed: 3,
},
];

for _ in 0..10 {
v.shuffle(&mut thread_rng());
let details = ActivityDetails::new(v.clone(), 10);
let full = FullActivityRollup {
consensus: FullSummary {
stats: AggregatedStats {
total_active_validators: 1,
total_num_blocks_committed: 2,
},
data: v.clone(),
},
};
let details = ActivityDetails::new(full);
assert_eq!(
hex::encode(details.commitment().unwrap()),
hex::encode(details.compressed().unwrap().consensus.data_root_commitment),
"5519955f33109df3338490473cb14458640efdccd4df05998c4c439738280ab0"
);
}
Expand Down
Loading

0 comments on commit 9d228b4

Please sign in to comment.