Skip to content

Commit

Permalink
Add evm_try_get_balance_at_state_root FFI method
Browse files Browse the repository at this point in the history
  • Loading branch information
Jouzo committed Aug 23, 2023
1 parent d9d1502 commit 9d3c798
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 4 deletions.
6 changes: 6 additions & 0 deletions lib/ain-evm/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,12 @@ impl EVMBackend {
.unwrap_or_default()
}

pub fn get_balance(&self, address: &H160) -> U256 {
self.get_account(address)
.map(|acc| acc.balance)
.unwrap_or_default()
}

pub fn get_contract_storage(&self, contract: H160, storage_index: &[u8]) -> Result<U256> {
let Some(account) = self.get_account(&contract) else {
return Ok(U256::zero());
Expand Down
12 changes: 12 additions & 0 deletions lib/ain-evm/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,11 +584,23 @@ impl EVMCoreService {
"[get_latest_block_backend] At block number : {:#x}, state_root : {:#x}",
block_number, state_root
);
self.get_backend(state_root)
}

pub fn get_backend(&self, state_root: H256) -> Result<EVMBackend> {
debug!("[get_backend] State_root : {:#x}", state_root);
EVMBackend::from_root(
state_root,
Arc::clone(&self.trie_store),
Arc::clone(&self.storage),
Vicinity::default(),
)
}

pub fn get_balance_at_state_root(&self, address: H160, state_root: H256) -> Result<U256> {
let balance = self.get_backend(state_root)?.get_balance(&address);

debug!("Account {:x?} balance {:x?}", address, balance);
Ok(balance)
}
}
3 changes: 2 additions & 1 deletion lib/ain-evm/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ impl EVMServices {
block.header.hash(),
block.header.number,
);
let new_state_root = format!("{:?}", block.header.state_root);
queue.block_data = Some(BlockData { block, receipts });

Ok(FinalizedBlockInfo {
Expand All @@ -378,7 +379,7 @@ impl EVMServices {
total_burnt_fees,
total_priority_fees,
block_number: current_block_number,
state_root: format!("{:?}", state_root),
state_root: new_state_root,
})
}

Expand Down
40 changes: 40 additions & 0 deletions lib/ain-rs-exports/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,46 @@ pub fn evm_try_get_balance(result: &mut ffi::CrossBoundaryResult, address: &str)
}
}

/// Retrieves the balance of an EVM account at state root.
///
/// # Arguments
///
/// * `address` - The EVM address of the account.
/// * `state_root` - The state root from which to restore temporary trie database.
///
/// # Errors
///
/// Returns an Error if the address is not a valid EVM address.
///
/// # Returns
///
/// Returns the balance of the account as a `u64` on success.
pub fn evm_try_get_balance_at_state_root(
result: &mut ffi::CrossBoundaryResult,
address: &str,
state_root: &str,
) -> u64 {
let Ok(address) = address.parse() else {
return cross_boundary_error_return(result, "Invalid address");
};
let Ok(state_root) = state_root.parse() else {
return cross_boundary_error_return(result, "Invalid state root");
};

match SERVICES
.evm
.core
.get_balance_at_state_root(address, state_root)
{
Err(e) => cross_boundary_error_return(result, e.to_string()),
Ok(balance) => {
let amount = WeiAmount(balance).to_satoshi().try_into();

try_cross_boundary_return(result, amount)
}
}
}

/// Retrieves the next valid nonce of an EVM account in a specific queue_id
///
/// # Arguments
Expand Down
6 changes: 6 additions & 0 deletions lib/ain-rs-exports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ pub mod ffi {
// If they are fallible, it's a TODO to changed and move later
// so errors are propogated up properly.
fn evm_try_get_balance(result: &mut CrossBoundaryResult, address: &str) -> u64;
fn evm_try_get_balance_at_state_root(
result: &mut CrossBoundaryResult,
address: &str,
state_root: &str,
) -> u64;

fn evm_unsafe_try_create_queue(result: &mut CrossBoundaryResult) -> u64;
fn evm_unsafe_try_remove_queue(result: &mut CrossBoundaryResult, queue_id: u64);
fn evm_try_disconnect_latest_block(result: &mut CrossBoundaryResult);
Expand Down
7 changes: 4 additions & 3 deletions src/masternodes/validation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2440,7 +2440,7 @@ void ProcessAccountingStateBeforeBlock(const CBlock &block, const CBlockIndex* p
}
}

static Res ProcessAccountingConsensusChecks(const CBlock &block, const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams, CEVMInitialState& evmInitialState, const CEvmBlockStatsLive& evmStats) {
static Res ProcessAccountingConsensusChecks(const CBlock &block, const CBlockIndex* pindex, CCustomCSView& cache, const CChainParams& chainparams, CEVMInitialState& evmInitialState, const CEvmBlockStatsLive& evmStats, const std::string &stateRoot) {
auto attributes = cache.GetAttributes();
assert(attributes);

Expand Down Expand Up @@ -2510,7 +2510,7 @@ static Res ProcessAccountingConsensusChecks(const CBlock &block, const CBlockInd
newBalance.AddBalances(delta.balances);
if (ExtractDestination(address, dest) && dest.index() == WitV16KeyEthHashType) {
const auto keyID = std::get<WitnessV16EthHash>(dest);
auto result = XResultValue(evm_try_get_balance(result, keyID.ToHexString()));
auto result = XResultValue(evm_try_get_balance_at_state_root(result, keyID.ToHexString(), stateRoot));
if (result)
if (auto balance = *result) {
if (newBalance.balances[DFIToken] != balance)
Expand Down Expand Up @@ -2622,7 +2622,8 @@ static Res ProcessEVMQueue(const CBlock &block, const CBlockIndex *pindex, CCust
}

// Process transferdomain events
res = ProcessAccountingConsensusChecks(block, pindex, cache, chainparams, evmInitialState, stats);
auto evmStateRoot = std::string(blockResult.state_root.data(), blockResult.state_root.length());
res = ProcessAccountingConsensusChecks(block, pindex, cache, chainparams, evmInitialState, stats, evmStateRoot);
if (!res) return res;

attributes->SetValue(CEvmBlockStatsLive::Key, stats);
Expand Down

0 comments on commit 9d3c798

Please sign in to comment.