-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbuild.rs
More file actions
438 lines (380 loc) · 14.6 KB
/
build.rs
File metadata and controls
438 lines (380 loc) · 14.6 KB
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
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]
#![allow(clippy::panic)]
use std::collections::BTreeMap;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use glob::glob;
use nom::IResult;
use nom::Parser;
use nom::bytes::complete::tag;
use nom::character::complete::hex_digit1;
use nom::combinator::rest;
use nom::sequence::preceded;
use nom::sequence::separated_pair;
use vergen_gitcl::AddCustomEntries;
use vergen_gitcl::BuildBuilder;
use vergen_gitcl::CargoBuilder;
use vergen_gitcl::CargoRerunIfChanged;
use vergen_gitcl::CargoWarning;
use vergen_gitcl::DefaultConfig;
use vergen_gitcl::Emitter;
use vergen_gitcl::GitclBuilder;
use vergen_gitcl::RustcBuilder;
use vergen_gitcl::SysinfoBuilder;
fn main() {
print_build_directives();
generate_build_info();
generate_contracts_structs();
generate_signatures_structs();
generate_client_scopes_matcher();
}
// -----------------------------------------------------------------------------
// Directives
// -----------------------------------------------------------------------------
fn print_build_directives() {
// any code change
println!("cargo:rerun-if-changed=src/");
// used in signatures codegen
println!("cargo:rerun-if-changed=static/");
// retrigger database compile-time checks
println!("cargo:rerun-if-changed=.sqlx/");
// client scopes configuration
println!("cargo:rerun-if-changed=static/client_scopes/client_scopes.txt");
}
// -----------------------------------------------------------------------------
// Code generation: Build Info
// -----------------------------------------------------------------------------
#[derive(Default)]
struct Custom {}
impl AddCustomEntries<&str, &str> for Custom {
fn add_calculated_entries(
&self,
_idempotent: bool,
cargo_rustc_env_map: &mut BTreeMap<&str, &str>,
_cargo_rerun_if_changed: &mut CargoRerunIfChanged,
_cargo_warning: &mut CargoWarning,
) -> anyhow::Result<()> {
// Get git remote URL using git command
let git_repo_url = Command::new("git")
.args(["remote", "get-url", "origin"])
.output()
.ok()
.and_then(|output| {
if output.status.success() {
String::from_utf8(output.stdout).ok()
} else {
None
}
})
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "unknown".to_string());
let git_url_static = Box::leak(git_repo_url.into_boxed_str());
cargo_rustc_env_map.insert("VERGEN_GIT_REPO_URL", git_url_static);
Ok(())
}
fn add_default_entries(
&self,
_config: &DefaultConfig,
_cargo_rustc_env_map: &mut BTreeMap<&str, &str>,
_cargo_rerun_if_changed: &mut CargoRerunIfChanged,
_cargo_warning: &mut CargoWarning,
) -> anyhow::Result<()> {
Ok(())
}
}
fn generate_build_info() {
// Capture the hostname of the machine where the binary is being built
let build_hostname = hostname::get().unwrap_or_default().to_string_lossy().into_owned();
// Export BUILD_HOSTNAME as a compile-time environment variable
println!("cargo:rustc-env=BUILD_HOSTNAME={build_hostname}");
// Capture OpenSSL version
let openssl_version = Command::new("openssl")
.arg("version")
.output()
.ok()
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|s| {
// take just the version number
s.split_whitespace().nth(1).unwrap_or("unknown").to_string()
})
.unwrap_or_else(|| "unknown".to_string());
// Capture glibc version (Linux only)
let glibc_version = if cfg!(target_os = "linux") {
Command::new("ldd")
.arg("--version")
.output()
.ok()
.and_then(|output| String::from_utf8(output.stdout).ok())
.and_then(|s| s.lines().next().map(|s| s.to_string())) // take just the first line
.map(|s| s.replace("ldd (GNU libc) ", "")) // take just the version number
.unwrap_or_else(|| "unknown".to_string())
} else {
"not applicable".to_string()
};
// Export as compile-time environment variables
println!("cargo:rustc-env=BUILD_OPENSSL_VERSION={}", openssl_version.trim());
println!("cargo:rustc-env=BUILD_GLIBC_VERSION={}", glibc_version.trim());
if let Err(e) = Emitter::default()
.add_instructions(&BuildBuilder::default().build_timestamp(true).build().unwrap())
.unwrap()
.add_instructions(&CargoBuilder::default().debug(true).features(true).build().unwrap())
.unwrap()
.add_instructions(
&GitclBuilder::default()
.branch(true)
.describe(false, true, None)
.sha(true)
.commit_timestamp(true)
.commit_message(true)
.commit_author_name(true)
.build()
.unwrap(),
)
.unwrap()
.add_instructions(&RustcBuilder::default().semver(true).channel(true).host_triple(true).build().unwrap())
.unwrap()
.add_instructions(&SysinfoBuilder::default().os_version(true).user(true).build().unwrap())
.unwrap()
.add_custom_instructions(&Custom::default())
.unwrap()
.emit()
{
panic!("Failed to emit build information | reason={e:?}");
};
}
// -----------------------------------------------------------------------------
// Code generation: Contract addresses
// -----------------------------------------------------------------------------
type ContractAddress = [u8; 20];
type ContractName = str;
fn generate_contracts_structs() {
write_module("contracts.rs", generate_contracts_module_content());
}
fn generate_contracts_module_content() -> String {
let deployment_files = list_files("static/contracts-deployments/*.csv");
let mut seen = HashSet::<ContractAddress>::new();
let mut contracts = phf_codegen::Map::<[u8; 20]>::new();
for deployment_file in deployment_files {
populate_contracts_map(&deployment_file.content, &mut seen, &mut contracts);
}
format!(
"
/// Mapping between 20 byte address and contract names.
pub static CONTRACTS: phf::Map<[u8; 20], &'static str> = {};
",
contracts.build()
)
}
fn populate_contracts_map(file_content: &str, seen: &mut HashSet<ContractAddress>, contracts: &mut phf_codegen::Map<[u8; 20]>) {
for line in file_content.lines() {
let (address, name) = parse_contract(line);
if seen.contains(&address) {
continue;
}
seen.insert(address);
let name = format!("\"{name}\"");
contracts.entry(address, name);
}
}
fn parse_contract(input: &str) -> (ContractAddress, &ContractName) {
fn parse(input: &str) -> IResult<&str, (&str, &str)> {
separated_pair(preceded(tag("0x"), hex_digit1), tag(","), rest).parse(input)
}
let (_, (address, name)) = parse(input).expect("Contract deployment line should match the expected pattern | pattern=[0x<hex_address>,<name>]\n");
let address = match const_hex::decode(address) {
Ok(address) => address,
Err(e) => panic!("Failed to parse contract address as hexadecimal | value={address} reason={e:?}"),
};
let address: [u8; 20] = match address.try_into() {
Ok(address) => address,
Err(address) => panic!(
"Contract address should have 20 bytes | value={}, len={}",
const_hex::encode_prefixed(&address),
address.len()
),
};
(address, name)
}
// -----------------------------------------------------------------------------
// Code generation: Solidity signatures
// -----------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
enum SolidityId {
FunctionOrError(SolidityFunctionOrErrorId),
Event(SolidityEventId),
}
type SolidityFunctionOrErrorId = [u8; 4];
type SolidityEventId = [u8; 32];
type SoliditySignature = str;
fn generate_signatures_structs() {
write_module("signatures.rs", generate_signature_module_content());
}
/// Generates the `signatures.rs` file containing a static PHF map with Solidity hashes and their description.
fn generate_signature_module_content() -> String {
let signature_files = list_files("static/contracts-signatures/*.signatures");
let mut seen = HashSet::<SolidityId>::new();
let mut signatures_4_bytes = phf_codegen::Map::<[u8; 4]>::new();
let mut signatures_32_bytes = phf_codegen::Map::<[u8; 32]>::new();
for signature_file in signature_files {
populate_signature_maps(&signature_file.content, &mut seen, &mut signatures_4_bytes, &mut signatures_32_bytes);
}
format!(
"
/// Mapping between 4 byte signatures and Solidity function and error signatures.
pub static SIGNATURES_4_BYTES: phf::Map<[u8; 4], &'static str> = {};
/// Mapping between 32 byte signatures and Solidity events signatures.
pub static SIGNATURES_32_BYTES: phf::Map<[u8; 32], &'static str> = {};
",
signatures_4_bytes.build(),
signatures_32_bytes.build()
)
}
fn populate_signature_maps(
file_content: &str,
seen: &mut HashSet<SolidityId>,
signatures_4_bytes: &mut phf_codegen::Map<[u8; 4]>,
signatures_32_bytes: &mut phf_codegen::Map<[u8; 32]>,
) {
for line in file_content.lines() {
// skip empty lines and header lines
if line.is_empty() || line.contains("signatures") {
continue;
}
// parse
let (id, signature) = parse_signature(line);
// check tracked
if seen.contains(&id) {
continue;
}
// track
seen.insert(id);
let signature = format!("\"{signature}\"");
match id {
SolidityId::FunctionOrError(id) => {
signatures_4_bytes.entry(id, signature.clone());
}
SolidityId::Event(id) => {
signatures_32_bytes.entry(id, signature);
}
}
}
}
fn parse_signature(input: &str) -> (SolidityId, &SoliditySignature) {
fn parse(input: &str) -> IResult<&str, (&str, &str)> {
separated_pair(hex_digit1, tag(": "), rest).parse(input)
}
let (_, (id, signature)) = parse(input).expect("Solidity signature line should match the expected pattern | pattern=[0x<hex_id>: <signature>]\n");
let id = match const_hex::decode(id) {
Ok(id) => id,
Err(e) => panic!("Failed to parse Solidity ID as hexadecimal | value={id} reason={e:?}"),
};
// try to parse 32 bytes
let id_result: Result<SolidityEventId, Vec<u8>> = id.clone().try_into();
if let Ok(id) = id_result {
return (SolidityId::Event(id), signature);
}
// try to parse 4 bytes
let id_result: Result<SolidityFunctionOrErrorId, Vec<u8>> = id.clone().try_into();
if let Ok(id) = id_result {
return (SolidityId::FunctionOrError(id), signature);
}
// failure
panic!(
"Failed to parse Solidity ID as function, error or event | id={} len={}",
const_hex::encode_prefixed(&id),
id.len()
);
}
// -----------------------------------------------------------------------------
// Code generation: Client Scopes Matcher
// -----------------------------------------------------------------------------
fn generate_client_scopes_matcher() {
write_module("client_scopes.rs", generate_client_scopes_content());
}
fn generate_client_scopes_content() -> String {
let scopes_file = fs::read_to_string("static/client_scopes/client_scopes.txt").expect("Failed to read client_scopes.txt");
let mut match_arms = Vec::new();
for line in scopes_file.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((scope, patterns_str)) = line.split_once(':') {
let scope = scope.trim();
let patterns_str = patterns_str.trim();
for pattern in patterns_str.split_whitespace() {
if let Some(prefix) = pattern.strip_suffix('/') {
// Pattern like "stratus/" - prefix match and trim suffix
match_arms.push(format!(
r#" n if n.starts_with("{prefix}") => ("{scope}", name.trim_start_matches("{prefix}")),
"#,
));
} else if let Some(prefix) = pattern.strip_suffix('*') {
// Pattern like "balance*" - prefix match
match_arms.push(format!(
r#" n if n.starts_with("{prefix}") => ("{scope}", name),
"#,
));
} else {
// Exact match
match_arms.push(format!(
r#" "{pattern}" => ("{scope}", name),
"#,
));
}
}
}
}
format!(
r#"// Auto-generated from client_scopes.txt
pub fn create_client_scope(name: &str) -> String {{
let (scope, name) = match name {{
{}
_ => ("other", name),
}};
format!("{{scope}}::{{name}}")
}}
"#,
match_arms.join("")
)
}
// -----------------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------------
struct InputFile {
_filename: PathBuf,
content: String,
}
/// Lists files in a path and ensure at least one file exists.
fn list_files(pattern: &'static str) -> Vec<InputFile> {
// list files
let filenames: Vec<PathBuf> = glob(pattern)
.expect("Listing files should not fail")
.map(|x| x.expect("Listing files should not fail"))
.collect();
// ensure at least one exists
if filenames.is_empty() {
panic!("No files found in \"{pattern}\"");
}
// read file contents
let mut files = Vec::with_capacity(filenames.len());
for filename in filenames {
files.push(InputFile {
content: fs::read_to_string(&filename).expect("Reading file should not fail"),
_filename: filename,
});
}
files
}
/// Writes generated module content to a file in the OUT_DIR.
fn write_module(file_basename: &'static str, file_content: String) {
let out_dir = env::var_os("OUT_DIR").map(PathBuf::from).expect("Compiler should set OUT_DIR");
let module_path = out_dir.join(file_basename);
if let Err(e) = fs::write(&module_path, file_content) {
panic!("Failed to write to file {module_path:?} | reason={e:?}");
}
}