forge-guard 0.3.6

Pre-deployment smart contract auditing framework for Foundry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! On-chain contract verification — verifies deployed contracts against
//! their source code via block explorers (Etherscan, Basescan, etc.) and
//! RPC bytecode matching.
//!
//! # Explorer URL Registry
//!
//! Maps chain names to their block explorer API URLs for all 17 supported chains.
//! Used by [`forge verify-contract`] and direct API calls.

use std::time::{Duration, Instant};

// ─────────────────────────────────────────────────────────────
// Explorer API URL Registry
// ─────────────────────────────────────────────────────────────

/// Returns the block explorer API base URL for a given chain name.
///
/// These are the standard Etherscan-compatible API endpoints used by
/// `forge verify-contract`. Returns `None` for unknown chains.
pub fn explorer_api_url(chain: &str) -> Option<&'static str> {
    match chain.to_lowercase().as_str() {
        "ethereum" | "eth" | "mainnet" => Some("https://api.etherscan.io/api"),
        "base" => Some("https://api.basescan.org/api"),
        "arbitrum" | "arb" => Some("https://api.arbiscan.io/api"),
        "optimism" | "op" => Some("https://api-optimistic.etherscan.io/api"),
        "polygon" | "matic" => Some("https://api.polygonscan.com/api"),
        "bnb" | "bsc" => Some("https://api.bscscan.com/api"),
        "avalanche" | "avax" => Some("https://api.snowtrace.io/api"),
        "scroll" => Some("https://api.scrollscan.com/api"),
        "linea" => Some("https://api.lineascan.build/api"),
        "zksync" | "zk" => Some("https://api-era.zksync.network/api"),
        "blast" => Some("https://api.blastscan.io/api"),
        "mantle" => Some("https://api.mantlescan.xyz/api"),
        "robinhood" => Some("https://api.robinhoodscan.com/api"),
        _ => None,
    }
}

/// Returns the block explorer front-end URL for a given chain name.
/// Used for providing clickable links in reports.
pub fn explorer_base_url(chain: &str) -> Option<&'static str> {
    match chain.to_lowercase().as_str() {
        "ethereum" | "eth" | "mainnet" => Some("https://etherscan.io"),
        "base" => Some("https://basescan.org"),
        "arbitrum" | "arb" => Some("https://arbiscan.io"),
        "optimism" | "op" => Some("https://optimistic.etherscan.io"),
        "polygon" | "matic" => Some("https://polygonscan.com"),
        "bnb" | "bsc" => Some("https://bscscan.com"),
        "avalanche" | "avax" => Some("https://snowtrace.io"),
        "scroll" => Some("https://scrollscan.com"),
        "linea" => Some("https://lineascan.build"),
        "unichain" => Some("https://uniscan.xyz"),
        "zksync" | "zk" => Some("https://explorer.zksync.io"),
        "hyperevm" | "hyperliquid" => Some("https://hyperscan.xyz"),
        "monad" => Some("https://monadscan.xyz"),
        "sonic" => Some("https://sonicscan.org"),
        "blast" => Some("https://blastscan.io"),
        "mantle" => Some("https://mantlescan.xyz"),
        "robinhood" => Some("https://robinhoodscan.com"),
        _ => None,
    }
}

/// Get the environment variable name for the explorer API key.
pub fn explorer_api_key_env(chain: &str) -> &'static str {
    match chain.to_lowercase().as_str() {
        "ethereum" | "eth" | "mainnet" => "ETHERSCAN_API_KEY",
        "base" => "BASESCAN_API_KEY",
        "arbitrum" | "arb" => "ARBISCAN_API_KEY",
        "optimism" | "op" => "OPTIMISTIC_ETHERSCAN_API_KEY",
        "polygon" | "matic" => "POLYGONSCAN_API_KEY",
        "bnb" | "bsc" => "BSCSCAN_API_KEY",
        "avalanche" | "avax" => "SNOWTRACE_API_KEY",
        "scroll" => "SCROLLSCAN_API_KEY",
        "linea" => "LINEASCAN_API_KEY",
        "zksync" | "zk" => "ZKSYNC_API_KEY",
        "blast" => "BLASTSCAN_API_KEY",
        "mantle" => "MANTLESCAN_API_KEY",
        _ => "ETHERSCAN_API_KEY",
    }
}

// ─────────────────────────────────────────────────────────────
// Verification Types
// ─────────────────────────────────────────────────────────────

/// The result of a verification attempt.
#[derive(Debug, Clone)]
pub struct VerificationResult {
    /// Whether the contract was successfully verified.
    pub verified: bool,
    /// The method used for verification.
    pub method: VerificationMethod,
    /// Human-readable details about the result.
    pub details: String,
    /// Duration of the verification attempt.
    pub duration: Duration,
}

/// The method used for contract verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerificationMethod {
    /// Verified via block explorer API (Etherscan, Basescan, etc.)
    Explorer,
    /// Verified by comparing local bytecode with on-chain bytecode via RPC
    BytecodeMatch,
    /// Verified via Sourcify
    Sourcify,
    /// Not yet verified
    Pending,
}

impl std::fmt::Display for VerificationMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Explorer => write!(f, "Block Explorer"),
            Self::BytecodeMatch => write!(f, "Bytecode Match"),
            Self::Sourcify => write!(f, "Sourcify"),
            Self::Pending => write!(f, "Pending"),
        }
    }
}

// ─────────────────────────────────────────────────────────────
// Verification Engine
// ─────────────────────────────────────────────────────────────

/// Handles on-chain contract verification via explorer APIs and RPC bytecode matching.
pub struct ContractVerifier {
    /// Explorer API key.
    api_key: String,
}

impl ContractVerifier {
    /// Create a new verifier for the given chain.
    ///
    /// `api_key` — optional explorer API key. Reads the chain-specific env var when empty.
    pub fn new(chain: &str, api_key: Option<String>) -> Self {
        let key = api_key
            .filter(|k| !k.is_empty())
            .or_else(|| std::env::var(explorer_api_key_env(chain)).ok())
            .unwrap_or_default();

        Self { api_key: key }
    }

    /// Verify a contract using `forge verify-contract`.
    ///
    /// This delegates to Foundry's built-in Etherscan integration.
    pub fn forge_verify(
        &self,
        address: &str,
        contract_name: &str,
        chain: &str,
        constructor_args: Option<&str>,
    ) -> VerificationResult {
        let start = Instant::now();

        if self.api_key.is_empty() {
            return VerificationResult {
                verified: false,
                method: VerificationMethod::Explorer,
                details: format!(
                    "No API key set. Set {} or pass --explorer-api-key.",
                    explorer_api_key_env(chain)
                ),
                duration: start.elapsed(),
            };
        }

        let mut cmd = std::process::Command::new("forge");
        cmd.arg("verify-contract")
            .arg(address)
            .arg(contract_name)
            .arg("--chain")
            .arg(chain)
            .arg("--etherscan-api-key")
            .arg(&self.api_key);

        if let Some(args) = constructor_args {
            cmd.arg("--constructor-args").arg(args);
        }

        match cmd.output() {
            Ok(output) => {
                let _stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);

                if output.status.success() {
                    VerificationResult {
                        verified: true,
                        method: VerificationMethod::Explorer,
                        details: "Contract verified successfully on block explorer.".into(),
                        duration: start.elapsed(),
                    }
                } else {
                    let msg = if stderr.contains("Already Verified") {
                        "Contract already verified on block explorer.".to_string()
                    } else {
                        format!("Verification failed: {}", stderr.trim())
                    };
                    VerificationResult {
                        verified: msg.contains("Already Verified"),
                        method: VerificationMethod::Explorer,
                        details: msg,
                        duration: start.elapsed(),
                    }
                }
            }
            Err(e) => VerificationResult {
                verified: false,
                method: VerificationMethod::Explorer,
                details: format!("Failed to run forge verify-contract: {e}"),
                duration: start.elapsed(),
            },
        }
    }

    /// Compare locally compiled bytecode with on-chain bytecode via RPC.
    ///
    /// This method:
    /// 1. Runs `forge build` to compile the contract
    /// 2. Extracts the deployed bytecode from `out/`
    /// 3. Calls `eth_getCode` via RPC
    /// 4. Compares the two (stripping metadata hash)
    pub fn verify_bytecode_match(
        &self,
        address: &str,
        contract_name: &str,
        rpc_url: &str,
    ) -> VerificationResult {
        let start = Instant::now();

        // Step 1: Compile the contract
        let _build_output = match std::process::Command::new("forge")
            .arg("build")
            .arg("--silent")
            .output()
        {
            Ok(o) if o.status.success() => o,
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                return VerificationResult {
                    verified: false,
                    method: VerificationMethod::BytecodeMatch,
                    details: format!("Compilation failed: {}", stderr.trim()),
                    duration: start.elapsed(),
                };
            }
            Err(e) => {
                return VerificationResult {
                    verified: false,
                    method: VerificationMethod::BytecodeMatch,
                    details: format!("Failed to run forge build: {e}"),
                    duration: start.elapsed(),
                };
            }
        };

        // Step 2: Parse bytecode from compilation output
        // Forge outputs to out/{contract}.sol/{contract}.json with deployedBytecode field
        let out_path = format!("out/{contract_name}.sol/{contract_name}.json");
        let bytecode = match std::fs::read_to_string(&out_path) {
            Ok(content) => {
                let parsed: serde_json::Value =
                    serde_json::from_str(&content).unwrap_or(serde_json::Value::Null);
                parsed["deployedBytecode"]["object"]
                    .as_str()
                    .map(|s| s.trim_start_matches("0x").to_lowercase())
                    .unwrap_or_default()
            }
            Err(_) => {
                // Try alternate path: flattened contract name
                let alt_path = format!("out/{contract_name}.json");
                match std::fs::read_to_string(&alt_path) {
                    Ok(content) => {
                        let parsed: serde_json::Value =
                            serde_json::from_str(&content).unwrap_or(serde_json::Value::Null);
                        parsed["deployedBytecode"]["object"]
                            .as_str()
                            .map(|s| s.trim_start_matches("0x").to_lowercase())
                            .unwrap_or_default()
                    }
                    Err(_) => String::new(),
                }
            }
        };

        if bytecode.is_empty() {
            return VerificationResult {
                verified: false,
                method: VerificationMethod::BytecodeMatch,
                details: format!(
                    "Could not find compiled bytecode at out/{contract_name}.sol/{contract_name}.json"
                ),
                duration: start.elapsed(),
            };
        }

        // Step 3: Fetch on-chain bytecode via RPC
        let onchain_bytecode = match self.fetch_onchain_bytecode(rpc_url, address) {
            Some(code) => code.trim_start_matches("0x").to_lowercase(),
            None => {
                return VerificationResult {
                    verified: false,
                    method: VerificationMethod::BytecodeMatch,
                    details: format!("Could not fetch on-chain bytecode for {address}"),
                    duration: start.elapsed(),
                };
            }
        };

        // Step 4: Compare (strip metadata hash — last 53 bytes / 106 hex chars)
        let local_stripped = strip_metadata(&bytecode);
        let onchain_stripped = strip_metadata(&onchain_bytecode);

        if local_stripped == onchain_stripped {
            VerificationResult {
                verified: true,
                method: VerificationMethod::BytecodeMatch,
                details: format!(
                    "Local bytecode matches on-chain bytecode at {address} ({} bytes matched)",
                    local_stripped.len() / 2
                ),
                duration: start.elapsed(),
            }
        } else {
            // Find where they diverge
            let diff_pos = local_stripped
                .chars()
                .zip(onchain_stripped.chars())
                .position(|(a, b)| a != b);

            VerificationResult {
                verified: false,
                method: VerificationMethod::BytecodeMatch,
                details: format!(
                    "Bytecode mismatch at address {address}. Local: {} bytes, On-chain: {} bytes{}",
                    local_stripped.len() / 2,
                    onchain_stripped.len() / 2,
                    diff_pos
                        .map(|p| format!(", first difference at hex position {p}"))
                        .unwrap_or_default()
                ),
                duration: start.elapsed(),
            }
        }
    }

    /// Check whether the `forge` CLI is available on the system.
    /// Delegates to the free function [`forge_available()`].
    pub fn forge_available(&self) -> bool {
        forge_available()
    }

    /// Fetch on-chain bytecode using `eth_getCode` RPC call.
    fn fetch_onchain_bytecode(&self, rpc_url: &str, address: &str) -> Option<String> {
        let client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .ok()?;

        let body = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "eth_getCode",
            "params": [address, "latest"],
            "id": 1
        });

        let resp = client
            .post(rpc_url)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .ok()?;

        let text = resp.text().ok()?;
        let parsed: serde_json::Value = serde_json::from_str(&text).ok()?;
        parsed["result"].as_str().map(String::from)
    }
}

/// Strip the Solidity metadata hash from the end of a bytecode string.
///
/// Solidity appends a CBOR-encoded metadata hash (ipfs/Swarm) to the end of
/// deployed bytecode. This hash differs between compilations even when the
/// source code is identical, so we strip it before comparing.
///
/// The metadata is encoded in the last 53 bytes (106 hex chars) of bytecode
/// and always ends with the CBOR tag `0xa264` for IPFS or `0xa265` for Swarm.
fn strip_metadata(bytecode: &str) -> &str {
    // The metadata section is at the end. Solidity 0.8+ uses last 53 bytes.
    // We look for the CBOR metadata marker at the tail.
    let len = bytecode.len();
    if len < 106 {
        return bytecode;
    }

    // Check for the CBOR end-of-encoding marker patterns
    // The last byte of valid bytecode before metadata is the end of the contract code.
    // Metadata starts with 0xa2 (IPFS) or 0xa2 (CBOR map of 2 items) or 0xa3 (CBOR map of 3 items)
    let metadata_start_candidates = [106, 110, 114, 118]; // common metadata lengths

    for &offset in &metadata_start_candidates {
        if offset > len {
            continue;
        }
        let start = len - offset;
        // Check if this looks like metadata by examining the tail pattern
        // Valid metadata ends with 0x00 0x29 (empty string CBOR)
        if bytecode[start..].ends_with("0029") {
            return &bytecode[..start];
        }
    }

    // Fallback: strip the last 106 hex chars (53 bytes)
    &bytecode[..len - 106]
}

/// Check whether `forge` CLI is available on the system.
pub fn forge_available() -> bool {
    std::process::Command::new("forge")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Get the RPC URL for a chain from environment or return a default.
pub fn rpc_url_for_chain(chain: &str) -> String {
    // Check chain-specific env vars first
    let env_var = match chain.to_lowercase().as_str() {
        "ethereum" | "eth" | "mainnet" => "ETH_RPC_URL",
        "base" => "BASE_RPC_URL",
        "arbitrum" | "arb" => "ARBITRUM_RPC_URL",
        "optimism" | "op" => "OPTIMISM_RPC_URL",
        "polygon" | "matic" => "POLYGON_RPC_URL",
        "bnb" | "bsc" => "BSC_RPC_URL",
        _ => "ETH_RPC_URL",
    };

    std::env::var(env_var)
        .or_else(|_| std::env::var("ETH_RPC_URL"))
        .unwrap_or_else(|_| "http://localhost:8545".into())
}

// ── Tests ────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_explorer_api_url_ethereum() {
        assert_eq!(
            explorer_api_url("ethereum"),
            Some("https://api.etherscan.io/api")
        );
        assert_eq!(
            explorer_api_url("eth"),
            Some("https://api.etherscan.io/api")
        );
        assert_eq!(
            explorer_api_url("mainnet"),
            Some("https://api.etherscan.io/api")
        );
    }

    #[test]
    fn test_explorer_api_url_base() {
        assert_eq!(
            explorer_api_url("base"),
            Some("https://api.basescan.org/api")
        );
    }

    #[test]
    fn test_explorer_api_url_arbitrum() {
        assert_eq!(explorer_api_url("arb"), Some("https://api.arbiscan.io/api"));
    }

    #[test]
    fn test_explorer_api_url_unknown() {
        assert_eq!(explorer_api_url("unknown-chain"), None);
    }

    #[test]
    fn test_explorer_base_url() {
        assert_eq!(explorer_base_url("ethereum"), Some("https://etherscan.io"));
        assert_eq!(explorer_base_url("base"), Some("https://basescan.org"));
        assert_eq!(explorer_base_url("arbitrum"), Some("https://arbiscan.io"));
    }

    #[test]
    fn test_explorer_api_key_env() {
        assert_eq!(explorer_api_key_env("ethereum"), "ETHERSCAN_API_KEY");
        assert_eq!(explorer_api_key_env("base"), "BASESCAN_API_KEY");
        assert_eq!(explorer_api_key_env("arb"), "ARBISCAN_API_KEY");
        assert_eq!(explorer_api_key_env("polygon"), "POLYGONSCAN_API_KEY");
    }

    #[test]
    fn test_verifier_no_api_key() {
        let verifier = ContractVerifier::new("ethereum", None);
        let result = verifier.forge_verify("0x1234", "MyContract", "ethereum", None);
        assert!(!result.verified);
        assert!(result.details.contains("API key"));
    }

    #[test]
    fn test_verifier_explicit_api_key() {
        let verifier = ContractVerifier::new("ethereum", Some("test_key".into()));
        // This will fail because forge isn't available or the address doesn't exist,
        // but it proves the API key was used.
        let result = verifier.forge_verify("0x1234", "MyContract", "ethereum", None);
        // It should try to run forge, not fail on API key
        assert!(result.details.contains("failed") || result.details.contains("forge"));
    }

    #[test]
    fn test_strip_metadata_short_bytecode() {
        // Bytecode shorter than metadata section — return as-is
        let short = "0x1234";
        assert_eq!(strip_metadata(short), short);
    }

    #[test]
    fn test_strip_metadata_with_cbor_tail() {
        // Simulated bytecode of sufficient length
        let mut bytecode = "608060405260008054".to_string();
        // Pad to 200 chars
        while bytecode.len() < 200 {
            bytecode.push_str("00");
        }
        // Add CBOR tail ending with 0029
        bytecode.push_str("a2646970667358221220");
        while bytecode.len() % 2 != 0 {
            bytecode.push('0');
        }
        // End with 0029
        if !bytecode.ends_with("0029") {
            bytecode.push_str("0029");
        }

        let stripped = strip_metadata(&bytecode);
        assert!(
            stripped.len() < bytecode.len(),
            "should strip metadata bytes"
        );
        assert!(stripped.ends_with("00"), "should end with valid opcode");
    }

    #[test]
    fn test_verification_method_display() {
        assert_eq!(VerificationMethod::Explorer.to_string(), "Block Explorer");
        assert_eq!(
            VerificationMethod::BytecodeMatch.to_string(),
            "Bytecode Match"
        );
        assert_eq!(VerificationMethod::Pending.to_string(), "Pending");
    }

    #[test]
    fn test_verification_result_creation() {
        let result = VerificationResult {
            verified: true,
            method: VerificationMethod::Explorer,
            details: "Success".into(),
            duration: Duration::from_secs(2),
        };
        assert!(result.verified);
        assert_eq!(result.method, VerificationMethod::Explorer);
    }

    #[test]
    fn test_rpc_url_from_env() {
        // Should return default when no env vars are set
        let url = rpc_url_for_chain("ethereum");
        assert!(!url.is_empty());
        assert!(url.contains("localhost") || url.contains("http"));
    }

    #[test]
    fn test_forge_available() {
        // This test verifies forge detection — forge might not be installed
        // in the test environment, so we just check it doesn't panic
        let _available = forge_available();
    }

    #[test]
    fn test_bytecode_verify_no_forge() {
        let verifier = ContractVerifier::new("ethereum", None);
        let result = verifier.verify_bytecode_match(
            "0xdead000000000000000000000000000000000000",
            "Nonexistent",
            "http://localhost:8545",
        );
        // Should fail gracefully, not panic
        assert!(!result.verified, "should fail without forge build");
        assert!(!result.details.is_empty());
    }
}