Skip to content

Commit

Permalink
feat: Selector generator tool (matter-labs#2844)
Browse files Browse the repository at this point in the history
## What ❔

* A small tool to generate the selector hashes based on the ABI from
json files

## Why ❔

* The output json can be useful for humans to better understand some of
the errors (and calldata)
* It can also be read by our tools, to make the debugging easier.

In the future, we could call this tool regularly on each contracts
version change, but for now it can stay as manual.
  • Loading branch information
mm-zk authored Sep 12, 2024
1 parent 4a10d7d commit b359b08
Show file tree
Hide file tree
Showing 7 changed files with 670 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ members = [
"core/bin/external_node",
"core/bin/merkle_tree_consistency_checker",
"core/bin/snapshots_creator",
"core/bin/selector_generator",
"core/bin/system-constants-generator",
"core/bin/verified_sources_fetcher",
"core/bin/zksync_server",
Expand Down Expand Up @@ -120,6 +121,7 @@ envy = "0.4"
ethabi = "18.0.0"
flate2 = "1.0.28"
futures = "0.3"
glob = "0.3"
google-cloud-auth = "0.16.0"
google-cloud-storage = "0.20.0"
governor = "0.4.2"
Expand Down
18 changes: 18 additions & 0 deletions core/bin/selector_generator/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "selector_generator"
version = "0.1.0"
edition.workspace = true
authors.workspace = true
homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
categories.workspace = true
publish = false

[dependencies]
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
sha3.workspace = true
glob.workspace = true
clap = { workspace = true, features = ["derive"] }
13 changes: 13 additions & 0 deletions core/bin/selector_generator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Generates the list of solidity selectors

This tool generates a mapping from solidity selectors to function names.

The output json file can be used by multiple tools to improve debugging and readability.

By default, it appends the newly found selectors into the list.

To run, first make sure that you have your contracts compiled and then run:

```
cargo run ../../../contracts ../../../etc/selector-generator-data/selectors.json
```
105 changes: 105 additions & 0 deletions core/bin/selector_generator/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use std::{
collections::HashMap,
fs::{File, OpenOptions},
io::{self},
};

use clap::Parser;
use glob::glob;
use serde::{Deserialize, Serialize};
use sha3::{Digest, Keccak256};

#[derive(Debug, Serialize, Deserialize)]
struct ABIEntry {
#[serde(rename = "type")]
entry_type: String,
name: Option<String>,
inputs: Option<Vec<ABIInput>>,
}

#[derive(Debug, Serialize, Deserialize)]
struct ABIInput {
#[serde(rename = "type")]
input_type: String,
}

#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
contracts_dir: String,
output_file: String,
}

/// Computes solidity selector for a given method and arguments.
fn compute_selector(name: &str, inputs: &[ABIInput]) -> String {
let signature = format!(
"{}({})",
name,
inputs
.iter()
.map(|i| i.input_type.clone())
.collect::<Vec<_>>()
.join(",")
);
let mut hasher = Keccak256::new();
hasher.update(signature);
format!("{:x}", hasher.finalize())[..8].to_string()
}

/// Analyses all the JSON files, looking for 'abi' entries, and then computing the selectors for them.
fn process_files(directory: &str, output_file: &str) -> io::Result<()> {
let mut selectors: HashMap<String, String> = match File::open(output_file) {
Ok(file) => serde_json::from_reader(file).unwrap_or_default(),
Err(_) => HashMap::new(),
};
let selectors_before = selectors.len();
let mut analyzed_files = 0;

for entry in glob(&format!("{}/**/*.json", directory)).expect("Failed to read glob pattern") {
match entry {
Ok(path) => {
let file_path = path.clone();
let file = File::open(path)?;
let json: Result<serde_json::Value, _> = serde_json::from_reader(file);

if let Ok(json) = json {
if let Some(abi) = json.get("abi").and_then(|v| v.as_array()) {
analyzed_files += 1;
for item in abi {
let entry: ABIEntry = serde_json::from_value(item.clone()).unwrap();
if entry.entry_type == "function" {
if let (Some(name), Some(inputs)) = (entry.name, entry.inputs) {
let selector = compute_selector(&name, &inputs);
selectors.entry(selector).or_insert(name);
}
}
}
}
} else {
eprintln!("Error parsing file: {:?} - ignoring.", file_path)
}
}
Err(e) => eprintln!("Error reading file: {:?}", e),
}
}
println!(
"Analyzed {} files. Added {} selectors (before: {} after: {})",
analyzed_files,
selectors.len() - selectors_before,
selectors_before,
selectors.len()
);

let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(output_file)?;
serde_json::to_writer_pretty(file, &selectors)?;
Ok(())
}

fn main() -> io::Result<()> {
let args = Cli::parse();
process_files(&args.contracts_dir, &args.output_file)
}
3 changes: 3 additions & 0 deletions etc/selector-generator-data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# List of selectors from our contracts

To regenerate the list, please use the selector_generator tool from core/bin directory.
Loading

0 comments on commit b359b08

Please sign in to comment.