Skip to content

Commit b359b08

Browse files
authored
feat: Selector generator tool (#2844)
## 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.
1 parent 4a10d7d commit b359b08

File tree

7 files changed

+670
-0
lines changed

7 files changed

+670
-0
lines changed

Cargo.lock

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ members = [
66
"core/bin/external_node",
77
"core/bin/merkle_tree_consistency_checker",
88
"core/bin/snapshots_creator",
9+
"core/bin/selector_generator",
910
"core/bin/system-constants-generator",
1011
"core/bin/verified_sources_fetcher",
1112
"core/bin/zksync_server",
@@ -120,6 +121,7 @@ envy = "0.4"
120121
ethabi = "18.0.0"
121122
flate2 = "1.0.28"
122123
futures = "0.3"
124+
glob = "0.3"
123125
google-cloud-auth = "0.16.0"
124126
google-cloud-storage = "0.20.0"
125127
governor = "0.4.2"
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "selector_generator"
3+
version = "0.1.0"
4+
edition.workspace = true
5+
authors.workspace = true
6+
homepage.workspace = true
7+
repository.workspace = true
8+
license.workspace = true
9+
keywords.workspace = true
10+
categories.workspace = true
11+
publish = false
12+
13+
[dependencies]
14+
serde = { workspace = true, features = ["derive"] }
15+
serde_json.workspace = true
16+
sha3.workspace = true
17+
glob.workspace = true
18+
clap = { workspace = true, features = ["derive"] }

core/bin/selector_generator/README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Generates the list of solidity selectors
2+
3+
This tool generates a mapping from solidity selectors to function names.
4+
5+
The output json file can be used by multiple tools to improve debugging and readability.
6+
7+
By default, it appends the newly found selectors into the list.
8+
9+
To run, first make sure that you have your contracts compiled and then run:
10+
11+
```
12+
cargo run ../../../contracts ../../../etc/selector-generator-data/selectors.json
13+
```
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
use std::{
2+
collections::HashMap,
3+
fs::{File, OpenOptions},
4+
io::{self},
5+
};
6+
7+
use clap::Parser;
8+
use glob::glob;
9+
use serde::{Deserialize, Serialize};
10+
use sha3::{Digest, Keccak256};
11+
12+
#[derive(Debug, Serialize, Deserialize)]
13+
struct ABIEntry {
14+
#[serde(rename = "type")]
15+
entry_type: String,
16+
name: Option<String>,
17+
inputs: Option<Vec<ABIInput>>,
18+
}
19+
20+
#[derive(Debug, Serialize, Deserialize)]
21+
struct ABIInput {
22+
#[serde(rename = "type")]
23+
input_type: String,
24+
}
25+
26+
#[derive(Debug, Parser)]
27+
#[command(author, version, about, long_about = None)]
28+
struct Cli {
29+
contracts_dir: String,
30+
output_file: String,
31+
}
32+
33+
/// Computes solidity selector for a given method and arguments.
34+
fn compute_selector(name: &str, inputs: &[ABIInput]) -> String {
35+
let signature = format!(
36+
"{}({})",
37+
name,
38+
inputs
39+
.iter()
40+
.map(|i| i.input_type.clone())
41+
.collect::<Vec<_>>()
42+
.join(",")
43+
);
44+
let mut hasher = Keccak256::new();
45+
hasher.update(signature);
46+
format!("{:x}", hasher.finalize())[..8].to_string()
47+
}
48+
49+
/// Analyses all the JSON files, looking for 'abi' entries, and then computing the selectors for them.
50+
fn process_files(directory: &str, output_file: &str) -> io::Result<()> {
51+
let mut selectors: HashMap<String, String> = match File::open(output_file) {
52+
Ok(file) => serde_json::from_reader(file).unwrap_or_default(),
53+
Err(_) => HashMap::new(),
54+
};
55+
let selectors_before = selectors.len();
56+
let mut analyzed_files = 0;
57+
58+
for entry in glob(&format!("{}/**/*.json", directory)).expect("Failed to read glob pattern") {
59+
match entry {
60+
Ok(path) => {
61+
let file_path = path.clone();
62+
let file = File::open(path)?;
63+
let json: Result<serde_json::Value, _> = serde_json::from_reader(file);
64+
65+
if let Ok(json) = json {
66+
if let Some(abi) = json.get("abi").and_then(|v| v.as_array()) {
67+
analyzed_files += 1;
68+
for item in abi {
69+
let entry: ABIEntry = serde_json::from_value(item.clone()).unwrap();
70+
if entry.entry_type == "function" {
71+
if let (Some(name), Some(inputs)) = (entry.name, entry.inputs) {
72+
let selector = compute_selector(&name, &inputs);
73+
selectors.entry(selector).or_insert(name);
74+
}
75+
}
76+
}
77+
}
78+
} else {
79+
eprintln!("Error parsing file: {:?} - ignoring.", file_path)
80+
}
81+
}
82+
Err(e) => eprintln!("Error reading file: {:?}", e),
83+
}
84+
}
85+
println!(
86+
"Analyzed {} files. Added {} selectors (before: {} after: {})",
87+
analyzed_files,
88+
selectors.len() - selectors_before,
89+
selectors_before,
90+
selectors.len()
91+
);
92+
93+
let file = OpenOptions::new()
94+
.write(true)
95+
.create(true)
96+
.truncate(true)
97+
.open(output_file)?;
98+
serde_json::to_writer_pretty(file, &selectors)?;
99+
Ok(())
100+
}
101+
102+
fn main() -> io::Result<()> {
103+
let args = Cli::parse();
104+
process_files(&args.contracts_dir, &args.output_file)
105+
}

etc/selector-generator-data/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# List of selectors from our contracts
2+
3+
To regenerate the list, please use the selector_generator tool from core/bin directory.

0 commit comments

Comments
 (0)