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 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, config.networks);
481
482                let BlockTransactions::Full(ref txs) = block.transactions else {
483                    return Err(eyre::eyre!("Could not get block txs"));
484                };
485
486                // Replay txes in block until the contract creation one.
487                for tx in txs {
488                    trace!("replay tx::: {}", tx.tx_hash());
489                    if is_known_system_sender(tx.from())
490                        || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
491                    {
492                        continue;
493                    }
494                    if tx.tx_hash() == tx_hash {
495                        break;
496                    }
497
498                    configure_tx_env(&mut env.as_env_mut(), &tx.inner);
499
500                    if let TxKind::Call(_) = tx.inner.kind() {
501                        executor.transact_with_env(env.clone()).wrap_err_with(|| {
502                            format!(
503                                "Failed to execute transaction: {:?} in block {}",
504                                tx.tx_hash(),
505                                env.evm_env.block_env.number
506                            )
507                        })?;
508                    } else if let Err(error) = executor.deploy_with_env(env.clone(), None) {
509                        match error {
510                            // Reverted transactions should be skipped
511                            EvmError::Execution(_) => (),
512                            error => {
513                                return Err(error).wrap_err_with(|| {
514                                    format!(
515                                        "Failed to deploy transaction: {:?} in block {}",
516                                        tx.tx_hash(),
517                                        env.evm_env.block_env.number
518                                    )
519                                });
520                            }
521                        }
522                    }
523                }
524            }
525
526            // Replace the `input` with local creation code in the creation tx.
527            if let Some(TxKind::Call(to)) = transaction.kind() {
528                if to == DEFAULT_CREATE2_DEPLOYER {
529                    let mut input = transaction.input.input.unwrap()[..32].to_vec(); // Salt
530                    input.extend_from_slice(&local_bytecode_vec);
531                    transaction.input = TransactionInput::both(Bytes::from(input));
532
533                    // Deploy default CREATE2 deployer
534                    executor.deploy_create2_deployer()?;
535                }
536            } else {
537                transaction.input = TransactionInput::both(Bytes::from(local_bytecode_vec));
538            }
539
540            // configure_req__env(&mut env, &transaction.inner);
541            configure_tx_req_env(&mut env.as_env_mut(), &transaction, None)
542                .wrap_err("Failed to configure tx request env")?;
543
544            let fork_address = crate::utils::deploy_contract(
545                &mut executor,
546                &env,
547                config.evm_spec_id(),
548                transaction.to,
549            )?;
550
551            // State committed using deploy_with_env, now get the runtime bytecode from the db.
552            let (fork_runtime_code, onchain_runtime_code) = crate::utils::get_runtime_codes(
553                &mut executor,
554                &provider,
555                self.address,
556                fork_address,
557                Some(simulation_block),
558            )
559            .await?;
560
561            // Compare the onchain runtime bytecode with the runtime code from the fork.
562            let match_type = crate::utils::match_bytecodes(
563                fork_runtime_code.original_byte_slice(),
564                &onchain_runtime_code,
565                &constructor_args,
566                true,
567                config.bytecode_hash,
568            );
569
570            crate::utils::print_result(
571                match_type,
572                BytecodeType::Runtime,
573                &mut json_results,
574                etherscan_metadata,
575                &config,
576            );
577        }
578
579        if shell::is_json() {
580            sh_println!("{}", serde_json::to_string(&json_results)?)?;
581        }
582        Ok(())
583    }
584}