Skip to main content

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(api_version) = &self.verifier.verifier_api_version {
114            dict.insert("etherscan_api_version".into(), api_version.to_string().into());
115        }
116
117        if let Some(block) = &self.block {
118            dict.insert("block".into(), figment::value::Value::serialize(block)?);
119        }
120        if let Some(rpc_url) = &self.rpc_url {
121            dict.insert("eth_rpc_url".into(), rpc_url.to_string().into());
122        }
123
124        Ok(figment::value::Map::from([(Config::selected_profile(), dict)]))
125    }
126}
127
128impl VerifyBytecodeArgs {
129    /// Run the `verify-bytecode` command to verify the bytecode onchain against the locally built
130    /// bytecode.
131    pub async fn run(mut self) -> Result<()> {
132        // Setup
133        let config = self.load_config()?;
134        let provider = utils::get_provider(&config)?;
135        let strategy = utils::get_executor_strategy(&config);
136
137        // If chain is not set, we try to get it from the RPC.
138        // If RPC is not set, the default chain is used.
139        let chain = match config.get_rpc_url() {
140            Some(_) => utils::get_chain(config.chain, &provider).await?,
141            None => config.chain.unwrap_or_default(),
142        };
143
144        // Set Etherscan options.
145        self.etherscan.chain = Some(chain);
146        self.etherscan.key = config.get_etherscan_config_with_chain(Some(chain))?.map(|c| c.key);
147
148        // Etherscan client
149        let etherscan =
150            EtherscanVerificationProvider.client(&self.etherscan, &self.verifier, &config)?;
151
152        // Get the bytecode at the address, bailing if it doesn't exist.
153        let code = provider.get_code_at(self.address).await?;
154        if code.is_empty() {
155            eyre::bail!("No bytecode found at address {}", self.address);
156        }
157
158        if !shell::is_json() {
159            sh_println!(
160                "Verifying bytecode for contract {} at address {}",
161                self.contract.name,
162                self.address
163            )?;
164        }
165
166        let mut json_results: Vec<JsonResult> = vec![];
167
168        // Get creation tx hash.
169        let creation_data = etherscan.contract_creation_data(self.address).await;
170
171        // Check if contract is a predeploy
172        let (creation_data, maybe_predeploy) = maybe_predeploy_contract(creation_data)?;
173
174        trace!(maybe_predeploy = ?maybe_predeploy);
175
176        // Get the constructor args using `source_code` endpoint.
177        let source_code = etherscan.contract_source_code(self.address).await?;
178
179        // Check if the contract name matches.
180        let name = source_code.items.first().map(|item| item.contract_name.to_owned());
181        if name.as_ref() != Some(&self.contract.name) {
182            eyre::bail!("Contract name mismatch");
183        }
184
185        // Obtain Etherscan compilation metadata.
186        let etherscan_metadata = source_code.items.first().unwrap();
187
188        // Obtain local artifact
189        let artifact = if let Ok(local_bytecode) =
190            crate::utils::build_using_cache(&self, etherscan_metadata, &config)
191        {
192            trace!("using cache");
193            local_bytecode
194        } else {
195            crate::utils::build_project(&self, &config)?
196        };
197
198        // Get local bytecode (creation code)
199        let local_bytecode = artifact
200            .bytecode
201            .as_ref()
202            .and_then(|b| b.to_owned().into_bytes())
203            .ok_or_eyre("Unlinked bytecode is not supported for verification")?;
204
205        // Get and encode user provided constructor args
206        let provided_constructor_args = if let Some(path) = self.constructor_args_path.to_owned() {
207            // Read from file
208            Some(read_constructor_args_file(path)?)
209        } else {
210            self.constructor_args.to_owned()
211        }
212        .map(|args| check_and_encode_args(&artifact, args))
213        .transpose()?
214        .or(self.encoded_constructor_args.to_owned().map(hex::decode).transpose()?);
215
216        let mut constructor_args = if let Some(provided) = provided_constructor_args {
217            provided.into()
218        } else {
219            // If no constructor args were provided, try to retrieve them from the explorer.
220            check_explorer_args(source_code.clone())?
221        };
222
223        // This fails only when the contract expects constructor args but NONE were provided OR
224        // retrieved from explorer (in case of predeploys).
225        crate::utils::check_args_len(&artifact, &constructor_args)?;
226
227        if maybe_predeploy {
228            if !shell::is_json() {
229                sh_warn!(
230                    "Attempting to verify predeployed contract at {:?}. Ignoring creation code verification.",
231                    self.address
232                )?;
233            }
234
235            // Append constructor args to the local_bytecode.
236            trace!(%constructor_args);
237            let mut local_bytecode_vec = local_bytecode.to_vec();
238            local_bytecode_vec.extend_from_slice(&constructor_args);
239
240            // Deploy at genesis
241            let gen_blk_num = 0_u64;
242            let (mut fork_config, evm_opts) = config.clone().load_config_and_evm_opts()?;
243            let (mut env, mut executor) = crate::utils::get_tracing_executor(
244                strategy.clone(),
245                &mut fork_config,
246                gen_blk_num,
247                etherscan_metadata.evm_version()?.unwrap_or(EvmVersion::default()),
248                evm_opts,
249            )
250            .await?;
251
252            env.evm_env.block_env.number = U256::ZERO;
253            let genesis_block = provider.get_block(gen_blk_num.into()).full().await?;
254
255            // Setup genesis tx and env.
256            let deployer = Address::with_last_byte(0x1);
257            let mut gen_tx_req = TransactionRequest::default()
258                .with_from(deployer)
259                .with_input(Bytes::from(local_bytecode_vec))
260                .into_create();
261
262            if let Some(ref block) = genesis_block {
263                configure_env_block(&mut env.as_env_mut(), block);
264                gen_tx_req.max_fee_per_gas = block.header.base_fee_per_gas.map(|g| g as u128);
265                gen_tx_req.gas = Some(block.header.gas_limit);
266                gen_tx_req.gas_price = block.header.base_fee_per_gas.map(|g| g as u128);
267            }
268
269            configure_tx_req_env(&mut env.as_env_mut(), &gen_tx_req, None)
270                .wrap_err("Failed to configure tx request env")?;
271
272            // Seed deployer account with funds
273            let account_info = AccountInfo {
274                balance: U256::from(100 * 10_u128.pow(18)),
275                nonce: 0,
276                ..Default::default()
277            };
278            executor.backend_mut().insert_account_info(deployer, account_info);
279
280            let fork_address = crate::utils::deploy_contract(
281                &mut executor,
282                &env,
283                config.evm_spec_id(),
284                gen_tx_req.to,
285            )?;
286
287            // Compare runtime bytecode
288            let (deployed_bytecode, onchain_runtime_code) = crate::utils::get_runtime_codes(
289                &mut executor,
290                &provider,
291                self.address,
292                fork_address,
293                None,
294            )
295            .await?;
296
297            let match_type = crate::utils::match_bytecodes(
298                deployed_bytecode.original_byte_slice(),
299                &onchain_runtime_code,
300                &constructor_args,
301                true,
302                config.bytecode_hash,
303            );
304
305            crate::utils::print_result(
306                match_type,
307                BytecodeType::Runtime,
308                &mut json_results,
309                etherscan_metadata,
310                &config,
311            );
312
313            if shell::is_json() {
314                sh_println!("{}", serde_json::to_string(&json_results)?)?;
315            }
316
317            return Ok(());
318        }
319
320        // We can unwrap directly as maybe_predeploy is false
321        let creation_data = creation_data.unwrap();
322        // Get transaction and receipt.
323        trace!(creation_tx_hash = ?creation_data.transaction_hash);
324        let transaction = provider
325            .get_transaction_by_hash(creation_data.transaction_hash)
326            .await
327            .or_else(|e| eyre::bail!("Couldn't fetch transaction from RPC: {:?}", e))?
328            .ok_or_else(|| {
329                eyre::eyre!("Transaction not found for hash {}", creation_data.transaction_hash)
330            })?;
331        let receipt = provider
332            .get_transaction_receipt(creation_data.transaction_hash)
333            .await
334            .or_else(|e| eyre::bail!("Couldn't fetch transaction receipt from RPC: {:?}", e))?;
335        let receipt = if let Some(receipt) = receipt {
336            receipt
337        } else {
338            eyre::bail!(
339                "Receipt not found for transaction hash {}",
340                creation_data.transaction_hash
341            );
342        };
343
344        let mut transaction: TransactionRequest = match transaction.inner.inner.inner() {
345            AnyTxEnvelope::Ethereum(tx) => tx.clone().into(),
346            AnyTxEnvelope::Unknown(_) => unreachable!("Unknown transaction type"),
347        };
348
349        // Extract creation code from creation tx input.
350        let maybe_creation_code = if receipt.to.is_none()
351            && receipt.contract_address == Some(self.address)
352        {
353            match &transaction.input.input {
354                Some(input) => &input[..],
355                None => unreachable!("creation tx input is None"),
356            }
357        } else if receipt.to == Some(DEFAULT_CREATE2_DEPLOYER) {
358            match &transaction.input.input {
359                Some(input) => &input[32..],
360                None => unreachable!("creation tx input is None"),
361            }
362        } else {
363            // Try to get creation bytecode from tx trace.
364            let traces = provider
365                .trace_transaction(creation_data.transaction_hash)
366                .await
367                .unwrap_or_default();
368
369            let creation_bytecode =
370                traces.iter().find_map(|trace| match (&trace.trace.result, &trace.trace.action) {
371                    (
372                        Some(TraceOutput::Create(CreateOutput { address, .. })),
373                        Action::Create(CreateAction { init, .. }),
374                    ) if *address == self.address => Some(init.clone()),
375                    _ => None,
376                });
377
378            &creation_bytecode.ok_or_else(|| {
379                eyre::eyre!(
380                    "Could not extract the creation code for contract at address {}",
381                    self.address
382                )
383            })?
384        };
385
386        // In some cases, Etherscan will return incorrect constructor arguments. If this
387        // happens, try extracting arguments ourselves.
388        if !maybe_creation_code.ends_with(&constructor_args) {
389            trace!("mismatch of constructor args with etherscan");
390            // If local bytecode is longer than on-chain one, this is probably not a match.
391            if maybe_creation_code.len() >= local_bytecode.len() {
392                constructor_args =
393                    Bytes::copy_from_slice(&maybe_creation_code[local_bytecode.len()..]);
394                trace!(
395                    target: "forge::verify",
396                    "setting constructor args to latest {} bytes of bytecode",
397                    constructor_args.len()
398                );
399            }
400        }
401
402        // Append constructor args to the local_bytecode.
403        trace!(%constructor_args);
404        let mut local_bytecode_vec = local_bytecode.to_vec();
405        local_bytecode_vec.extend_from_slice(&constructor_args);
406
407        trace!(ignore = ?self.ignore);
408        // Check if `--ignore` is set to `creation`.
409        if !self.ignore.is_some_and(|b| b.is_creation()) {
410            // Compare creation code with locally built bytecode and `maybe_creation_code`.
411            let match_type = crate::utils::match_bytecodes(
412                local_bytecode_vec.as_slice(),
413                maybe_creation_code,
414                &constructor_args,
415                false,
416                config.bytecode_hash,
417            );
418
419            crate::utils::print_result(
420                match_type,
421                BytecodeType::Creation,
422                &mut json_results,
423                etherscan_metadata,
424                &config,
425            );
426
427            // If the creation code does not match, the runtime also won't match. Hence return.
428            if match_type.is_none() {
429                crate::utils::print_result(
430                    None,
431                    BytecodeType::Runtime,
432                    &mut json_results,
433                    etherscan_metadata,
434                    &config,
435                );
436                if shell::is_json() {
437                    sh_println!("{}", serde_json::to_string(&json_results)?)?;
438                }
439                return Ok(());
440            }
441        }
442
443        if !self.ignore.is_some_and(|b| b.is_runtime()) {
444            // Get contract creation block.
445            let simulation_block = match self.block {
446                Some(BlockId::Number(BlockNumberOrTag::Number(block))) => block,
447                Some(_) => eyre::bail!("Invalid block number"),
448                None => {
449                    let provider = utils::get_provider(&config)?;
450                    provider
451                    .get_transaction_by_hash(creation_data.transaction_hash)
452                    .await.or_else(|e| eyre::bail!("Couldn't fetch transaction from RPC: {:?}", e))?.ok_or_else(|| {
453                        eyre::eyre!("Transaction not found for hash {}", creation_data.transaction_hash)
454                    })?
455                    .block_number.ok_or_else(|| {
456                        eyre::eyre!("Failed to get block number of the contract creation tx, specify using the --block flag")
457                    })?
458                }
459            };
460
461            // Fork the chain at `simulation_block`.
462            let (mut fork_config, evm_opts) = config.clone().load_config_and_evm_opts()?;
463            let (mut env, mut executor) = crate::utils::get_tracing_executor(
464                strategy,
465                &mut fork_config,
466                simulation_block - 1, // env.fork_block_number
467                etherscan_metadata.evm_version()?.unwrap_or(EvmVersion::default()),
468                evm_opts,
469            )
470            .await?;
471            env.evm_env.block_env.number = U256::from(simulation_block);
472            let block = provider.get_block(simulation_block.into()).full().await?;
473
474            // Workaround for the NonceTooHigh issue as we're not simulating prior txs of the same
475            // block.
476            let prev_block_id = BlockId::number(simulation_block - 1);
477
478            // Use `transaction.from` instead of `creation_data.contract_creator` to resolve
479            // blockscout creation data discrepancy in case of CREATE2.
480            let prev_block_nonce = provider
481                .get_transaction_count(transaction.from.unwrap())
482                .block_id(prev_block_id)
483                .await?;
484            transaction.set_nonce(prev_block_nonce);
485
486            if let Some(ref block) = block {
487                configure_env_block(&mut env.as_env_mut(), block)
488            }
489
490            // Replace the `input` with local creation code in the creation tx.
491            if let Some(TxKind::Call(to)) = transaction.kind() {
492                if to == DEFAULT_CREATE2_DEPLOYER {
493                    let mut input = transaction.input.input.unwrap()[..32].to_vec(); // Salt
494                    input.extend_from_slice(&local_bytecode_vec);
495                    transaction.input = TransactionInput::both(Bytes::from(input));
496
497                    // Deploy default CREATE2 deployer
498                    executor.deploy_create2_deployer()?;
499                }
500            } else {
501                transaction.input = TransactionInput::both(Bytes::from(local_bytecode_vec));
502            }
503
504            // configure_req__env(&mut env, &transaction.inner);
505            configure_tx_req_env(&mut env.as_env_mut(), &transaction, None)
506                .wrap_err("Failed to configure tx request env")?;
507
508            let fork_address = crate::utils::deploy_contract(
509                &mut executor,
510                &env,
511                config.evm_spec_id(),
512                transaction.to,
513            )?;
514
515            // State committed using deploy_with_env, now get the runtime bytecode from the db.
516            let (fork_runtime_code, onchain_runtime_code) = crate::utils::get_runtime_codes(
517                &mut executor,
518                &provider,
519                self.address,
520                fork_address,
521                Some(simulation_block),
522            )
523            .await?;
524
525            // Compare the onchain runtime bytecode with the runtime code from the fork.
526            let match_type = crate::utils::match_bytecodes(
527                fork_runtime_code.original_byte_slice(),
528                &onchain_runtime_code,
529                &constructor_args,
530                true,
531                config.bytecode_hash,
532            );
533
534            crate::utils::print_result(
535                match_type,
536                BytecodeType::Runtime,
537                &mut json_results,
538                etherscan_metadata,
539                &config,
540            );
541        }
542
543        if shell::is_json() {
544            sh_println!("{}", serde_json::to_string(&json_results)?)?;
545        }
546        Ok(())
547    }
548}