forge_verify/
bytecode.rs

1//! The `forge verify-bytecode` command.
2use crate::{
3    etherscan::EtherscanVerificationProvider,
4    utils::{
5        BytecodeType, JsonResult, check_and_encode_args, check_explorer_args, configure_env_block,
6        maybe_predeploy_contract,
7    },
8    verify::VerifierArgs,
9};
10use alloy_primitives::{Address, Bytes, TxKind, U256, hex};
11use alloy_provider::{
12    Provider,
13    ext::TraceApi,
14    network::{AnyTxEnvelope, TransactionBuilder},
15};
16use alloy_rpc_types::{
17    BlockId, BlockNumberOrTag, TransactionInput, TransactionRequest,
18    trace::parity::{Action, CreateAction, CreateOutput, TraceOutput},
19};
20use clap::{Parser, ValueHint};
21use eyre::{Context, OptionExt, Result};
22use foundry_cli::{
23    opts::EtherscanOpts,
24    utils::{self, LoadConfig, read_constructor_args_file},
25};
26use foundry_common::shell;
27use foundry_compilers::{artifacts::EvmVersion, info::ContractInfo};
28use foundry_config::{Config, figment, impl_figment_convert};
29use foundry_evm::{constants::DEFAULT_CREATE2_DEPLOYER, utils::configure_tx_req_env};
30use foundry_evm_core::AsEnvMut;
31use revm::state::AccountInfo;
32use std::path::PathBuf;
33
34impl_figment_convert!(VerifyBytecodeArgs);
35
36/// CLI arguments for `forge verify-bytecode`.
37#[derive(Clone, Debug, Parser)]
38pub struct VerifyBytecodeArgs {
39    /// The address of the contract to verify.
40    pub address: Address,
41
42    /// The contract identifier in the form `<path>:<contractname>`.
43    pub contract: ContractInfo,
44
45    /// The block at which the bytecode should be verified.
46    #[arg(long, value_name = "BLOCK")]
47    pub block: Option<BlockId>,
48
49    /// The constructor args to generate the creation code.
50    #[arg(
51        long,
52        num_args(1..),
53        conflicts_with_all = &["constructor_args_path", "encoded_constructor_args"],
54        value_name = "ARGS",
55    )]
56    pub constructor_args: Option<Vec<String>>,
57
58    /// The ABI-encoded constructor arguments.
59    #[arg(
60        long,
61        conflicts_with_all = &["constructor_args_path", "constructor_args"],
62        value_name = "HEX",
63    )]
64    pub encoded_constructor_args: Option<String>,
65
66    /// The path to a file containing the constructor arguments.
67    #[arg(
68        long,
69        value_hint = ValueHint::FilePath,
70        value_name = "PATH",
71        conflicts_with_all = &["constructor_args", "encoded_constructor_args"]
72    )]
73    pub constructor_args_path: Option<PathBuf>,
74
75    /// The rpc url to use for verification.
76    #[arg(short = 'r', long, value_name = "RPC_URL", env = "ETH_RPC_URL")]
77    pub rpc_url: Option<String>,
78
79    /// Etherscan options.
80    #[command(flatten)]
81    pub etherscan: EtherscanOpts,
82
83    /// Verifier options.
84    #[command(flatten)]
85    pub verifier: VerifierArgs,
86
87    /// The project's root path.
88    ///
89    /// By default root of the Git repository, if in one,
90    /// or the current working directory.
91    #[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
92    pub root: Option<PathBuf>,
93
94    /// Ignore verification for creation or runtime bytecode.
95    #[arg(long, value_name = "BYTECODE_TYPE")]
96    pub ignore: Option<BytecodeType>,
97}
98
99impl figment::Provider for VerifyBytecodeArgs {
100    fn metadata(&self) -> figment::Metadata {
101        figment::Metadata::named("Verify Bytecode Provider")
102    }
103
104    fn data(
105        &self,
106    ) -> Result<figment::value::Map<figment::Profile, figment::value::Dict>, figment::Error> {
107        let mut dict = self.etherscan.dict();
108
109        if let Some(api_key) = &self.verifier.verifier_api_key {
110            dict.insert("etherscan_api_key".into(), api_key.as_str().into());
111        }
112
113        if let Some(block) = &self.block {
114            dict.insert("block".into(), figment::value::Value::serialize(block)?);
115        }
116        if let Some(rpc_url) = &self.rpc_url {
117            dict.insert("eth_rpc_url".into(), rpc_url.to_string().into());
118        }
119
120        Ok(figment::value::Map::from([(Config::selected_profile(), dict)]))
121    }
122}
123
124impl VerifyBytecodeArgs {
125    /// Run the `verify-bytecode` command to verify the bytecode onchain against the locally built
126    /// bytecode.
127    pub async fn run(mut self) -> Result<()> {
128        // Setup
129        let config = self.load_config()?;
130        let provider = utils::get_provider(&config)?;
131
132        // If chain is not set, we try to get it from the RPC.
133        // If RPC is not set, the default chain is used.
134        let chain = match config.get_rpc_url() {
135            Some(_) => utils::get_chain(config.chain, &provider).await?,
136            None => config.chain.unwrap_or_default(),
137        };
138
139        // Set Etherscan options.
140        self.etherscan.chain = Some(chain);
141        self.etherscan.key = config.get_etherscan_config_with_chain(Some(chain))?.map(|c| c.key);
142
143        // Etherscan client
144        let etherscan =
145            EtherscanVerificationProvider.client(&self.etherscan, &self.verifier, &config)?;
146
147        // Get the bytecode at the address, bailing if it doesn't exist.
148        let code = provider.get_code_at(self.address).await?;
149        if code.is_empty() {
150            eyre::bail!("No bytecode found at address {}", self.address);
151        }
152
153        if !shell::is_json() {
154            sh_println!(
155                "Verifying bytecode for contract {} at address {}",
156                self.contract.name,
157                self.address
158            )?;
159        }
160
161        let mut json_results: Vec<JsonResult> = vec![];
162
163        // Get creation tx hash.
164        let creation_data = etherscan.contract_creation_data(self.address).await;
165
166        // Check if contract is a predeploy
167        let (creation_data, maybe_predeploy) = maybe_predeploy_contract(creation_data)?;
168
169        trace!(maybe_predeploy = ?maybe_predeploy);
170
171        // Get the constructor args using `source_code` endpoint.
172        let source_code = etherscan.contract_source_code(self.address).await?;
173
174        // Check if the contract name matches.
175        let name = source_code.items.first().map(|item| item.contract_name.to_owned());
176        if name.as_ref() != Some(&self.contract.name) {
177            eyre::bail!("Contract name mismatch");
178        }
179
180        // Obtain Etherscan compilation metadata.
181        let etherscan_metadata = source_code.items.first().unwrap();
182
183        // Obtain local artifact
184        let artifact = if let Ok(local_bytecode) =
185            crate::utils::build_using_cache(&self, etherscan_metadata, &config)
186        {
187            trace!("using cache");
188            local_bytecode
189        } else {
190            crate::utils::build_project(&self, &config)?
191        };
192
193        // Get local bytecode (creation code)
194        let local_bytecode = artifact
195            .bytecode
196            .as_ref()
197            .and_then(|b| b.to_owned().into_bytes())
198            .ok_or_eyre("Unlinked bytecode is not supported for verification")?;
199
200        // Get and encode user provided constructor args
201        let provided_constructor_args = if let Some(path) = self.constructor_args_path.to_owned() {
202            // Read from file
203            Some(read_constructor_args_file(path)?)
204        } else {
205            self.constructor_args.to_owned()
206        }
207        .map(|args| check_and_encode_args(&artifact, args))
208        .transpose()?
209        .or(self.encoded_constructor_args.to_owned().map(hex::decode).transpose()?);
210
211        let mut constructor_args = if let Some(provided) = provided_constructor_args {
212            provided.into()
213        } else {
214            // If no constructor args were provided, try to retrieve them from the explorer.
215            check_explorer_args(source_code.clone())?
216        };
217
218        // This fails only when the contract expects constructor args but NONE were provided OR
219        // retrieved from explorer (in case of predeploys).
220        crate::utils::check_args_len(&artifact, &constructor_args)?;
221
222        if maybe_predeploy {
223            if !shell::is_json() {
224                sh_warn!(
225                    "Attempting to verify predeployed contract at {:?}. Ignoring creation code verification.",
226                    self.address
227                )?;
228            }
229
230            // Append constructor args to the local_bytecode.
231            trace!(%constructor_args);
232            let mut local_bytecode_vec = local_bytecode.to_vec();
233            local_bytecode_vec.extend_from_slice(&constructor_args);
234
235            // Deploy at genesis
236            let gen_blk_num = 0_u64;
237            let (mut fork_config, evm_opts) = config.clone().load_config_and_evm_opts()?;
238            let (mut env, mut executor) = crate::utils::get_tracing_executor(
239                &mut fork_config,
240                gen_blk_num,
241                etherscan_metadata.evm_version()?.unwrap_or(EvmVersion::default()),
242                evm_opts,
243            )
244            .await?;
245
246            env.evm_env.block_env.number = U256::ZERO;
247            let genesis_block = provider.get_block(gen_blk_num.into()).full().await?;
248
249            // Setup genesis tx and env.
250            let deployer = Address::with_last_byte(0x1);
251            let mut gen_tx_req = TransactionRequest::default()
252                .with_from(deployer)
253                .with_input(Bytes::from(local_bytecode_vec))
254                .into_create();
255
256            if let Some(ref block) = genesis_block {
257                configure_env_block(&mut env.as_env_mut(), block);
258                gen_tx_req.max_fee_per_gas = block.header.base_fee_per_gas.map(|g| g as u128);
259                gen_tx_req.gas = Some(block.header.gas_limit);
260                gen_tx_req.gas_price = block.header.base_fee_per_gas.map(|g| g as u128);
261            }
262
263            configure_tx_req_env(&mut env.as_env_mut(), &gen_tx_req, None)
264                .wrap_err("Failed to configure tx request env")?;
265
266            // Seed deployer account with funds
267            let account_info = AccountInfo {
268                balance: U256::from(100 * 10_u128.pow(18)),
269                nonce: 0,
270                ..Default::default()
271            };
272            executor.backend_mut().insert_account_info(deployer, account_info);
273
274            let fork_address = crate::utils::deploy_contract(
275                &mut executor,
276                &env,
277                config.evm_spec_id(),
278                gen_tx_req.to,
279            )?;
280
281            // Compare runtime bytecode
282            let (deployed_bytecode, onchain_runtime_code) = crate::utils::get_runtime_codes(
283                &mut executor,
284                &provider,
285                self.address,
286                fork_address,
287                None,
288            )
289            .await?;
290
291            let match_type = crate::utils::match_bytecodes(
292                deployed_bytecode.original_byte_slice(),
293                &onchain_runtime_code,
294                &constructor_args,
295                true,
296                config.bytecode_hash,
297            );
298
299            crate::utils::print_result(
300                match_type,
301                BytecodeType::Runtime,
302                &mut json_results,
303                etherscan_metadata,
304                &config,
305            );
306
307            if shell::is_json() {
308                sh_println!("{}", serde_json::to_string(&json_results)?)?;
309            }
310
311            return Ok(());
312        }
313
314        // We can unwrap directly as maybe_predeploy is false
315        let creation_data = creation_data.unwrap();
316        // Get transaction and receipt.
317        trace!(creation_tx_hash = ?creation_data.transaction_hash);
318        let transaction = provider
319            .get_transaction_by_hash(creation_data.transaction_hash)
320            .await
321            .or_else(|e| eyre::bail!("Couldn't fetch transaction from RPC: {:?}", e))?
322            .ok_or_else(|| {
323                eyre::eyre!("Transaction not found for hash {}", creation_data.transaction_hash)
324            })?;
325        let receipt = provider
326            .get_transaction_receipt(creation_data.transaction_hash)
327            .await
328            .or_else(|e| eyre::bail!("Couldn't fetch transaction receipt from RPC: {:?}", e))?;
329        let receipt = if let Some(receipt) = receipt {
330            receipt
331        } else {
332            eyre::bail!(
333                "Receipt not found for transaction hash {}",
334                creation_data.transaction_hash
335            );
336        };
337
338        let mut transaction: TransactionRequest = match transaction.inner.inner.inner() {
339            AnyTxEnvelope::Ethereum(tx) => tx.clone().into(),
340            AnyTxEnvelope::Unknown(_) => unreachable!("Unknown transaction type"),
341        };
342
343        // Extract creation code from creation tx input.
344        let maybe_creation_code = if receipt.to.is_none()
345            && receipt.contract_address == Some(self.address)
346        {
347            match &transaction.input.input {
348                Some(input) => &input[..],
349                None => unreachable!("creation tx input is None"),
350            }
351        } else if receipt.to == Some(DEFAULT_CREATE2_DEPLOYER) {
352            match &transaction.input.input {
353                Some(input) => &input[32..],
354                None => unreachable!("creation tx input is None"),
355            }
356        } else {
357            // Try to get creation bytecode from tx trace.
358            let traces = provider
359                .trace_transaction(creation_data.transaction_hash)
360                .await
361                .unwrap_or_default();
362
363            let creation_bytecode =
364                traces.iter().find_map(|trace| match (&trace.trace.result, &trace.trace.action) {
365                    (
366                        Some(TraceOutput::Create(CreateOutput { address, .. })),
367                        Action::Create(CreateAction { init, .. }),
368                    ) if *address == self.address => Some(init.clone()),
369                    _ => None,
370                });
371
372            &creation_bytecode.ok_or_else(|| {
373                eyre::eyre!(
374                    "Could not extract the creation code for contract at address {}",
375                    self.address
376                )
377            })?
378        };
379
380        // In some cases, Etherscan will return incorrect constructor arguments. If this
381        // happens, try extracting arguments ourselves.
382        if !maybe_creation_code.ends_with(&constructor_args) {
383            trace!("mismatch of constructor args with etherscan");
384            // If local bytecode is longer than on-chain one, this is probably not a match.
385            if maybe_creation_code.len() >= local_bytecode.len() {
386                constructor_args =
387                    Bytes::copy_from_slice(&maybe_creation_code[local_bytecode.len()..]);
388                trace!(
389                    target: "forge::verify",
390                    "setting constructor args to latest {} bytes of bytecode",
391                    constructor_args.len()
392                );
393            }
394        }
395
396        // Append constructor args to the local_bytecode.
397        trace!(%constructor_args);
398        let mut local_bytecode_vec = local_bytecode.to_vec();
399        local_bytecode_vec.extend_from_slice(&constructor_args);
400
401        trace!(ignore = ?self.ignore);
402        // Check if `--ignore` is set to `creation`.
403        if !self.ignore.is_some_and(|b| b.is_creation()) {
404            // Compare creation code with locally built bytecode and `maybe_creation_code`.
405            let match_type = crate::utils::match_bytecodes(
406                local_bytecode_vec.as_slice(),
407                maybe_creation_code,
408                &constructor_args,
409                false,
410                config.bytecode_hash,
411            );
412
413            crate::utils::print_result(
414                match_type,
415                BytecodeType::Creation,
416                &mut json_results,
417                etherscan_metadata,
418                &config,
419            );
420
421            // If the creation code does not match, the runtime also won't match. Hence return.
422            if match_type.is_none() {
423                crate::utils::print_result(
424                    None,
425                    BytecodeType::Runtime,
426                    &mut json_results,
427                    etherscan_metadata,
428                    &config,
429                );
430                if shell::is_json() {
431                    sh_println!("{}", serde_json::to_string(&json_results)?)?;
432                }
433                return Ok(());
434            }
435        }
436
437        if !self.ignore.is_some_and(|b| b.is_runtime()) {
438            // Get contract creation block.
439            let simulation_block = match self.block {
440                Some(BlockId::Number(BlockNumberOrTag::Number(block))) => block,
441                Some(_) => eyre::bail!("Invalid block number"),
442                None => {
443                    let provider = utils::get_provider(&config)?;
444                    provider
445                    .get_transaction_by_hash(creation_data.transaction_hash)
446                    .await.or_else(|e| eyre::bail!("Couldn't fetch transaction from RPC: {:?}", e))?.ok_or_else(|| {
447                        eyre::eyre!("Transaction not found for hash {}", creation_data.transaction_hash)
448                    })?
449                    .block_number.ok_or_else(|| {
450                        eyre::eyre!("Failed to get block number of the contract creation tx, specify using the --block flag")
451                    })?
452                }
453            };
454
455            // Fork the chain at `simulation_block`.
456            let (mut fork_config, evm_opts) = config.clone().load_config_and_evm_opts()?;
457            let (mut env, mut executor) = crate::utils::get_tracing_executor(
458                &mut fork_config,
459                simulation_block - 1, // env.fork_block_number
460                etherscan_metadata.evm_version()?.unwrap_or(EvmVersion::default()),
461                evm_opts,
462            )
463            .await?;
464            env.evm_env.block_env.number = U256::from(simulation_block);
465            let block = provider.get_block(simulation_block.into()).full().await?;
466
467            // Workaround for the NonceTooHigh issue as we're not simulating prior txs of the same
468            // block.
469            let prev_block_id = BlockId::number(simulation_block - 1);
470
471            // Use `transaction.from` instead of `creation_data.contract_creator` to resolve
472            // blockscout creation data discrepancy in case of CREATE2.
473            let prev_block_nonce = provider
474                .get_transaction_count(transaction.from.unwrap())
475                .block_id(prev_block_id)
476                .await?;
477            transaction.set_nonce(prev_block_nonce);
478
479            if let Some(ref block) = block {
480                configure_env_block(&mut env.as_env_mut(), block)
481            }
482
483            // Replace the `input` with local creation code in the creation tx.
484            if let Some(TxKind::Call(to)) = transaction.kind() {
485                if to == DEFAULT_CREATE2_DEPLOYER {
486                    let mut input = transaction.input.input.unwrap()[..32].to_vec(); // Salt
487                    input.extend_from_slice(&local_bytecode_vec);
488                    transaction.input = TransactionInput::both(Bytes::from(input));
489
490                    // Deploy default CREATE2 deployer
491                    executor.deploy_create2_deployer()?;
492                }
493            } else {
494                transaction.input = TransactionInput::both(Bytes::from(local_bytecode_vec));
495            }
496
497            // configure_req__env(&mut env, &transaction.inner);
498            configure_tx_req_env(&mut env.as_env_mut(), &transaction, None)
499                .wrap_err("Failed to configure tx request env")?;
500
501            let fork_address = crate::utils::deploy_contract(
502                &mut executor,
503                &env,
504                config.evm_spec_id(),
505                transaction.to,
506            )?;
507
508            // State committed using deploy_with_env, now get the runtime bytecode from the db.
509            let (fork_runtime_code, onchain_runtime_code) = crate::utils::get_runtime_codes(
510                &mut executor,
511                &provider,
512                self.address,
513                fork_address,
514                Some(simulation_block),
515            )
516            .await?;
517
518            // Compare the onchain runtime bytecode with the runtime code from the fork.
519            let match_type = crate::utils::match_bytecodes(
520                fork_runtime_code.original_byte_slice(),
521                &onchain_runtime_code,
522                &constructor_args,
523                true,
524                config.bytecode_hash,
525            );
526
527            crate::utils::print_result(
528                match_type,
529                BytecodeType::Runtime,
530                &mut json_results,
531                etherscan_metadata,
532                &config,
533            );
534        }
535
536        if shell::is_json() {
537            sh_println!("{}", serde_json::to_string(&json_results)?)?;
538        }
539        Ok(())
540    }
541}