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