Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for binary_mappings and network_family configs #9505

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/anvil/src/anvil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ fn main() {
fn run() -> Result<()> {
utils::load_dotenv();

if let Some(to) = utils::should_redirect_to()? {
utils::redirect_execution(to)?;
return Ok(())
}

let mut args = Anvil::parse();
args.global.init()?;
args.node.evm.resolve_rpc_alias();
Expand Down
5 changes: 5 additions & 0 deletions crates/cast/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ fn run() -> Result<()> {
utils::subscriber();
utils::enable_paint();

if let Some(to) = utils::should_redirect_to()? {
utils::redirect_execution(to)?;
return Ok(())
}

let args = CastArgs::parse();
args.global.init()?;
main_args(args)
Expand Down
5 changes: 5 additions & 0 deletions crates/chisel/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ fn run() -> eyre::Result<()> {
utils::subscriber();
utils::load_dotenv();

if let Some(to) = utils::should_redirect_to()? {
utils::redirect_execution(to)?;
return Ok(())
}

let args = Chisel::parse();
args.global.init()?;
main_args(args)
Expand Down
126 changes: 126 additions & 0 deletions crates/cli/src/utils/bin_redirect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use std::{io::IsTerminal, path::PathBuf};

use eyre::{Context as _, ContextCompat as _};
use foundry_common::{io::style::WARN, stdin::parse_line, Shell};
use foundry_config::network_family::NetworkFamily;

/// Loads config and checks if there is a binary remapping for the current binary.
/// If there is a remapping, returns the path to the binary that should be executed.
/// Returns `None` if the binary is not remapped _or_ if the current binary is not found in the
/// config.
///
/// Required user consent for the redirect. If consent is not provided (either via
/// config or prompt), will return an error.
pub fn should_redirect_to() -> eyre::Result<Option<PathBuf>> {
let current_exe =
std::env::current_exe().context("Unable to query the current executable name")?;
let binary_name = current_exe
.file_stem()
.with_context(|| "Unable to parse executable file name")?
.to_str()
.context("Executable name is not UTF-8")?;
let config = foundry_config::Config::load()?;
let Some(redirect) = config.binary_mappings().redirect_for(binary_name).cloned() else {
trace!(
binary_name = ?binary_name,
redirects = ?config.binary_mappings(),
"No redirect is found",
);
return Ok(None)
};

// We cannot use shell macros, since they will implicitly initialize global shell.
let mut shell = Shell::default();

// Ensure that if redirect exists, user opted in to it.
let redirect = match config.allow_alternative_binaries {
Some(true) => {
// User opted in to alternative binaries.
Some(redirect)
}
Some(false) => {
// User opted out of alternative binaries.
shell.warn("A binary remapping was detected, but `allow_alternative_binaries` is set to false, which prohibits the redirects.")?;
eyre::bail!("Binary remapping is not allowed by the user.");
}
None => {
// Prompt user to allow alternative binary.
shell.warn("")?;
let mut lines = vec![
"A binary remapping was detected, but `allow_alternative_binaries` is not set in the config.".to_string(),
"You can set `allow_alternative_binaries` config to `true` to avoid this prompt.".to_string(),
"Foundry team is not responsible for the safety of the redirected binary.".to_string(),
format!("If you would allow it, the execution would be redirected to the following binary: {redirect:?}")
];
append_attestation_docs(&mut lines, &config, &redirect);

print_box_message(&mut shell, &lines)?;

let std = std::io::stdin();
if !std.is_terminal() {
shell.error("std is not a terminal, cannot prompt user. Ignoring the redirect")?;
eyre::bail!("Binary remapping must be explicitly allowed");
}

shell.print_out("Do you want to allow the redirect? [y/N] ")?;
std::io::Write::flush(&mut std::io::stdout())?;

let response: String = parse_line()?;
if matches!(response.as_str(), "y" | "Y") {
Some(redirect)
} else {
eyre::bail!("User did not allow redirecting to another binary");
}
}
};
Ok(redirect)
}

/// Appends the lines that explain how to verify the binary attestation.
fn append_attestation_docs(
lines: &mut Vec<String>,
config: &foundry_config::Config,
binary_name: &PathBuf,
) {
if config.network_family == NetworkFamily::Zksync {
lines.extend_from_slice(&[
String::new(),
"Tip:".to_string(),
"ZKsync network family is selected in the config.".to_string(),
"To verify the authenticity of the binary, you can use the following command (Linux/MacOS):".to_string(),
format!("$ gh attestation verify --owner matter-labs $(which {binary_name:?})"),
])
}
}

fn print_box_message(shell: &mut Shell, lines: &[String]) -> eyre::Result<()> {
// Print messages via `shell.print` rounding them with an ascii box.
let max_len = lines.iter().map(String::len).max().unwrap_or(0);
let top = format!("+{:-<1$}+\n", "", max_len + 2);
shell.write_stdout(&top, &WARN)?;
for line in lines {
shell.write_stdout("| ", &WARN)?;
shell.print_out(format!("{line:<max_len$}"))?;
shell.write_stdout(" |\n", &WARN)?;
}
shell.write_stdout(&top, &WARN)?;
Ok(())
}

/// Launches the `to` binary with the same arguments as the current binary.
/// E.g. if user runs `forge build --arg1 --arg2`, and `to` is `/path/to/custom/forge`, then
/// this function will run `/path/to/custom/forge build --arg1 --arg2`.
pub fn redirect_execution(to: PathBuf) -> eyre::Result<()> {
// We cannot use shell macros, since they will implicitly initialize global shell.
let mut shell = Shell::default();
shell.warn(format!("Redirecting execution to: {to:?}"))?;
let args = std::env::args().skip(1).collect::<Vec<_>>();
let status = std::process::Command::new(to)
.args(args)
.status()
.map_err(|e| eyre::eyre!("Failed to run command: {}", e))?;
if !status.success() {
eyre::bail!("Command failed with status: {}", status);
}
Ok(())
}
3 changes: 3 additions & 0 deletions crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ pub use suggestions::*;
mod abi;
pub use abi::*;

mod bin_redirect;
pub use bin_redirect::*;

// reexport all `foundry_config::utils`
#[doc(hidden)]
pub use foundry_config::utils::*;
Expand Down
109 changes: 109 additions & 0 deletions crates/config/src/binary_mappings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use std::{
collections::HashMap,
path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};

/// Binaries that can be remapped.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BinaryName {
Forge,
Anvil,
Cast,
Chisel,
}

impl TryFrom<&str> for BinaryName {
type Error = eyre::Error;

fn try_from(value: &str) -> eyre::Result<Self> {
match value {
"forge" => Ok(Self::Forge),
"anvil" => Ok(Self::Anvil),
"cast" => Ok(Self::Cast),
"chisel" => Ok(Self::Chisel),
_ => eyre::bail!("Invalid binary name: {value}"),
}
}
}

/// Contains the config for binary remappings,
/// e.g. ability to redirect any of the foundry binaries to some other binary.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryMappings {
/// The mappings from binary name to the path of the binary.
#[serde(flatten)]
pub mappings: HashMap<BinaryName, PathBuf>,
}

impl BinaryMappings {
/// Tells if the binary name is remapped to some other binary.
/// This function will return `None` if the binary name cannot be parsed or if
/// the binary name is not remapped.
pub fn redirect_for(&self, binary_name: &str) -> Option<&PathBuf> {
// Sanitize the path so that it
let binary_name = Path::new(binary_name).file_stem()?.to_str()?;
let binary_name = BinaryName::try_from(binary_name).ok()?;
self.mappings.get(&binary_name)
}
}

impl<T> From<T> for BinaryMappings
where
T: Into<HashMap<BinaryName, PathBuf>>,
{
fn from(mappings: T) -> Self {
Self { mappings: mappings.into() }
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn binary_names() {
assert_eq!(BinaryName::try_from("forge").unwrap(), BinaryName::Forge);
assert_eq!(BinaryName::try_from("anvil").unwrap(), BinaryName::Anvil);
assert_eq!(BinaryName::try_from("cast").unwrap(), BinaryName::Cast);
assert_eq!(BinaryName::try_from("chisel").unwrap(), BinaryName::Chisel);
}

#[test]
fn binary_names_serde() {
let test_vector = [
(BinaryName::Forge, r#""forge""#),
(BinaryName::Anvil, r#""anvil""#),
(BinaryName::Cast, r#""cast""#),
(BinaryName::Chisel, r#""chisel""#),
];

for (binary_name, expected) in test_vector.iter() {
let serialized = serde_json::to_string(binary_name).unwrap();
assert_eq!(serialized, *expected);

let deserialized: BinaryName = serde_json::from_str(expected).unwrap();
assert_eq!(deserialized, *binary_name);
}
}

#[test]
fn redirect_to() {
let mappings = BinaryMappings::from([
(BinaryName::Forge, PathBuf::from("forge-zksync")),
(BinaryName::Anvil, PathBuf::from("anvil-zksync")),
(BinaryName::Cast, PathBuf::from("cast-zksync")),
(BinaryName::Chisel, PathBuf::from("chisel-zksync")),
]);

assert_eq!(mappings.redirect_for("forge"), Some(&PathBuf::from("forge-zksync")));
assert_eq!(mappings.redirect_for("anvil"), Some(&PathBuf::from("anvil-zksync")));
assert_eq!(mappings.redirect_for("cast"), Some(&PathBuf::from("cast-zksync")));
assert_eq!(mappings.redirect_for("chisel"), Some(&PathBuf::from("chisel-zksync")));
assert_eq!(mappings.redirect_for("invalid"), None);
assert_eq!(mappings.redirect_for("/usr/bin/forge"), Some(&PathBuf::from("forge-zksync")));
assert_eq!(mappings.redirect_for("anvil.exe"), Some(&PathBuf::from("anvil-zksync")));
}
}
Loading