Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
123 changes: 91 additions & 32 deletions crates/revive-strategy/src/cheatcodes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use alloy_sol_types::SolValue;
use foundry_cheatcodes::{
Broadcast, BroadcastableTransactions, CheatcodeInspectorStrategy,
CheatcodeInspectorStrategyContext, CheatcodeInspectorStrategyRunner, CheatsConfig, CheatsCtxt,
CommonCreateInput, Ecx, EvmCheatcodeInspectorStrategyRunner, Result,
CommonCreateInput, DynCheatcode, Ecx, EvmCheatcodeInspectorStrategyRunner, Result,
Vm::{
AccountAccessKind, chainIdCall, coinbaseCall, dealCall, etchCall, getNonce_0Call, loadCall,
polkadot_0Call, polkadot_1Call, polkadotSkipCall, resetNonceCall,
Expand Down Expand Up @@ -318,8 +318,9 @@ impl CheatcodeInspectorStrategyRunner for PvmCheatcodeInspectorStrategyRunner {
tracing::info!(cheatcode = ?cheatcode.as_debug() , using_revive = ?using_revive);
let dealCall { account, newBalance } = cheatcode.as_any().downcast_ref().unwrap();

ctx.externalities.set_balance(*account, *newBalance);
cheatcode.dyn_apply(ccx, executor)
let clamped_balance = ctx.externalities.set_balance(*account, *newBalance);
let clamped_deal = dealCall { account: *account, newBalance: clamped_balance };
clamped_deal.dyn_apply(ccx, executor)
}
t if using_revive && is::<setNonceCall>(t) => {
tracing::info!(cheatcode = ?cheatcode.as_debug() , using_revive = ?using_revive);
Expand Down Expand Up @@ -354,29 +355,13 @@ impl CheatcodeInspectorStrategyRunner for PvmCheatcodeInspectorStrategyRunner {
}
t if using_revive && is::<rollCall>(t) => {
let &rollCall { newHeight } = cheatcode.as_any().downcast_ref().unwrap();
let new_block_number: u64 = newHeight.try_into().expect("Block number exceeds u32");

// blockhash should be the same on both revive and revm sides, so fetch it before
// changing the block number.
let prev_new_height_hash = ccx
.ecx
.journaled_state
.database
.block_hash(new_block_number - 1)
.expect("Should not fail");
let new_height_hash = ccx
.ecx
.journaled_state
.database
.block_hash(new_block_number)
.expect("Should not fail");
ctx.externalities.set_block_number(
let clamped_height = ctx.externalities.roll(
newHeight,
prev_new_height_hash,
new_height_hash,
&mut *ccx.ecx.journaled_state.database,
);

cheatcode.dyn_apply(ccx, executor)
rollCall { newHeight: clamped_height }.dyn_apply(ccx, executor)
}
t if using_revive && is::<snapshotStateCall>(t) => {
ctx.externalities.start_snapshotting();
Expand All @@ -398,10 +383,9 @@ impl CheatcodeInspectorStrategyRunner for PvmCheatcodeInspectorStrategyRunner {
t if using_revive && is::<warpCall>(t) => {
let &warpCall { newTimestamp } = cheatcode.as_any().downcast_ref().unwrap();

tracing::info!(cheatcode = ?cheatcode.as_debug() , using_revive = ?using_revive);
ctx.externalities.set_timestamp(newTimestamp);
let clamped_timestamp = ctx.externalities.set_timestamp(newTimestamp);

cheatcode.dyn_apply(ccx, executor)
warpCall { newTimestamp: clamped_timestamp }.dyn_apply(ccx, executor)
}

t if using_revive && is::<chainIdCall>(t) => {
Expand All @@ -425,19 +409,29 @@ impl CheatcodeInspectorStrategyRunner for PvmCheatcodeInspectorStrategyRunner {
cheatcode.as_any().downcast_ref().unwrap();

tracing::info!(cheatcode = ?cheatcode.as_debug(), using_revive = ?using_revive);
let u64_max: U256 = U256::from(u64::MAX);
let clamped_block_number = if blockNumber > u64_max {
tracing::warn!(
blockNumber = ?blockNumber,
max = ?u64_max,
"Block number exceeds u64::MAX. Clamping to u64::MAX."
);
u64_max
} else {
blockNumber
};

// Validate blockNumber is not in the future
let current_block = ctx.externalities.get_block_number();
if blockNumber > current_block {
if clamped_block_number > current_block {
return Err(foundry_cheatcodes::Error::from(
"block number must be less than or equal to the current block number",
));
}

let block_num_u64 = blockNumber.to::<u64>();
ctx.externalities.set_blockhash(block_num_u64, blockHash);
ctx.externalities.set_blockhash(clamped_block_number.to(), blockHash);

cheatcode.dyn_apply(ccx, executor)
setBlockhashCall { blockNumber: clamped_block_number, blockHash }.dyn_apply(ccx, executor)
}
t if using_revive && is::<etchCall>(t) => {
let etchCall { target, newRuntimeBytecode } =
Expand Down Expand Up @@ -669,15 +663,15 @@ fn select_revive(

let block_number = data.block.number;
let timestamp = data.block.timestamp;
ctx.externalities.set_timestamp(timestamp);
ctx.externalities.roll(block_number, &mut *data.journaled_state.database);

ctx.externalities.execute_with(||{
// Enable debug mode to bypass EIP-170 size checks during testing
if data.cfg.limit_contract_code_size == Some(usize::MAX) {
let debug_settings = DebugSettings::new(true, true, true);
debug_settings.write_to_storage::<Runtime>();
}
System::set_block_number(block_number.saturating_to());
Timestamp::set_timestamp(timestamp.saturating_to::<u64>() * 1000);
<revive_env::Runtime as polkadot_sdk::pallet_revive::Config>::ChainId::set(
&data.cfg.chain_id,
);
Expand All @@ -702,7 +696,22 @@ fn select_revive(
let account = H160::from_slice(address.as_slice());
let account_id =
AccountId32Mapper::<Runtime>::to_fallback_account_id(&account);
let amount_pvm = sp_core::U256::from_little_endian(&amount.as_le_bytes()).min(u128::MAX.into());

let u128_max: U256 = U256::from(u128::MAX);
let clamped_amount = if amount > u128_max {
tracing::info!(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here it's info and in state it's warn. Shouldn't this be consistent?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue was that it flooded the terminal. The migration runs during each test for 15 accounts which are funded with u256::max, so I decided to decrease the log level.

address = ?address,
requested = ?amount,
actual = ?u128_max,
"Migration: balance exceeds u128::MAX, clamping to u128::MAX. \
pallet-revive uses u128 for balances."
);
u128_max
} else {
amount
};

let amount_pvm = sp_core::U256::from_little_endian(&clamped_amount.as_le_bytes());
Pallet::<Runtime>::set_evm_balance(&account, amount_pvm)
.expect("failed to set evm balance");

Expand Down Expand Up @@ -997,6 +1006,30 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
}
};

let u128_max: U256 = U256::from(u128::MAX);
if input.value() > u128_max {
tracing::warn!(
caller = ?input.caller(),
value = ?input.value(),
max = ?u128_max,
"Create value exceeds u128::MAX. pallet-revive uses u128 for balances."
);
return Some(CreateOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: Bytes::from_iter(
format!(
"Create value {} exceeds u128::MAX ({}). pallet-revive uses u128 for balances.",
input.value(),
u128::MAX
).as_bytes(),
),
gas: Gas::new(input.gas_limit()),
},
address: None,
});
}

let gas_price_pvm =
sp_core::U256::from_little_endian(&U256::from(ecx.tx.gas_price).as_le_bytes());
let mut tracer = Tracer::new(state.expected_calls.clone(), state.expected_creates.clone());
Expand Down Expand Up @@ -1167,6 +1200,32 @@ impl foundry_cheatcodes::CheatcodeInspectorStrategyExt for PvmCheatcodeInspector
}

tracing::info!("running call on pallet-revive with {} {:#?}", ctx.runtime_mode, call);

let u128_max: U256 = U256::from(u128::MAX);
let call_value = call.call_value();
if call_value > u128_max {
tracing::warn!(
caller = ?call.caller,
target = ?call.target_address,
value = ?call_value,
max = ?u128_max,
"Call value exceeds u128::MAX. pallet-revive uses u128 for balances."
);
return Some(CallOutcome {
result: InterpreterResult {
result: InstructionResult::Revert,
output: Bytes::from_iter(
format!(
"Call value {} exceeds u128::MAX ({}). pallet-revive uses u128 for balances.",
call_value,
u128::MAX
).as_bytes(),
),
gas: Gas::new(call.gas_limit),
},
memory_offset: call.return_memory_offset.clone(),
});
}

let gas_price_pvm =
sp_core::U256::from_little_endian(&U256::from(ecx.tx.gas_price).as_le_bytes());
Expand Down
92 changes: 77 additions & 15 deletions crates/revive-strategy/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,38 +112,83 @@ impl TestEnv {
new_height: U256,
prev_new_height_hash: B256,
new_height_hash: B256,
) {
) -> U256 {
// Set block number in pallet-revive runtime.
self.0.lock().unwrap().externalities.execute_with(|| {
let new_block_number: u64 = new_height.try_into().expect("Block number exceeds u64");
let u64_max = U256::from(u64::MAX);
let clamped_height = if new_height > u64_max {
tracing::warn!(
block_number = ?new_height,
max = ?u64_max,
"Block number exceeds u64::MAX. Clamping to u64::MAX."
);
u64_max
} else {
new_height
};

let new_block_number: u64 = clamped_height.to();
let digest = System::digest();
if System::block_hash(new_block_number) == H256::zero() {
// First initialize and finalize the parent block to set up correct hashes.
System::set_block_number(new_block_number - 1);
let current_hash = H256::from_slice(prev_new_height_hash.0.as_slice());
System::initialize(&new_block_number, &current_hash, &digest);
if new_block_number > 0 {
System::set_block_number(new_block_number - 1);
let current_hash = H256::from_slice(prev_new_height_hash.0.as_slice());
System::initialize(&new_block_number, &current_hash, &digest);
}

// Now finalize the new block to set up its hash.
System::set_block_number(new_block_number);
let current_hash = H256::from_slice(new_height_hash.0.as_slice());

System::initialize(&(new_block_number + 1), &current_hash, &digest);
if new_block_number < u64::MAX {
System::set_block_number(new_block_number);
let current_hash = H256::from_slice(new_height_hash.0.as_slice());
System::initialize(&(new_block_number + 1), &current_hash, &digest);
}
}
System::set_block_number(new_block_number);
});
clamped_height
})
}

pub fn get_block_number(&mut self) -> U256 {
// Get block number in pallet-revive runtime.
self.0.lock().unwrap().externalities.execute_with(|| U256::from(System::block_number()))
}

pub fn set_timestamp(&mut self, new_timestamp: U256) {
pub fn roll<DB: revm::Database + ?Sized>(
&mut self,
new_height: U256,
database: &mut DB,
) -> U256 {
let block_num_u64 = new_height.saturating_to::<u64>();
let prev_block_hash = database
.block_hash(block_num_u64.saturating_sub(1))
.unwrap_or_default();
let current_block_hash = database
.block_hash(block_num_u64)
.unwrap_or_default();

self.set_block_number(new_height, prev_block_hash, current_block_hash)
}

pub fn set_timestamp(&mut self, new_timestamp: U256) -> U256 {
// Set timestamp in pallet-revive runtime (milliseconds).
self.0.lock().unwrap().externalities.execute_with(|| {
let timestamp_ms = new_timestamp.saturating_to::<u64>().saturating_mul(1000);
let u64_max = U256::from(u64::MAX);
let clamped_timestamp = if new_timestamp > u64_max {
tracing::warn!(
timestamp = ?new_timestamp,
max = ?u64_max,
"Timestamp exceeds u64::MAX. Clamping to u64::MAX."
);
u64_max
} else {
new_timestamp
};

let timestamp_ms = clamped_timestamp.saturating_to::<u64>().saturating_mul(1000);
Timestamp::set_timestamp(timestamp_ms);
});
clamped_timestamp
})
}

pub fn etch_call(&mut self, target: &Address, new_runtime_code: &Bytes) -> Result {
Expand Down Expand Up @@ -235,16 +280,33 @@ impl TestEnv {
Ok(())
}

pub fn set_balance(&mut self, address: Address, amount: U256) {
pub fn set_balance(&mut self, address: Address, amount: U256) -> U256 {
let u128_max = U256::from(u128::MAX);
let clamped_amount = if amount > u128_max {
tracing::warn!(
address = ?address,
requested = ?amount,
actual = ?u128_max,
"Balance exceeds u128::MAX, clamping to u128::MAX. \
pallet-revive uses u128 for balances."
);
u128_max
} else {
amount
};

let amount_pvm =
sp_core::U256::from_little_endian(&amount.as_le_bytes()).min(u128::MAX.into());
sp_core::U256::from_little_endian(&clamped_amount.as_le_bytes());

self.0.lock().unwrap().externalities.execute_with(|| {
let h160_addr = H160::from_slice(address.as_slice());
pallet_revive::Pallet::<Runtime>::set_evm_balance(&h160_addr, amount_pvm)
.expect("failed to set evm balance");
});

clamped_amount
}

pub fn get_balance(&mut self, address: Address) -> U256 {
U256::from_limbs(
self.0
Expand Down
Loading