From 2a403985792aba2721e0649671e21b0c2672aa19 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 7 Aug 2024 17:50:06 +0200 Subject: [PATCH 01/17] Support simpler capture and replay of ValidatorInputs There are several changes in this commit. 1. Move the `parse_inputs.rs` and `prepare.rs` files from the benchbin package to the prover. This enables the prover to ingest most of the information it needs from the `block_inputs_.json` file. 2. Add a `--json-inputs` flag to the `prover` bin which obviates several competing flags preferring to read the data from the json. 3. Write the json file to disk in the working directory before the arbitrator spawner writes the `run_prover.sh` file which is attempting to make a similar validaiton easy to reproduce. 4. Introduce a new `recordBlock` method to the tests suite which can be called once a block has been recorded to L1. 5. Wire the call to `recordBlock` into the `TestProgramStorage` to be sure to capture a block that actually uses a Stylus contract so that the prover can be shown to work with that block as well. 6. Enhance the `parse_inputs.rs` to know how to handle the `UserWasms` deserialization. To reproduce the failure state at this commit: 1. make clean && make all 2. go test -timeout 10m -tags challengetest -run ^TestProgramStorage$ github.com/offchainlabs/nitro/system_tests 3. Observe, there are now two new files in `ls system_tests/block_inputs_{2,5}.json` 4. target/bin/prover target/machines/latest/machine.wavm.br -b --json-inputs system_tests/block_inputs_5.json 5. The error is: ``` thread 'main' panicked at prover/src/machine.rs:690:58: unknown dictionary: TryFromPrimitiveError { number: 10 } ``` If you make changes to the rust code, you can quickly rebuild and install with: ``` cargo build --manifest-path arbitrator/Cargo.toml --release --bin prover && install arbitrator/target/release/prover target/bin/prover ``` --- arbitrator/Cargo.lock | 78 +---- arbitrator/arbutil/src/types.rs | 16 ++ arbitrator/bench/Cargo.toml | 1 - arbitrator/bench/src/bin.rs | 6 +- arbitrator/bench/src/lib.rs | 2 - arbitrator/prover/Cargo.toml | 2 +- arbitrator/prover/src/lib.rs | 2 + arbitrator/prover/src/main.rs | 167 ++++++----- .../{bench => prover}/src/parse_input.rs | 29 +- arbitrator/{bench => prover}/src/prepare.rs | 18 +- arbitrator/wasm-libraries/Cargo.lock | 266 +++++++++++++++--- staker/block_validator.go | 6 + staker/stateless_block_validator.go | 25 ++ system_tests/program_norace_test.go | 13 + system_tests/program_test.go | 8 +- validator/client/validation_client.go | 5 - validator/server_arb/validator_spawner.go | 6 + 17 files changed, 440 insertions(+), 210 deletions(-) delete mode 100644 arbitrator/bench/src/lib.rs rename arbitrator/{bench => prover}/src/parse_input.rs (74%) rename arbitrator/{bench => prover}/src/prepare.rs (73%) diff --git a/arbitrator/Cargo.lock b/arbitrator/Cargo.lock index 79a9117a31..2aa9864b08 100644 --- a/arbitrator/Cargo.lock +++ b/arbitrator/Cargo.lock @@ -215,7 +215,6 @@ dependencies = [ "prover", "serde", "serde_json", - "serde_with 3.9.0", ] [[package]] @@ -705,38 +704,14 @@ dependencies = [ "typenum", ] -[[package]] -name = "darling" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" -dependencies = [ - "darling_core 0.13.4", - "darling_macro 0.13.4", -] - [[package]] name = "darling" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ - "darling_core 0.20.10", - "darling_macro 0.20.10", -] - -[[package]] -name = "darling_core" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 1.0.109", + "darling_core", + "darling_macro", ] [[package]] @@ -753,24 +728,13 @@ dependencies = [ "syn 2.0.72", ] -[[package]] -name = "darling_macro" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" -dependencies = [ - "darling_core 0.13.4", - "quote", - "syn 1.0.109", -] - [[package]] name = "darling_macro" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ - "darling_core 0.20.10", + "darling_core", "quote", "syn 2.0.72", ] @@ -928,7 +892,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59c3b24c345d8c314966bdc1832f6c2635bfcce8e7cf363bd115987bba2ee242" dependencies = [ - "darling 0.20.10", + "darling", "proc-macro2", "quote", "syn 2.0.72", @@ -1750,7 +1714,7 @@ dependencies = [ "rustc-demangle", "serde", "serde_json", - "serde_with 1.14.0", + "serde_with", "sha2 0.9.9", "sha3 0.9.1", "smallvec", @@ -2073,16 +2037,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_with" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" -dependencies = [ - "serde", - "serde_with_macros 1.5.2", -] - [[package]] name = "serde_with" version = "3.9.0" @@ -2097,29 +2051,17 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "serde_with_macros 3.9.0", + "serde_with_macros", "time", ] -[[package]] -name = "serde_with_macros" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" -dependencies = [ - "darling 0.13.4", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "serde_with_macros" version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8fee4991ef4f274617a51ad4af30519438dacb2f56ac773b08a1922ff743350" dependencies = [ - "darling 0.20.10", + "darling", "proc-macro2", "quote", "syn 2.0.72", @@ -2226,12 +2168,6 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "strsim" version = "0.11.1" diff --git a/arbitrator/arbutil/src/types.rs b/arbitrator/arbutil/src/types.rs index 6cf1d6cdf7..207b8ab949 100644 --- a/arbitrator/arbutil/src/types.rs +++ b/arbitrator/arbutil/src/types.rs @@ -8,6 +8,7 @@ use std::{ borrow::Borrow, fmt, ops::{Deref, DerefMut}, + str::FromStr, }; // These values must be kept in sync with `arbutil/preimage_type.go`, @@ -83,6 +84,21 @@ impl From for Bytes32 { } } +impl FromStr for Bytes32 { + type Err = hex::FromHexError; + + fn from_str(s: &str) -> Result { + let trimmed = match s.strip_prefix("0x") { + Some(t) => t, + None => s, + }; + let bytes = hex::decode(trimmed)?; + let mut b = [0u8; 32]; + b.copy_from_slice(&bytes); + Ok(Self(b)) + } +} + impl TryFrom<&[u8]> for Bytes32 { type Error = std::array::TryFromSliceError; diff --git a/arbitrator/bench/Cargo.toml b/arbitrator/bench/Cargo.toml index 3ab5b99b08..284180dc46 100644 --- a/arbitrator/bench/Cargo.toml +++ b/arbitrator/bench/Cargo.toml @@ -20,7 +20,6 @@ clap = { version = "4.4.8", features = ["derive"] } gperftools = { version = "0.2.0", optional = true } serde = { version = "1.0.130", features = ["derive", "rc"] } serde_json = "1.0.67" -serde_with = { version = "3.8.1", features = ["base64"] } [features] counters = [] diff --git a/arbitrator/bench/src/bin.rs b/arbitrator/bench/src/bin.rs index f7e69f5373..60a7036e2b 100644 --- a/arbitrator/bench/src/bin.rs +++ b/arbitrator/bench/src/bin.rs @@ -1,6 +1,5 @@ use std::{path::PathBuf, time::Duration}; -use bench::prepare::*; use clap::Parser; use eyre::bail; @@ -10,11 +9,12 @@ use gperftools::profiler::PROFILER; #[cfg(feature = "heapprof")] use gperftools::heap_profiler::HEAP_PROFILER; -use prover::machine::MachineStatus; - #[cfg(feature = "counters")] use prover::{machine, memory, merkle}; +use prover::machine::MachineStatus; +use prover::prepare::prepare_machine; + #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { diff --git a/arbitrator/bench/src/lib.rs b/arbitrator/bench/src/lib.rs deleted file mode 100644 index 5f7c024094..0000000000 --- a/arbitrator/bench/src/lib.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod parse_input; -pub mod prepare; diff --git a/arbitrator/prover/Cargo.toml b/arbitrator/prover/Cargo.toml index 5475647765..da329b1cb5 100644 --- a/arbitrator/prover/Cargo.toml +++ b/arbitrator/prover/Cargo.toml @@ -19,10 +19,10 @@ num = "0.4" rustc-demangle = "0.1.21" serde = { version = "1.0.130", features = ["derive", "rc"] } serde_json = "1.0.67" +serde_with = { version = "3.8.1", features = ["base64"] } sha3 = "0.9.1" static_assertions = "1.1.0" structopt = "0.3.23" -serde_with = "1.12.1" parking_lot = "0.12.1" lazy_static.workspace = true itertools = "0.10.5" diff --git a/arbitrator/prover/src/lib.rs b/arbitrator/prover/src/lib.rs index 0f537478eb..08473c2598 100644 --- a/arbitrator/prover/src/lib.rs +++ b/arbitrator/prover/src/lib.rs @@ -11,6 +11,8 @@ pub mod machine; /// cbindgen:ignore pub mod memory; pub mod merkle; +pub mod parse_input; +pub mod prepare; mod print; pub mod programs; mod reinterpret; diff --git a/arbitrator/prover/src/main.rs b/arbitrator/prover/src/main.rs index dba32e0e72..002b693bd9 100644 --- a/arbitrator/prover/src/main.rs +++ b/arbitrator/prover/src/main.rs @@ -8,6 +8,7 @@ use eyre::{eyre, Context, Result}; use fnv::{FnvHashMap as HashMap, FnvHashSet as HashSet}; use prover::{ machine::{GlobalState, InboxIdentifier, Machine, MachineStatus, PreimageResolver, ProofInfo}, + prepare::prepare_machine, utils::{file_bytes, hash_preimage, CBytes}, wavm::Opcode, }; @@ -86,6 +87,10 @@ struct Opts { skip_until_host_io: bool, #[structopt(long)] max_steps: Option, + // JSON inputs are supercede any of the command-line inputs which could + // be specified in the JSON file. + #[structopt(long)] + json_inputs: Option, } fn file_with_stub_header(path: &Path, headerlength: usize) -> Result> { @@ -135,83 +140,8 @@ fn main() -> Result<()> { } } } - let mut inbox_contents = HashMap::default(); - let mut inbox_position = opts.inbox_position; - let mut delayed_position = opts.delayed_inbox_position; - let inbox_header_len; - let delayed_header_len; - if opts.inbox_add_stub_headers { - inbox_header_len = INBOX_HEADER_LEN; - delayed_header_len = DELAYED_HEADER_LEN + 1; - } else { - inbox_header_len = 0; - delayed_header_len = 0; - } - - for path in opts.inbox { - inbox_contents.insert( - (InboxIdentifier::Sequencer, inbox_position), - file_with_stub_header(&path, inbox_header_len)?, - ); - println!("read file {:?} to seq. inbox {}", &path, inbox_position); - inbox_position += 1; - } - for path in opts.delayed_inbox { - inbox_contents.insert( - (InboxIdentifier::Delayed, delayed_position), - file_with_stub_header(&path, delayed_header_len)?, - ); - delayed_position += 1; - } - let mut preimages: HashMap> = HashMap::default(); - if let Some(path) = opts.preimages { - let mut file = BufReader::new(File::open(path)?); - loop { - let mut ty_buf = [0u8; 1]; - match file.read_exact(&mut ty_buf) { - Ok(()) => {} - Err(e) if e.kind() == ErrorKind::UnexpectedEof => break, - Err(e) => return Err(e.into()), - } - let preimage_ty: PreimageType = ty_buf[0].try_into()?; - - let mut size_buf = [0u8; 8]; - file.read_exact(&mut size_buf)?; - let size = u64::from_le_bytes(size_buf) as usize; - let mut buf = vec![0u8; size]; - file.read_exact(&mut buf)?; - - let hash = hash_preimage(&buf, preimage_ty)?; - preimages - .entry(preimage_ty) - .or_default() - .insert(hash.into(), buf.as_slice().into()); - } - } - let preimage_resolver = - Arc::new(move |_, ty, hash| preimages.get(&ty).and_then(|m| m.get(&hash)).cloned()) - as PreimageResolver; - - let last_block_hash = decode_hex_arg(&opts.last_block_hash, "--last-block-hash")?; - let last_send_root = decode_hex_arg(&opts.last_send_root, "--last-send-root")?; - - let global_state = GlobalState { - u64_vals: [opts.inbox_position, opts.position_within_message], - bytes32_vals: [last_block_hash, last_send_root], - }; - - let mut mach = Machine::from_paths( - &opts.libraries, - &opts.binary, - true, - opts.allow_hostapi, - opts.debug_funcs, - true, - global_state, - inbox_contents, - preimage_resolver, - )?; + let mut mach = initialize_machine(&opts)?; for path in &opts.stylus_modules { let err = || eyre!("failed to read module at {}", path.to_string_lossy().red()); @@ -462,7 +392,6 @@ fn main() -> Result<()> { } } } - let opts_binary = opts.binary; let opts_libraries = opts.libraries; let format_pc = |module_num: usize, func_num: usize| -> (String, String) { @@ -543,3 +472,87 @@ fn main() -> Result<()> { } Ok(()) } + +fn initialize_machine(opts: &Opts) -> eyre::Result { + if let Some(json_inputs) = opts.json_inputs.clone() { + prepare_machine(json_inputs, opts.binary.clone()) + } else { + let mut inbox_contents = HashMap::default(); + let mut inbox_position = opts.inbox_position; + let mut delayed_position = opts.delayed_inbox_position; + let inbox_header_len; + let delayed_header_len; + if opts.inbox_add_stub_headers { + inbox_header_len = INBOX_HEADER_LEN; + delayed_header_len = DELAYED_HEADER_LEN + 1; + } else { + inbox_header_len = 0; + delayed_header_len = 0; + } + + for path in opts.inbox.clone() { + inbox_contents.insert( + (InboxIdentifier::Sequencer, inbox_position), + file_with_stub_header(&path, inbox_header_len)?, + ); + println!("read file {:?} to seq. inbox {}", &path, inbox_position); + inbox_position += 1; + } + for path in opts.delayed_inbox.clone() { + inbox_contents.insert( + (InboxIdentifier::Delayed, delayed_position), + file_with_stub_header(&path, delayed_header_len)?, + ); + delayed_position += 1; + } + + let mut preimages: HashMap> = HashMap::default(); + if let Some(path) = opts.preimages.clone() { + let mut file = BufReader::new(File::open(path)?); + loop { + let mut ty_buf = [0u8; 1]; + match file.read_exact(&mut ty_buf) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::UnexpectedEof => break, + Err(e) => return Err(e.into()), + } + let preimage_ty: PreimageType = ty_buf[0].try_into()?; + + let mut size_buf = [0u8; 8]; + file.read_exact(&mut size_buf)?; + let size = u64::from_le_bytes(size_buf) as usize; + let mut buf = vec![0u8; size]; + file.read_exact(&mut buf)?; + + let hash = hash_preimage(&buf, preimage_ty)?; + preimages + .entry(preimage_ty) + .or_default() + .insert(hash.into(), buf.as_slice().into()); + } + } + let preimage_resolver = + Arc::new(move |_, ty, hash| preimages.get(&ty).and_then(|m| m.get(&hash)).cloned()) + as PreimageResolver; + + let last_block_hash = decode_hex_arg(&opts.last_block_hash, "--last-block-hash")?; + let last_send_root = decode_hex_arg(&opts.last_send_root, "--last-send-root")?; + + let global_state = GlobalState { + u64_vals: [opts.inbox_position, opts.position_within_message], + bytes32_vals: [last_block_hash, last_send_root], + }; + + Machine::from_paths( + &opts.libraries, + &opts.binary, + true, + opts.allow_hostapi, + opts.debug_funcs, + true, + global_state, + inbox_contents, + preimage_resolver, + ) + } +} diff --git a/arbitrator/bench/src/parse_input.rs b/arbitrator/prover/src/parse_input.rs similarity index 74% rename from arbitrator/bench/src/parse_input.rs rename to arbitrator/prover/src/parse_input.rs index decc67372a..9af8652c96 100644 --- a/arbitrator/bench/src/parse_input.rs +++ b/arbitrator/prover/src/parse_input.rs @@ -35,6 +35,31 @@ mod prefixed_hex { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct PreimageMap(HashMap>); +#[derive(Debug)] +pub struct UserWasm { + data: Vec, +} + +impl UserWasm { + pub fn as_vec(&self) -> Vec { + self.data.clone() + } +} + +impl AsRef<[u8]> for UserWasm { + fn as_ref(&self) -> &[u8] { + &self.data + } +} + +/// The Vec is compressed using brotli, and must be decompressed before use. +impl From> for UserWasm { + fn from(data: Vec) -> Self { + let decompressed = brotli::decompress(&data, brotli::Dictionary::Empty).unwrap(); + Self { data: decompressed } + } +} + #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct BatchInfo { @@ -54,7 +79,7 @@ pub struct StartState { pub pos_in_batch: u64, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct FileData { pub id: u64, @@ -66,6 +91,8 @@ pub struct FileData { #[serde(with = "As::")] pub delayed_msg_b64: Vec, pub start_state: StartState, + #[serde(with = "As::>>")] + pub user_wasms: HashMap>>, } impl FileData { diff --git a/arbitrator/bench/src/prepare.rs b/arbitrator/prover/src/prepare.rs similarity index 73% rename from arbitrator/bench/src/prepare.rs rename to arbitrator/prover/src/prepare.rs index 741a7350ac..08bbd1476c 100644 --- a/arbitrator/bench/src/prepare.rs +++ b/arbitrator/prover/src/prepare.rs @@ -1,13 +1,13 @@ use arbutil::{Bytes32, PreimageType}; -use prover::machine::{argument_data_to_inbox, GlobalState, Machine}; -use prover::utils::CBytes; use std::collections::HashMap; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::sync::Arc; +use crate::machine::{argument_data_to_inbox, GlobalState, Machine, Module}; use crate::parse_input::*; +use crate::utils::CBytes; pub fn prepare_machine(preimages: PathBuf, machines: PathBuf) -> eyre::Result { let file = File::open(preimages)?; @@ -40,6 +40,20 @@ pub fn prepare_machine(preimages: PathBuf, machines: PathBuf) -> eyre::Result.json files when WriteToFile() is called. + BlockInputsFilePath string `koanf:"block-inputs-file-path"` memoryFreeLimit int } @@ -163,6 +166,7 @@ func BlockValidatorConfigAddOptions(prefix string, f *pflag.FlagSet) { f.Bool(prefix+".failure-is-fatal", DefaultBlockValidatorConfig.FailureIsFatal, "failing a validation is treated as a fatal error") BlockValidatorDangerousConfigAddOptions(prefix+".dangerous", f) f.String(prefix+".memory-free-limit", DefaultBlockValidatorConfig.MemoryFreeLimit, "minimum free-memory limit after reaching which the blockvalidator pauses validation. Enabled by default as 1GB, to disable provide empty string") + f.String(prefix+".block-inputs-file-path", DefaultBlockValidatorConfig.BlockInputsFilePath, "directory to write block validation inputs files") } func BlockValidatorDangerousConfigAddOptions(prefix string, f *pflag.FlagSet) { @@ -181,6 +185,7 @@ var DefaultBlockValidatorConfig = BlockValidatorConfig{ PendingUpgradeModuleRoot: "latest", FailureIsFatal: true, Dangerous: DefaultBlockValidatorDangerousConfig, + BlockInputsFilePath: "./target/validation_inputs", MemoryFreeLimit: "default", } @@ -196,6 +201,7 @@ var TestBlockValidatorConfig = BlockValidatorConfig{ PendingUpgradeModuleRoot: "latest", FailureIsFatal: true, Dangerous: DefaultBlockValidatorDangerousConfig, + BlockInputsFilePath: "./target/validation_inputs", MemoryFreeLimit: "default", } diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index c8842aedc4..c2704b89ab 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -463,6 +463,31 @@ func (v *StatelessBlockValidator) ValidateResult( return true, &entry.End, nil } +func (v *StatelessBlockValidator) RecordValidationInput(ctx context.Context, pos arbutil.MessageIndex, moduleRoot common.Hash) error { + entry, err := v.CreateReadyValidationEntry(ctx, pos) + if err != nil { + return err + } + found := false + for _, spawner := range v.execSpawners { + if validator.SpawnerSupportsModule(spawner, moduleRoot) { + found = true + input, err := entry.ToInput(spawner.StylusArchs()) + if err != nil { + return err + } + _, err = spawner.WriteToFile(input, entry.End, moduleRoot).Await(ctx) + if err != nil { + return err + } + } + } + if !found { + return fmt.Errorf("validation with WasmModuleRoot %v not supported by node", moduleRoot) + } + return nil +} + func (v *StatelessBlockValidator) OverrideRecorder(t *testing.T, recorder execution.ExecutionRecorder) { v.recorder = recorder } diff --git a/system_tests/program_norace_test.go b/system_tests/program_norace_test.go index 56b2046716..2ccd77c5b5 100644 --- a/system_tests/program_norace_test.go +++ b/system_tests/program_norace_test.go @@ -104,6 +104,19 @@ func validateBlockRange( } } +// recordBlock writes a json file with all of the data needed to validate a block. +// +// This can be used as an input to the arbitrator prover to validate a block. +func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { + t.Helper() + ctx := builder.ctx + wasmModuleRoot := currentRootModule(t) + inboxPos := arbutil.MessageIndex(block) + if err := builder.L2.ConsensusNode.StatelessBlockValidator.RecordValidationInput(ctx, inboxPos, wasmModuleRoot); err != nil { + Fatal(t, "failed to record block", block, err) + } +} + func TestProgramEvmData(t *testing.T) { t.Parallel() testEvmData(t, true) diff --git a/system_tests/program_test.go b/system_tests/program_test.go index 5fa5db95c2..1327c67ab7 100644 --- a/system_tests/program_test.go +++ b/system_tests/program_test.go @@ -368,7 +368,7 @@ func errorTest(t *testing.T, jit bool) { func TestProgramStorage(t *testing.T) { t.Parallel() - storageTest(t, true) + storageTest(t, false) } func storageTest(t *testing.T, jit bool) { @@ -390,10 +390,13 @@ func storageTest(t *testing.T, jit bool) { key := testhelpers.RandomHash() value := testhelpers.RandomHash() tx := l2info.PrepareTxTo("Owner", &programAddress, l2info.TransferGas, nil, argsForStorageWrite(key, value)) - ensure(tx, l2client.SendTransaction(ctx, tx)) + receipt := ensure(tx, l2client.SendTransaction(ctx, tx)) + assertStorageAt(t, ctx, l2client, programAddress, key, value) validateBlocks(t, 2, jit, builder) + recordBlock(t, 2, builder) + recordBlock(t, receipt.BlockNumber.Uint64(), builder) } func TestProgramTransientStorage(t *testing.T) { @@ -1143,6 +1146,7 @@ func testActivateFails(t *testing.T, jit bool) { }) validateBlockRange(t, []uint64{blockToValidate}, jit, builder) + recordBlock(t, blockToValidate, builder) } func TestProgramSdkStorage(t *testing.T) { diff --git a/validator/client/validation_client.go b/validator/client/validation_client.go index d6743b109e..91b0c71a79 100644 --- a/validator/client/validation_client.go +++ b/validator/client/validation_client.go @@ -181,11 +181,6 @@ func (c *ExecutionClient) LatestWasmModuleRoot() containers.PromiseInterface[com func (c *ExecutionClient) WriteToFile(input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { jsonInput := server_api.ValidationInputToJson(input) - if err := jsonInput.WriteToFile(); err != nil { - return stopwaiter.LaunchPromiseThread[struct{}](c, func(ctx context.Context) (struct{}, error) { - return struct{}{}, err - }) - } return stopwaiter.LaunchPromiseThread[struct{}](c, func(ctx context.Context) (struct{}, error) { err := c.client.CallContext(ctx, nil, server_api.Namespace+"_writeToFile", jsonInput, expOut, moduleRoot) return struct{}{}, err diff --git a/validator/server_arb/validator_spawner.go b/validator/server_arb/validator_spawner.go index 1d4126dc7c..43ad7930b6 100644 --- a/validator/server_arb/validator_spawner.go +++ b/validator/server_arb/validator_spawner.go @@ -17,6 +17,7 @@ import ( "github.com/offchainlabs/nitro/util/containers" "github.com/offchainlabs/nitro/util/stopwaiter" "github.com/offchainlabs/nitro/validator" + "github.com/offchainlabs/nitro/validator/server_api" "github.com/offchainlabs/nitro/validator/server_common" "github.com/offchainlabs/nitro/validator/valnode/redis" @@ -187,6 +188,7 @@ func (v *ArbitratorSpawner) execute( } func (v *ArbitratorSpawner) Launch(entry *validator.ValidationInput, moduleRoot common.Hash) validator.ValidationRun { + println("LAUCHING ARBITRATOR VALIDATION") v.count.Add(1) promise := stopwaiter.LaunchPromiseThread[validator.GoGlobalState](v, func(ctx context.Context) (validator.GoGlobalState, error) { defer v.count.Add(-1) @@ -207,6 +209,10 @@ var launchTime = time.Now().Format("2006_01_02__15_04") //nolint:gosec func (v *ArbitratorSpawner) writeToFile(ctx context.Context, input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) error { + jsonInput := server_api.ValidationInputToJson(input) + if err := jsonInput.WriteToFile(); err != nil { + return err + } outDirPath := filepath.Join(v.locator.RootPath(), v.config().OutputPath, launchTime, fmt.Sprintf("block_%d", input.Id)) err := os.MkdirAll(outDirPath, 0755) if err != nil { From 7113c52fe3fc3d4b9843466d0cc7a33df906e99f Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 7 Aug 2024 19:10:52 +0200 Subject: [PATCH 02/17] Fix the deserialization of the UserWasm data This change also: 1. Documents the `parse_inputs.rs` file in an attempt to give context to why the deserialization is special. 2. Hardcodes the architecture to `wasm` when recording ValidationInputs for use with the prover. Previously, the `jit` validator would use the go system architecture, and the `arbitrator` validator would use `wavm`. 3. Switches the `TestStorageProgram` test back to the `jit` validator. Note: As of this commit, there is still a small problem that when running the validator using the json inputs, it does not come up with the same end has as `entry.End.Hash`. --- arbitrator/prover/src/parse_input.rs | 51 ++++++++++++++++------------ arbitrator/prover/src/prepare.rs | 18 ++++------ staker/stateless_block_validator.go | 3 +- system_tests/program_test.go | 2 +- 4 files changed, 40 insertions(+), 34 deletions(-) diff --git a/arbitrator/prover/src/parse_input.rs b/arbitrator/prover/src/parse_input.rs index 9af8652c96..fa7adb4c41 100644 --- a/arbitrator/prover/src/parse_input.rs +++ b/arbitrator/prover/src/parse_input.rs @@ -1,5 +1,5 @@ use arbutil::Bytes32; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use serde_json; use serde_with::base64::Base64; use serde_with::As; @@ -9,15 +9,14 @@ use std::{ io::{self, BufRead}, }; +/// prefixed_hex deserializes hex strings which are prefixed with `0x` +/// +/// The default hex deserializer does not support prefixed hex strings. +/// +/// It is an error to use this deserializer on a string that does not +/// begin with `0x`. mod prefixed_hex { - use serde::{self, Deserialize, Deserializer, Serializer}; - - pub fn serialize(bytes: &Vec, serializer: S) -> Result - where - S: Serializer, - { - serializer.serialize_str(&format!("0x{}", hex::encode(bytes))) - } + use serde::{self, Deserialize, Deserializer}; pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where @@ -32,23 +31,25 @@ mod prefixed_hex { } } -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct PreimageMap(HashMap>); - #[derive(Debug)] -pub struct UserWasm { - data: Vec, -} +pub struct UserWasm(Vec); +/// UserWasm is a wrapper around Vec +/// +/// It is useful for decompressing a brotli-compressed wasm module. +/// +/// Note: The wrapped Vec is already Base64 decoded before +/// from(Vec) is called by serde. impl UserWasm { + /// as_vec returns the decompressed wasm module as a Vec pub fn as_vec(&self) -> Vec { - self.data.clone() + self.0.clone() } } impl AsRef<[u8]> for UserWasm { fn as_ref(&self) -> &[u8] { - &self.data + &self.0 } } @@ -56,11 +57,11 @@ impl AsRef<[u8]> for UserWasm { impl From> for UserWasm { fn from(data: Vec) -> Self { let decompressed = brotli::decompress(&data, brotli::Dictionary::Empty).unwrap(); - Self { data: decompressed } + Self(decompressed) } } -#[derive(Debug, Clone, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct BatchInfo { pub number: u64, @@ -68,7 +69,7 @@ pub struct BatchInfo { pub data_b64: Vec, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct StartState { #[serde(with = "prefixed_hex")] @@ -79,6 +80,14 @@ pub struct StartState { pub pos_in_batch: u64, } +/// FileData is the deserialized form of the input JSON file. +/// +/// The go JSON library in json.go uses some custom serialization and +/// compression logic that needs to be reversed when deserializing the +/// JSON in rust. +/// +/// Note: It is important to change this file whenever the go JSON +/// serialization changes. #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct FileData { @@ -92,7 +101,7 @@ pub struct FileData { pub delayed_msg_b64: Vec, pub start_state: StartState, #[serde(with = "As::>>")] - pub user_wasms: HashMap>>, + pub user_wasms: HashMap>, } impl FileData { diff --git a/arbitrator/prover/src/prepare.rs b/arbitrator/prover/src/prepare.rs index 08bbd1476c..ecfb517735 100644 --- a/arbitrator/prover/src/prepare.rs +++ b/arbitrator/prover/src/prepare.rs @@ -5,7 +5,7 @@ use std::io::BufReader; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::machine::{argument_data_to_inbox, GlobalState, Machine, Module}; +use crate::machine::{argument_data_to_inbox, GlobalState, Machine}; use crate::parse_input::*; use crate::utils::CBytes; @@ -40,17 +40,13 @@ pub fn prepare_machine(preimages: PathBuf, machines: PathBuf) -> eyre::Result Date: Wed, 7 Aug 2024 21:11:24 +0200 Subject: [PATCH 03/17] Print the End global state This makes it easier to visually confirm the expected outcome if a human is looking at the output of the prover and knows what the expected end global state should be. --- arbitrator/prover/src/main.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arbitrator/prover/src/main.rs b/arbitrator/prover/src/main.rs index 002b693bd9..8c90ee44a4 100644 --- a/arbitrator/prover/src/main.rs +++ b/arbitrator/prover/src/main.rs @@ -344,6 +344,13 @@ fn main() -> Result<()> { }); } + println!( + "End GlobalState:\n BlockHash: {:?}\n SendRoot: {:?}\n Batch: {}\n PosInBatch: {}", + mach.get_global_state().bytes32_vals[0], + mach.get_global_state().bytes32_vals[1], + mach.get_global_state().u64_vals[0], + mach.get_global_state().u64_vals[1] + ); println!("End machine status: {:?}", mach.get_status()); println!("End machine hash: {}", mach.hash()); println!("End machine stack: {:?}", mach.get_data_stack()); From 3eed9bf6ec46cd81f6011778cef2ff03ba2040de Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 7 Aug 2024 21:15:47 +0200 Subject: [PATCH 04/17] Remove two calls to recordBlock The thrid one is left around as an example of how to use the new method. --- system_tests/program_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/system_tests/program_test.go b/system_tests/program_test.go index a7eb94733d..29c5099912 100644 --- a/system_tests/program_test.go +++ b/system_tests/program_test.go @@ -395,7 +395,8 @@ func storageTest(t *testing.T, jit bool) { assertStorageAt(t, ctx, l2client, programAddress, key, value) validateBlocks(t, 2, jit, builder) - recordBlock(t, 2, builder) + // Captures a block_input_.json file for the block that included the + // storage write transaction. recordBlock(t, receipt.BlockNumber.Uint64(), builder) } @@ -1146,7 +1147,6 @@ func testActivateFails(t *testing.T, jit bool) { }) validateBlockRange(t, []uint64{blockToValidate}, jit, builder) - recordBlock(t, blockToValidate, builder) } func TestProgramSdkStorage(t *testing.T) { From ec7a386cd6364c4dcced822e452e74de3b49c7c5 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Thu, 8 Aug 2024 11:49:14 +0200 Subject: [PATCH 05/17] A few small changes bundled together in here. 1. Remove the part of the writeToFile method on ArbitratorSpawner which was writing the bash scripts. (TODO: Write the block_inputs_.json files somewhere better.) 2. Drop the expOut from the WriteToFile signature since none of the implementations need it any more. 3. Rename some unused function arguments to "_". --- arbitrator/bench/Cargo.toml | 4 - staker/block_validator.go | 2 +- staker/stateless_block_validator.go | 2 +- system_tests/validation_mock_test.go | 2 +- validator/client/validation_client.go | 4 +- validator/interface.go | 2 +- validator/server_arb/validator_spawner.go | 133 +--------------------- validator/server_jit/jit_machine.go | 2 +- validator/valnode/validation_api.go | 4 +- 9 files changed, 13 insertions(+), 142 deletions(-) diff --git a/arbitrator/bench/Cargo.toml b/arbitrator/bench/Cargo.toml index 284180dc46..74b948aca8 100644 --- a/arbitrator/bench/Cargo.toml +++ b/arbitrator/bench/Cargo.toml @@ -3,10 +3,6 @@ name = "bench" version = "0.1.0" edition = "2021" -[lib] -name = "bench" -path = "src/lib.rs" - [[bin]] name = "benchbin" path = "src/bin.rs" diff --git a/staker/block_validator.go b/staker/block_validator.go index 8d25ddf3c9..5d37cb17bd 100644 --- a/staker/block_validator.go +++ b/staker/block_validator.go @@ -496,7 +496,7 @@ func (v *BlockValidator) writeToFile(validationEntry *validationEntry, moduleRoo } for _, spawner := range v.execSpawners { if validator.SpawnerSupportsModule(spawner, moduleRoot) { - _, err = spawner.WriteToFile(input, validationEntry.End, moduleRoot).Await(v.GetContext()) + _, err = spawner.WriteToFile(input, moduleRoot).Await(v.GetContext()) return err } } diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index d19b1e2d1a..d97b02d340 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -477,7 +477,7 @@ func (v *StatelessBlockValidator) RecordValidationInput(ctx context.Context, pos if err != nil { return err } - _, err = spawner.WriteToFile(input, entry.End, moduleRoot).Await(ctx) + _, err = spawner.WriteToFile(input, moduleRoot).Await(ctx) if err != nil { return err } diff --git a/system_tests/validation_mock_test.go b/system_tests/validation_mock_test.go index 2c6321d009..48328d778e 100644 --- a/system_tests/validation_mock_test.go +++ b/system_tests/validation_mock_test.go @@ -95,7 +95,7 @@ func (s *mockSpawner) LatestWasmModuleRoot() containers.PromiseInterface[common. return containers.NewReadyPromise[common.Hash](mockWasmModuleRoots[0], nil) } -func (s *mockSpawner) WriteToFile(input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { +func (s *mockSpawner) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { return containers.NewReadyPromise[struct{}](struct{}{}, nil) } diff --git a/validator/client/validation_client.go b/validator/client/validation_client.go index 91b0c71a79..5a50a9525c 100644 --- a/validator/client/validation_client.go +++ b/validator/client/validation_client.go @@ -179,10 +179,10 @@ func (c *ExecutionClient) LatestWasmModuleRoot() containers.PromiseInterface[com }) } -func (c *ExecutionClient) WriteToFile(input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { +func (c *ExecutionClient) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { jsonInput := server_api.ValidationInputToJson(input) return stopwaiter.LaunchPromiseThread[struct{}](c, func(ctx context.Context) (struct{}, error) { - err := c.client.CallContext(ctx, nil, server_api.Namespace+"_writeToFile", jsonInput, expOut, moduleRoot) + err := c.client.CallContext(ctx, nil, server_api.Namespace+"_writeToFile", jsonInput, moduleRoot) return struct{}{}, err }) } diff --git a/validator/interface.go b/validator/interface.go index 80aa2c1fcc..96d3d2da18 100644 --- a/validator/interface.go +++ b/validator/interface.go @@ -26,7 +26,7 @@ type ExecutionSpawner interface { ValidationSpawner CreateExecutionRun(wasmModuleRoot common.Hash, input *ValidationInput) containers.PromiseInterface[ExecutionRun] LatestWasmModuleRoot() containers.PromiseInterface[common.Hash] - WriteToFile(input *ValidationInput, expOut GoGlobalState, moduleRoot common.Hash) containers.PromiseInterface[struct{}] + WriteToFile(input *ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] } type ExecutionRun interface { diff --git a/validator/server_arb/validator_spawner.go b/validator/server_arb/validator_spawner.go index 43ad7930b6..8df390514b 100644 --- a/validator/server_arb/validator_spawner.go +++ b/validator/server_arb/validator_spawner.go @@ -2,11 +2,8 @@ package server_arb import ( "context" - "encoding/binary" "errors" "fmt" - "os" - "path/filepath" "runtime" "sync/atomic" "time" @@ -97,7 +94,7 @@ func (s *ArbitratorSpawner) Name() string { return "arbitrator" } -func (v *ArbitratorSpawner) loadEntryToMachine(ctx context.Context, entry *validator.ValidationInput, mach *ArbitratorMachine) error { +func (v *ArbitratorSpawner) loadEntryToMachine(_ context.Context, entry *validator.ValidationInput, mach *ArbitratorMachine) error { resolver := func(ty arbutil.PreimageType, hash common.Hash) ([]byte, error) { // Check if it's a known preimage if preimage, ok := entry.Preimages[ty][hash]; ok { @@ -205,139 +202,17 @@ func (v *ArbitratorSpawner) Room() int { return avail } -var launchTime = time.Now().Format("2006_01_02__15_04") - -//nolint:gosec -func (v *ArbitratorSpawner) writeToFile(ctx context.Context, input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) error { +func (v *ArbitratorSpawner) writeToFile(_ context.Context, input *validator.ValidationInput, _ common.Hash) error { jsonInput := server_api.ValidationInputToJson(input) if err := jsonInput.WriteToFile(); err != nil { return err } - outDirPath := filepath.Join(v.locator.RootPath(), v.config().OutputPath, launchTime, fmt.Sprintf("block_%d", input.Id)) - err := os.MkdirAll(outDirPath, 0755) - if err != nil { - return err - } - if ctx.Err() != nil { - return ctx.Err() - } - - rootPathAssign := "" - if executable, err := os.Executable(); err == nil { - rootPathAssign = "ROOTPATH=\"" + filepath.Dir(executable) + "\"\n" - } - cmdFile, err := os.OpenFile(filepath.Join(outDirPath, "run-prover.sh"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) - if err != nil { - return err - } - defer cmdFile.Close() - _, err = cmdFile.WriteString("#!/bin/bash\n" + - fmt.Sprintf("# expected output: batch %d, postion %d, hash %s\n", expOut.Batch, expOut.PosInBatch, expOut.BlockHash) + - "MACHPATH=\"" + v.locator.GetMachinePath(moduleRoot) + "\"\n" + - rootPathAssign + - "if (( $# > 1 )); then\n" + - " if [[ $1 == \"-m\" ]]; then\n" + - " MACHPATH=$2\n" + - " shift\n" + - " shift\n" + - " fi\n" + - "fi\n" + - "${ROOTPATH}/bin/prover ${MACHPATH}/replay.wasm") - if err != nil { - return err - } - if ctx.Err() != nil { - return ctx.Err() - } - - libraries := []string{"soft-float.wasm", "wasi_stub.wasm", "go_stub.wasm", "host_io.wasm", "brotli.wasm"} - for _, module := range libraries { - _, err = cmdFile.WriteString(" -l " + "${MACHPATH}/" + module) - if err != nil { - return err - } - } - _, err = cmdFile.WriteString(fmt.Sprintf(" --inbox-position %d --position-within-message %d --last-block-hash %s", input.StartState.Batch, input.StartState.PosInBatch, input.StartState.BlockHash)) - if err != nil { - return err - } - - for _, msg := range input.BatchInfo { - if ctx.Err() != nil { - return ctx.Err() - } - sequencerFileName := fmt.Sprintf("sequencer_%d.bin", msg.Number) - err = os.WriteFile(filepath.Join(outDirPath, sequencerFileName), msg.Data, 0644) - if err != nil { - return err - } - _, err = cmdFile.WriteString(" --inbox " + sequencerFileName) - if err != nil { - return err - } - } - - preimageFile, err := os.Create(filepath.Join(outDirPath, "preimages.bin")) - if err != nil { - return err - } - defer preimageFile.Close() - for ty, preimages := range input.Preimages { - _, err = preimageFile.Write([]byte{byte(ty)}) - if err != nil { - return err - } - for _, data := range preimages { - if ctx.Err() != nil { - return ctx.Err() - } - lenbytes := make([]byte, 8) - binary.LittleEndian.PutUint64(lenbytes, uint64(len(data))) - _, err := preimageFile.Write(lenbytes) - if err != nil { - return err - } - _, err = preimageFile.Write(data) - if err != nil { - return err - } - } - } - - _, err = cmdFile.WriteString(" --preimages preimages.bin") - if err != nil { - return err - } - - if input.HasDelayedMsg { - if ctx.Err() != nil { - return ctx.Err() - } - _, err = cmdFile.WriteString(fmt.Sprintf(" --delayed-inbox-position %d", input.DelayedMsgNr)) - if err != nil { - return err - } - filename := fmt.Sprintf("delayed_%d.bin", input.DelayedMsgNr) - err = os.WriteFile(filepath.Join(outDirPath, filename), input.DelayedMsg, 0644) - if err != nil { - return err - } - _, err = cmdFile.WriteString(fmt.Sprintf(" --delayed-inbox %s", filename)) - if err != nil { - return err - } - } - - _, err = cmdFile.WriteString(" \"$@\"\n") - if err != nil { - return err - } return nil } -func (v *ArbitratorSpawner) WriteToFile(input *validator.ValidationInput, expOut validator.GoGlobalState, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { +func (v *ArbitratorSpawner) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { return stopwaiter.LaunchPromiseThread[struct{}](v, func(ctx context.Context) (struct{}, error) { - err := v.writeToFile(ctx, input, expOut, moduleRoot) + err := v.writeToFile(ctx, input, moduleRoot) return struct{}{}, err }) } diff --git a/validator/server_jit/jit_machine.go b/validator/server_jit/jit_machine.go index e4fb840cbb..5ba011727f 100644 --- a/validator/server_jit/jit_machine.go +++ b/validator/server_jit/jit_machine.go @@ -31,7 +31,7 @@ type JitMachine struct { wasmMemoryUsageLimit int } -func createJitMachine(jitBinary string, binaryPath string, cranelift bool, wasmMemoryUsageLimit int, moduleRoot common.Hash, fatalErrChan chan error) (*JitMachine, error) { +func createJitMachine(jitBinary string, binaryPath string, cranelift bool, wasmMemoryUsageLimit int, _ common.Hash, fatalErrChan chan error) (*JitMachine, error) { invocation := []string{"--binary", binaryPath, "--forks"} if cranelift { invocation = append(invocation, "--cranelift") diff --git a/validator/valnode/validation_api.go b/validator/valnode/validation_api.go index 6245ffc5e3..6561e7f0fd 100644 --- a/validator/valnode/validation_api.go +++ b/validator/valnode/validation_api.go @@ -117,12 +117,12 @@ func (a *ExecServerAPI) Start(ctx_in context.Context) { a.CallIteratively(a.removeOldRuns) } -func (a *ExecServerAPI) WriteToFile(ctx context.Context, jsonInput *server_api.InputJSON, expOut validator.GoGlobalState, moduleRoot common.Hash) error { +func (a *ExecServerAPI) WriteToFile(ctx context.Context, jsonInput *server_api.InputJSON, moduleRoot common.Hash) error { input, err := server_api.ValidationInputFromJson(jsonInput) if err != nil { return err } - _, err = a.execSpawner.WriteToFile(input, expOut, moduleRoot).Await(ctx) + _, err = a.execSpawner.WriteToFile(input, moduleRoot).Await(ctx) return err } From e9bf293ea30261981efe6d565dfd40457214530c Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Tue, 20 Aug 2024 10:42:26 -0400 Subject: [PATCH 06/17] Use the strongly-typed rawdb.Target --- staker/stateless_block_validator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index 56e41a9c20..0a979ce96b 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -473,7 +473,7 @@ func (v *StatelessBlockValidator) RecordValidationInput(ctx context.Context, pos if validator.SpawnerSupportsModule(spawner, moduleRoot) { found = true // Hardcoded to use wavm so that it can be read by the prover. - input, err := entry.ToInput([]string{"wavm"}) + input, err := entry.ToInput([]rawdb.Target{rawdb.TargetWavm}) if err != nil { return err } From 39cd0a7a89159680b63fc07d30fa4831c55895b3 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Thu, 22 Aug 2024 11:04:16 -0400 Subject: [PATCH 07/17] Finish wiring the json file writing everywhere. At this point the location of the output file is hardcoded to be in the `$HOME/.arbitrum` directory. Hopefully, this will be okay. --- arbnode/api.go | 16 ++++++++++++++ staker/block_validator.go | 15 ++++++------- staker/stateless_block_validator.go | 27 ++++++----------------- system_tests/common_test.go | 17 ++++++++++++++ system_tests/program_norace_test.go | 13 ----------- system_tests/validation_mock_test.go | 4 ---- validator/client/validation_client.go | 8 ------- validator/interface.go | 1 - validator/server_api/json.go | 24 ++++++++++++++++++-- validator/server_arb/validator_spawner.go | 16 -------------- validator/valnode/validation_api.go | 9 -------- 11 files changed, 69 insertions(+), 81 deletions(-) diff --git a/arbnode/api.go b/arbnode/api.go index 228ad51cf8..27d3509d59 100644 --- a/arbnode/api.go +++ b/arbnode/api.go @@ -10,6 +10,7 @@ import ( "github.com/offchainlabs/nitro/arbutil" "github.com/offchainlabs/nitro/staker" "github.com/offchainlabs/nitro/validator" + "github.com/offchainlabs/nitro/validator/server_api" ) type BlockValidatorAPI struct { @@ -54,3 +55,18 @@ func (a *BlockValidatorDebugAPI) ValidateMessageNumber( result.Valid = valid return result, err } + +func (a *BlockValidatorDebugAPI) ValidationInputsAt(ctx context.Context, msgNum hexutil.Uint64, moduleRootOptional *common.Hash, +) (server_api.InputJSON, error) { + var moduleRoot common.Hash + if moduleRootOptional != nil { + moduleRoot = *moduleRootOptional + } else { + var err error + moduleRoot, err = a.val.GetLatestWasmModuleRoot(ctx) + if err != nil { + return server_api.InputJSON{}, fmt.Errorf("no latest WasmModuleRoot configured, must provide parameter: %w", err) + } + } + return a.val.ValidationInputsAt(ctx, arbutil.MessageIndex(msgNum), moduleRoot) +} diff --git a/staker/block_validator.go b/staker/block_validator.go index 4be65c8d1d..f91d91d2e5 100644 --- a/staker/block_validator.go +++ b/staker/block_validator.go @@ -29,6 +29,7 @@ import ( "github.com/offchainlabs/nitro/util/stopwaiter" "github.com/offchainlabs/nitro/validator" "github.com/offchainlabs/nitro/validator/client/redis" + "github.com/offchainlabs/nitro/validator/server_api" "github.com/spf13/pflag" ) @@ -504,18 +505,16 @@ func (v *BlockValidator) sendRecord(s *validationStatus) error { } //nolint:gosec -func (v *BlockValidator) writeToFile(validationEntry *validationEntry, moduleRoot common.Hash) error { +func (v *BlockValidator) writeToFile(validationEntry *validationEntry) error { input, err := validationEntry.ToInput([]rawdb.Target{rawdb.TargetWavm}) if err != nil { return err } - for _, spawner := range v.execSpawners { - if validator.SpawnerSupportsModule(spawner, moduleRoot) { - _, err = spawner.WriteToFile(input, moduleRoot).Await(v.GetContext()) - return err - } + inputJson := server_api.ValidationInputToJson(input) + if err := inputJson.WriteToFile("BlockValidator"); err != nil { + return err } - return errors.New("did not find exec spawner for wasmModuleRoot") + return nil } func (v *BlockValidator) SetCurrentWasmModuleRoot(hash common.Hash) error { @@ -783,7 +782,7 @@ validationsLoop: runEnd, err := run.Current() if err == nil && runEnd != validationStatus.Entry.End { err = fmt.Errorf("validation failed: expected %v got %v", validationStatus.Entry.End, runEnd) - writeErr := v.writeToFile(validationStatus.Entry, run.WasmModuleRoot()) + writeErr := v.writeToFile(validationStatus.Entry) if writeErr != nil { log.Warn("failed to write debug results file", "err", writeErr) } diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index 0a979ce96b..bb96e6f8c2 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -24,6 +24,7 @@ import ( "github.com/offchainlabs/nitro/util/rpcclient" "github.com/offchainlabs/nitro/validator" "github.com/offchainlabs/nitro/validator/client/redis" + "github.com/offchainlabs/nitro/validator/server_api" validatorclient "github.com/offchainlabs/nitro/validator/client" ) @@ -463,30 +464,16 @@ func (v *StatelessBlockValidator) ValidateResult( return true, &entry.End, nil } -func (v *StatelessBlockValidator) RecordValidationInput(ctx context.Context, pos arbutil.MessageIndex, moduleRoot common.Hash) error { +func (v *StatelessBlockValidator) ValidationInputsAt(ctx context.Context, pos arbutil.MessageIndex, moduleRoot common.Hash) (server_api.InputJSON, error) { entry, err := v.CreateReadyValidationEntry(ctx, pos) if err != nil { - return err + return server_api.InputJSON{}, err } - found := false - for _, spawner := range v.execSpawners { - if validator.SpawnerSupportsModule(spawner, moduleRoot) { - found = true - // Hardcoded to use wavm so that it can be read by the prover. - input, err := entry.ToInput([]rawdb.Target{rawdb.TargetWavm}) - if err != nil { - return err - } - _, err = spawner.WriteToFile(input, moduleRoot).Await(ctx) - if err != nil { - return err - } - } - } - if !found { - return fmt.Errorf("validation with WasmModuleRoot %v not supported by node", moduleRoot) + input, err := entry.ToInput([]rawdb.Target{rawdb.TargetWavm}) + if err != nil { + return server_api.InputJSON{}, err } - return nil + return *server_api.ValidationInputToJson(input), nil } func (v *StatelessBlockValidator) OverrideRecorder(t *testing.T, recorder execution.ExecutionRecorder) { diff --git a/system_tests/common_test.go b/system_tests/common_test.go index 6e7375a921..53d17c762c 100644 --- a/system_tests/common_test.go +++ b/system_tests/common_test.go @@ -1459,6 +1459,23 @@ func logParser[T any](t *testing.T, source string, name string) func(*types.Log) } } +// recordBlock writes a json file with all of the data needed to validate a block. +// +// This can be used as an input to the arbitrator prover to validate a block. +func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { + t.Helper() + ctx := builder.ctx + wasmModuleRoot := currentRootModule(t) + inboxPos := arbutil.MessageIndex(block) + inputJson, err := builder.L2.ConsensusNode.StatelessBlockValidator.ValidationInputsAt(ctx, inboxPos, wasmModuleRoot) + if err != nil { + Fatal(t, "failed to get validation inputs", block, err) + } + if err := inputJson.WriteToFile(t.Name()); err != nil { + Fatal(t, "failed to write validation inputs", block, err) + } +} + func populateMachineDir(t *testing.T, cr *github.ConsensusRelease) string { baseDir := t.TempDir() machineDir := baseDir + "/machines" diff --git a/system_tests/program_norace_test.go b/system_tests/program_norace_test.go index 2ccd77c5b5..56b2046716 100644 --- a/system_tests/program_norace_test.go +++ b/system_tests/program_norace_test.go @@ -104,19 +104,6 @@ func validateBlockRange( } } -// recordBlock writes a json file with all of the data needed to validate a block. -// -// This can be used as an input to the arbitrator prover to validate a block. -func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { - t.Helper() - ctx := builder.ctx - wasmModuleRoot := currentRootModule(t) - inboxPos := arbutil.MessageIndex(block) - if err := builder.L2.ConsensusNode.StatelessBlockValidator.RecordValidationInput(ctx, inboxPos, wasmModuleRoot); err != nil { - Fatal(t, "failed to record block", block, err) - } -} - func TestProgramEvmData(t *testing.T) { t.Parallel() testEvmData(t, true) diff --git a/system_tests/validation_mock_test.go b/system_tests/validation_mock_test.go index b854ec1cb3..ddf0f4c3aa 100644 --- a/system_tests/validation_mock_test.go +++ b/system_tests/validation_mock_test.go @@ -96,10 +96,6 @@ func (s *mockSpawner) LatestWasmModuleRoot() containers.PromiseInterface[common. return containers.NewReadyPromise[common.Hash](mockWasmModuleRoots[0], nil) } -func (s *mockSpawner) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { - return containers.NewReadyPromise[struct{}](struct{}{}, nil) -} - type mockValRun struct { containers.Promise[validator.GoGlobalState] root common.Hash diff --git a/validator/client/validation_client.go b/validator/client/validation_client.go index 01e0684d70..8372731e06 100644 --- a/validator/client/validation_client.go +++ b/validator/client/validation_client.go @@ -186,14 +186,6 @@ func (c *ExecutionClient) LatestWasmModuleRoot() containers.PromiseInterface[com }) } -func (c *ExecutionClient) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { - jsonInput := server_api.ValidationInputToJson(input) - return stopwaiter.LaunchPromiseThread[struct{}](c, func(ctx context.Context) (struct{}, error) { - err := c.client.CallContext(ctx, nil, server_api.Namespace+"_writeToFile", jsonInput, moduleRoot) - return struct{}{}, err - }) -} - func (r *ExecutionClientRun) SendKeepAlive(ctx context.Context) time.Duration { err := r.client.client.CallContext(ctx, nil, server_api.Namespace+"_execKeepAlive", r.id) if err != nil { diff --git a/validator/interface.go b/validator/interface.go index 8c2991364a..4e759545e0 100644 --- a/validator/interface.go +++ b/validator/interface.go @@ -27,7 +27,6 @@ type ExecutionSpawner interface { ValidationSpawner CreateExecutionRun(wasmModuleRoot common.Hash, input *ValidationInput) containers.PromiseInterface[ExecutionRun] LatestWasmModuleRoot() containers.PromiseInterface[common.Hash] - WriteToFile(input *ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] } type ExecutionRun interface { diff --git a/validator/server_api/json.go b/validator/server_api/json.go index dbe2bb1fee..069ab014d9 100644 --- a/validator/server_api/json.go +++ b/validator/server_api/json.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "os" + "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/rawdb" @@ -68,12 +69,31 @@ type InputJSON struct { DebugChain bool } -func (i *InputJSON) WriteToFile() error { +// WriteToFile writes the InputJSON to a file in JSON format. +// +// The path to the file is determined in part by the slug parameter so +// callers can provide a recognizable name to differentiate various +// contexts in which the InputJSON is being written. +// +// The file is created at a path +// +// $HOME/.arbuitrum/validation-inputs///block_inputs_.json +func (i *InputJSON) WriteToFile(slug string) error { + homeDir, err := os.UserHomeDir() + if err != nil { + return err + } + t := time.Now() + tStr := t.Format("20060102_150405") + dir := fmt.Sprintf("%s/.arbitrum/validation-inputs/%s/%s", homeDir, slug, tStr) + if err = os.MkdirAll(dir, 0700); err != nil { + return err + } contents, err := json.MarshalIndent(i, "", " ") if err != nil { return err } - if err = os.WriteFile(fmt.Sprintf("block_inputs_%d.json", i.Id), contents, 0600); err != nil { + if err = os.WriteFile(fmt.Sprintf("%s/block_inputs_%d.json", dir, i.Id), contents, 0600); err != nil { return err } return nil diff --git a/validator/server_arb/validator_spawner.go b/validator/server_arb/validator_spawner.go index ae8c8be9ab..74cf77fdf5 100644 --- a/validator/server_arb/validator_spawner.go +++ b/validator/server_arb/validator_spawner.go @@ -14,7 +14,6 @@ import ( "github.com/offchainlabs/nitro/util/containers" "github.com/offchainlabs/nitro/util/stopwaiter" "github.com/offchainlabs/nitro/validator" - "github.com/offchainlabs/nitro/validator/server_api" "github.com/offchainlabs/nitro/validator/server_common" "github.com/offchainlabs/nitro/validator/valnode/redis" @@ -203,21 +202,6 @@ func (v *ArbitratorSpawner) Room() int { return avail } -func (v *ArbitratorSpawner) writeToFile(_ context.Context, input *validator.ValidationInput, _ common.Hash) error { - jsonInput := server_api.ValidationInputToJson(input) - if err := jsonInput.WriteToFile(); err != nil { - return err - } - return nil -} - -func (v *ArbitratorSpawner) WriteToFile(input *validator.ValidationInput, moduleRoot common.Hash) containers.PromiseInterface[struct{}] { - return stopwaiter.LaunchPromiseThread[struct{}](v, func(ctx context.Context) (struct{}, error) { - err := v.writeToFile(ctx, input, moduleRoot) - return struct{}{}, err - }) -} - func (v *ArbitratorSpawner) CreateExecutionRun(wasmModuleRoot common.Hash, input *validator.ValidationInput) containers.PromiseInterface[validator.ExecutionRun] { getMachine := func(ctx context.Context) (MachineInterface, error) { initialFrozenMachine, err := v.machineLoader.GetZeroStepMachine(ctx, wasmModuleRoot) diff --git a/validator/valnode/validation_api.go b/validator/valnode/validation_api.go index 68d357695b..c36d8ee62c 100644 --- a/validator/valnode/validation_api.go +++ b/validator/valnode/validation_api.go @@ -118,15 +118,6 @@ func (a *ExecServerAPI) Start(ctx_in context.Context) { a.CallIteratively(a.removeOldRuns) } -func (a *ExecServerAPI) WriteToFile(ctx context.Context, jsonInput *server_api.InputJSON, moduleRoot common.Hash) error { - input, err := server_api.ValidationInputFromJson(jsonInput) - if err != nil { - return err - } - _, err = a.execSpawner.WriteToFile(input, moduleRoot).Await(ctx) - return err -} - var errRunNotFound error = errors.New("run not found") func (a *ExecServerAPI) getRun(id uint64) (validator.ExecutionRun, error) { From 1a353b21ccc4a52f35ee0df69ba135a304a1ba17 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Fri, 23 Aug 2024 15:18:23 +0000 Subject: [PATCH 08/17] Add a hacky sleep Reviewers, please tell me the "right" way to ensure that the transaction is visible in the L1. I don't like the idea of adding sleeps in tests to ensure that some event has occurred. Is there some RPC I can call or event I can subscribe to that I can then wait for before proceeding? --- system_tests/program_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/system_tests/program_test.go b/system_tests/program_test.go index bb6e34ec4f..9392de0c4d 100644 --- a/system_tests/program_test.go +++ b/system_tests/program_test.go @@ -394,6 +394,9 @@ func storageTest(t *testing.T, jit bool) { assertStorageAt(t, ctx, l2client, programAddress, key, value) validateBlocks(t, 2, jit, builder) + // Without this sleep, this test fails in the "-race" CI builds complaining that + // the block has not been seen in L1 yet. + time.Sleep(10 * time.Second) // Captures a block_input_.json file for the block that included the // storage write transaction. recordBlock(t, receipt.BlockNumber.Uint64(), builder) From 25af47fcc1ffb06285a87d61a8cfe0cc0c5f92a3 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Thu, 29 Aug 2024 13:43:15 +0200 Subject: [PATCH 09/17] Ensure the inbox tracker has the desired message. If the inbox is lagging behind the message, the node won't be able to create a validation entry for it. --- system_tests/common_test.go | 10 ++++++++++ system_tests/program_test.go | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/system_tests/common_test.go b/system_tests/common_test.go index 53d17c762c..7f8864ff94 100644 --- a/system_tests/common_test.go +++ b/system_tests/common_test.go @@ -1467,6 +1467,16 @@ func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { ctx := builder.ctx wasmModuleRoot := currentRootModule(t) inboxPos := arbutil.MessageIndex(block) + for { + time.Sleep(250 * time.Millisecond) + batches, err := builder.L2.ConsensusNode.InboxTracker.GetBatchCount() + Require(t, err) + haveMessages, err := builder.L2.ConsensusNode.InboxTracker.GetBatchMessageCount(batches - 1) + Require(t, err) + if haveMessages >= inboxPos { + break + } + } inputJson, err := builder.L2.ConsensusNode.StatelessBlockValidator.ValidationInputsAt(ctx, inboxPos, wasmModuleRoot) if err != nil { Fatal(t, "failed to get validation inputs", block, err) diff --git a/system_tests/program_test.go b/system_tests/program_test.go index 023d88a380..c5de186978 100644 --- a/system_tests/program_test.go +++ b/system_tests/program_test.go @@ -396,7 +396,8 @@ func storageTest(t *testing.T, jit bool) { validateBlocks(t, 2, jit, builder) // Without this sleep, this test fails in the "-race" CI builds complaining that // the block has not been seen in L1 yet. - time.Sleep(10 * time.Second) + // time.Sleep(10 * time.Second) + // Captures a block_input_.json file for the block that included the // storage write transaction. recordBlock(t, receipt.BlockNumber.Uint64(), builder) From e0d70e6aeddb02606689812dff8a92ae16c009f8 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Thu, 29 Aug 2024 13:45:07 +0200 Subject: [PATCH 10/17] Remove commented out code. Meant to do this in the previous commit. --- system_tests/program_test.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/system_tests/program_test.go b/system_tests/program_test.go index c5de186978..9b3dd56ffb 100644 --- a/system_tests/program_test.go +++ b/system_tests/program_test.go @@ -394,9 +394,6 @@ func storageTest(t *testing.T, jit bool) { assertStorageAt(t, ctx, l2client, programAddress, key, value) validateBlocks(t, 2, jit, builder) - // Without this sleep, this test fails in the "-race" CI builds complaining that - // the block has not been seen in L1 yet. - // time.Sleep(10 * time.Second) // Captures a block_input_.json file for the block that included the // storage write transaction. From bc25dde884f0c473c72a41cff01ba2b248ef3415 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Thu, 29 Aug 2024 15:35:05 +0200 Subject: [PATCH 11/17] Separate the writer for validaiton inputs from the json. This change attempts to make the location for writing the json file more flexibly configurable by the clients without making it difficult to put the data in a resonable spot by default. --- staker/block_validator.go | 11 ++- system_tests/common_test.go | 6 +- validator/inputs/writer.go | 129 ++++++++++++++++++++++++++++++++ validator/inputs/writer_test.go | 87 +++++++++++++++++++++ validator/server_api/json.go | 33 +------- 5 files changed, 234 insertions(+), 32 deletions(-) create mode 100644 validator/inputs/writer.go create mode 100644 validator/inputs/writer_test.go diff --git a/staker/block_validator.go b/staker/block_validator.go index a7e475b4f0..a884ac81f7 100644 --- a/staker/block_validator.go +++ b/staker/block_validator.go @@ -29,6 +29,7 @@ import ( "github.com/offchainlabs/nitro/util/stopwaiter" "github.com/offchainlabs/nitro/validator" "github.com/offchainlabs/nitro/validator/client/redis" + "github.com/offchainlabs/nitro/validator/inputs" "github.com/offchainlabs/nitro/validator/server_api" "github.com/spf13/pflag" ) @@ -95,6 +96,9 @@ type BlockValidator struct { // for testing only testingProgressMadeChan chan struct{} + // For troubleshooting failed validations + validationInputsWriter *inputs.Writer + fatalErr chan<- error MemoryFreeLimitChecker resourcemanager.LimitChecker @@ -275,6 +279,11 @@ func NewBlockValidator( config: config, fatalErr: fatalErr, } + valInputsWriter, err := inputs.NewWriter() + if err != nil { + return nil, err + } + ret.validationInputsWriter = valInputsWriter.SetSlug("BlockValidator") if !config().Dangerous.ResetBlockValidation { validated, err := ret.ReadLastValidatedInfo() if err != nil { @@ -512,7 +521,7 @@ func (v *BlockValidator) writeToFile(validationEntry *validationEntry) error { return err } inputJson := server_api.ValidationInputToJson(input) - if err := inputJson.WriteToFile("BlockValidator"); err != nil { + if err := v.validationInputsWriter.Write(inputJson); err != nil { return err } return nil diff --git a/system_tests/common_test.go b/system_tests/common_test.go index 7f8864ff94..17834b429d 100644 --- a/system_tests/common_test.go +++ b/system_tests/common_test.go @@ -36,6 +36,7 @@ import ( "github.com/offchainlabs/nitro/util/headerreader" "github.com/offchainlabs/nitro/util/redisutil" "github.com/offchainlabs/nitro/util/signature" + "github.com/offchainlabs/nitro/validator/inputs" "github.com/offchainlabs/nitro/validator/server_api" "github.com/offchainlabs/nitro/validator/server_common" "github.com/offchainlabs/nitro/validator/valnode" @@ -1477,11 +1478,14 @@ func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { break } } + validationInputsWriter, err := inputs.NewWriter() + Require(t, err) + validationInputsWriter.SetSlug(t.Name()) inputJson, err := builder.L2.ConsensusNode.StatelessBlockValidator.ValidationInputsAt(ctx, inboxPos, wasmModuleRoot) if err != nil { Fatal(t, "failed to get validation inputs", block, err) } - if err := inputJson.WriteToFile(t.Name()); err != nil { + if err := validationInputsWriter.Write(&inputJson); err != nil { Fatal(t, "failed to write validation inputs", block, err) } } diff --git a/validator/inputs/writer.go b/validator/inputs/writer.go new file mode 100644 index 0000000000..b8160a4fa5 --- /dev/null +++ b/validator/inputs/writer.go @@ -0,0 +1,129 @@ +package inputs + +import ( + "fmt" + "os" + "time" + + "github.com/offchainlabs/nitro/validator/server_api" +) + +// Writer is a configurable writer of InputJSON files. +// +// The default Writer will write to a path like: +// +// $HOME/.arbuitrum/validation-inputs//block_inputs_.json +// +// The path can be nested under a slug directory so callers can provide a +// recognizable name to differentiate various contexts in which the InputJSON +// is being written. If the Writer is configured by calling SetSlug, then the +// path will be like: +// +// $HOME/.arbuitrum/validation-inputs///block_inputs_.json +// +// The inclusion of a timestamp directory is on by default to avoid conflicts which +// would result in files being overwritten. However, the Writer can be configured +// to not use a timestamp directory. If the Writer is configured by calling +// SetUseTimestampDir(false), then the path will be like: +// +// $HOME/.arbuitrum/validation-inputs//block_inputs_.json +// +// Finally, to give complete control to the clients, the base directory can be +// set directly with SetBaseDir. In which case, the path will be like: +// +// /block_inputs_.json +// or +// //block_inputs_.json +// or +// ///block_inputs_.json +type Writer struct { + clock Clock + baseDir string + slug string + useTimestampDir bool +} + +// Clock is an interface for getting the current time. +type Clock interface { + Now() time.Time +} + +type realClock struct{} + +func (realClock) Now() time.Time { + return time.Now() +} + +// NewWriter creates a new Writer with default settings. +func NewWriter() (*Writer, error) { + homeDir, err := os.UserHomeDir() + if err != nil { + return nil, err + } + baseDir := fmt.Sprintf("%s/.arbitrum/validation-inputs", homeDir) + return &Writer{ + clock: realClock{}, + baseDir: baseDir, + slug: "", + useTimestampDir: true}, nil +} + +// SetClockForTesting sets the clock used by the Writer. +// +// This is only intended for testing. +func (w *Writer) SetClockForTesting(clock Clock) *Writer { + w.clock = clock + return w +} + +// SetSlug configures the Writer to use the given slug as a directory name. +func (w *Writer) SetSlug(slug string) *Writer { + w.slug = slug + return w +} + +// ClearSlug clears the slug configuration. +// +// This is equivalent to calling SetSlug("") but is more readable. +func (w *Writer) ClearSlug() *Writer { + w.slug = "" + return w +} + +// SetBaseDir configures the Writer to use the given base directory. +func (w *Writer) SetBaseDir(baseDir string) *Writer { + w.baseDir = baseDir + return w +} + +// SetUseTimestampDir controls the addition of a timestamp directory. +func (w *Writer) SetUseTimestampDir(useTimestampDir bool) *Writer { + w.useTimestampDir = useTimestampDir + return w +} + +// Write writes the given InputJSON to a file in JSON format. +func (w *Writer) Write(inputs *server_api.InputJSON) error { + dir := w.baseDir + if w.slug != "" { + dir = fmt.Sprintf("%s/%s", dir, w.slug) + } + if w.useTimestampDir { + t := w.clock.Now() + tStr := t.Format("20060102_150405") + dir = fmt.Sprintf("%s/%s", dir, tStr) + } + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + contents, err := inputs.Marshal() + if err != nil { + return err + } + if err = os.WriteFile( + fmt.Sprintf("%s/block_inputs_%d.json", dir, inputs.Id), + contents, 0600); err != nil { + return err + } + return nil +} diff --git a/validator/inputs/writer_test.go b/validator/inputs/writer_test.go new file mode 100644 index 0000000000..5e80b9aa3a --- /dev/null +++ b/validator/inputs/writer_test.go @@ -0,0 +1,87 @@ +package inputs + +import ( + "os" + "testing" + "time" + + "github.com/offchainlabs/nitro/validator/server_api" +) + +func TestDefaultBaseDir(t *testing.T) { + // Simply testing that the default baseDir is set relative to the user's home directory. + // This way, the other tests can all override the baseDir to a temporary directory. + w, err := NewWriter() + if err != nil { + t.Fatal(err) + } + homeDir, err := os.UserHomeDir() + if err != nil { + t.Fatal(err) + } + if w.baseDir != homeDir+"/.arbitrum/validation-inputs" { + t.Errorf("unexpected baseDir: %v", w.baseDir) + } +} + +type fakeClock struct { + now time.Time +} + +func (c fakeClock) Now() time.Time { + return c.now +} + +func TestWriting(t *testing.T) { + w, err := NewWriter() + if err != nil { + t.Fatal(err) + } + w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) + dir := t.TempDir() + w.SetBaseDir(dir) + err = w.Write(&server_api.InputJSON{Id: 24601}) + if err != nil { + t.Fatal(err) + } + // The file should exist. + if _, err := os.Stat(dir + "/20210102_030405/block_inputs_24601.json"); err != nil { + t.Error(err) + } +} + +func TestWritingWithSlug(t *testing.T) { + w, err := NewWriter() + if err != nil { + t.Fatal(err) + } + w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) + dir := t.TempDir() + w.SetBaseDir(dir).SetSlug("foo") + err = w.Write(&server_api.InputJSON{Id: 24601}) + if err != nil { + t.Fatal(err) + } + // The file should exist. + if _, err := os.Stat(dir + "/foo/20210102_030405/block_inputs_24601.json"); err != nil { + t.Error(err) + } +} + +func TestWritingWithoutTimestampDir(t *testing.T) { + w, err := NewWriter() + if err != nil { + t.Fatal(err) + } + w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) + dir := t.TempDir() + w.SetBaseDir(dir).SetUseTimestampDir(false) + err = w.Write(&server_api.InputJSON{Id: 24601}) + if err != nil { + t.Fatal(err) + } + // The file should exist. + if _, err := os.Stat(dir + "/block_inputs_24601.json"); err != nil { + t.Error(err) + } +} diff --git a/validator/server_api/json.go b/validator/server_api/json.go index 069ab014d9..bdb19bc0ba 100644 --- a/validator/server_api/json.go +++ b/validator/server_api/json.go @@ -8,8 +8,6 @@ import ( "encoding/json" "errors" "fmt" - "os" - "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/rawdb" @@ -69,34 +67,9 @@ type InputJSON struct { DebugChain bool } -// WriteToFile writes the InputJSON to a file in JSON format. -// -// The path to the file is determined in part by the slug parameter so -// callers can provide a recognizable name to differentiate various -// contexts in which the InputJSON is being written. -// -// The file is created at a path -// -// $HOME/.arbuitrum/validation-inputs///block_inputs_.json -func (i *InputJSON) WriteToFile(slug string) error { - homeDir, err := os.UserHomeDir() - if err != nil { - return err - } - t := time.Now() - tStr := t.Format("20060102_150405") - dir := fmt.Sprintf("%s/.arbitrum/validation-inputs/%s/%s", homeDir, slug, tStr) - if err = os.MkdirAll(dir, 0700); err != nil { - return err - } - contents, err := json.MarshalIndent(i, "", " ") - if err != nil { - return err - } - if err = os.WriteFile(fmt.Sprintf("%s/block_inputs_%d.json", dir, i.Id), contents, 0600); err != nil { - return err - } - return nil +// Marshal returns the JSON encoding of the InputJSON. +func (i *InputJSON) Marshal() ([]byte, error) { + return json.MarshalIndent(i, "", " ") } type BatchInfoJson struct { From 984a7f1cec03d86fa40f2a0634f1fa3fcf1c69ff Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 18 Sep 2024 15:14:58 +0200 Subject: [PATCH 12/17] Fix broken imports of ethdb and rawdb --- staker/stateless_block_validator.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index 0cd97ec8d3..c4b0948e43 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -12,6 +12,7 @@ import ( "github.com/offchainlabs/nitro/arbstate/daprovider" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/log" @@ -468,7 +469,7 @@ func (v *StatelessBlockValidator) ValidationInputsAt(ctx context.Context, pos ar if err != nil { return server_api.InputJSON{}, err } - input, err := entry.ToInput([]rawdb.Target{rawdb.TargetWavm}) + input, err := entry.ToInput([]ethdb.WasmTarget{rawdb.TargetWavm}) if err != nil { return server_api.InputJSON{}, err } From c45d80fd4ff16fd4b25dc8e4e200be19d5f0cd7c Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 18 Sep 2024 15:35:34 +0200 Subject: [PATCH 13/17] Update Cargo.lock --- arbitrator/wasm-libraries/Cargo.lock | 195 ++++++++++++++++++++------- 1 file changed, 148 insertions(+), 47 deletions(-) diff --git a/arbitrator/wasm-libraries/Cargo.lock b/arbitrator/wasm-libraries/Cargo.lock index b234424f69..c79b389f6a 100644 --- a/arbitrator/wasm-libraries/Cargo.lock +++ b/arbitrator/wasm-libraries/Cargo.lock @@ -46,6 +46,21 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "ansi_term" version = "0.12.1" @@ -121,6 +136,12 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bincode" version = "1.3.3" @@ -260,6 +281,19 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-targets", +] + [[package]] name = "clap" version = "2.34.0" @@ -281,6 +315,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "corosensei" version = "0.1.4" @@ -436,38 +476,14 @@ dependencies = [ "typenum", ] -[[package]] -name = "darling" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" -dependencies = [ - "darling_core 0.13.4", - "darling_macro 0.13.4", -] - [[package]] name = "darling" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ - "darling_core 0.20.10", - "darling_macro 0.20.10", -] - -[[package]] -name = "darling_core" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 1.0.109", + "darling_core", + "darling_macro", ] [[package]] @@ -480,27 +496,17 @@ dependencies = [ "ident_case", "proc-macro2", "quote", + "strsim 0.11.1", "syn 2.0.72", ] -[[package]] -name = "darling_macro" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" -dependencies = [ - "darling_core 0.13.4", - "quote", - "syn 1.0.109", -] - [[package]] name = "darling_macro" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ - "darling_core 0.20.10", + "darling_core", "quote", "syn 2.0.72", ] @@ -518,6 +524,16 @@ dependencies = [ "parking_lot_core", ] +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + [[package]] name = "derivative" version = "2.2.0" @@ -622,7 +638,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59c3b24c345d8c314966bdc1832f6c2635bfcce8e7cf363bd115987bba2ee242" dependencies = [ - "darling 0.20.10", + "darling", "proc-macro2", "quote", "syn 2.0.72", @@ -760,6 +776,29 @@ dependencies = [ "caller-env", ] +[[package]] +name = "iana-time-zone" +version = "0.1.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -780,6 +819,7 @@ checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg", "hashbrown 0.12.3", + "serde", ] [[package]] @@ -790,6 +830,7 @@ checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0" dependencies = [ "equivalent", "hashbrown 0.14.5", + "serde", ] [[package]] @@ -1000,6 +1041,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-derive" version = "0.4.2" @@ -1128,6 +1175,12 @@ version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "proc-macro-crate" version = "3.1.0" @@ -1473,24 +1526,32 @@ dependencies = [ [[package]] name = "serde_with" -version = "1.14.0" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" +checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" dependencies = [ + "base64", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.3.0", "serde", + "serde_derive", + "serde_json", "serde_with_macros", + "time", ] [[package]] name = "serde_with_macros" -version = "1.5.2" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" +checksum = "a8fee4991ef4f274617a51ad4af30519438dacb2f56ac773b08a1922ff743350" dependencies = [ - "darling 0.13.4", + "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.72", ] [[package]] @@ -1602,9 +1663,9 @@ checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" [[package]] name = "strsim" -version = "0.10.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "structopt" @@ -1693,6 +1754,37 @@ dependencies = [ "syn 2.0.72", ] +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -2111,6 +2203,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.33.0" From f9e6eea54e31d50834f64697b5cd029c5274e160 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Wed, 18 Sep 2024 18:32:16 +0200 Subject: [PATCH 14/17] Address review feedback --- arbitrator/arbutil/src/types.rs | 101 ++++++++++++++++++++++++++++ arbitrator/prover/src/prepare.rs | 1 - arbnode/api.go | 15 +---- staker/stateless_block_validator.go | 5 +- system_tests/common_test.go | 3 +- 5 files changed, 107 insertions(+), 18 deletions(-) diff --git a/arbitrator/arbutil/src/types.rs b/arbitrator/arbutil/src/types.rs index 207b8ab949..e92d4dfbc5 100644 --- a/arbitrator/arbutil/src/types.rs +++ b/arbitrator/arbutil/src/types.rs @@ -84,6 +84,32 @@ impl From for Bytes32 { } } +impl FromStr for Bytes32 { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + // Remove the "0x" prefix if present + let s = s.strip_prefix("0x").unwrap_or(s); + + // Pad with leading zeros if the string is shorter than 64 characters (32 bytes) + let padded = format!("{:0>64}", s); + + // Decode the hex string using the hex crate + let decoded_bytes = hex::decode(padded).map_err(|_| "Invalid hex string")?; + + // Ensure the decoded bytes is exactly 32 bytes + if decoded_bytes.len() != 32 { + return Err("Hex string too long for Bytes32"); + } + + // Create a 32-byte array and fill it with the decoded bytes. + let mut b = [0u8; 32]; + b.copy_from_slice(&decoded_bytes); + + Ok(Bytes32(b)) + } +} +/* impl FromStr for Bytes32 { type Err = hex::FromHexError; @@ -98,6 +124,7 @@ impl FromStr for Bytes32 { Ok(Self(b)) } } +*/ impl TryFrom<&[u8]> for Bytes32 { type Error = std::array::TryFromSliceError; @@ -265,3 +292,77 @@ impl From for Bytes20 { <[u8; 20]>::from(x).into() } } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_bytes32() { + let b = Bytes32::from(0x12345678u32); + let expected = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0x12, 0x34, 0x56, 0x78, + ]; + assert_eq!(b, Bytes32(expected)); + } + + #[test] + fn test_from_str_short() { + // Short hex string + let b = Bytes32::from_str("0x12345678").unwrap(); + let expected = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0x12, 0x34, 0x56, 0x78, + ]; + assert_eq!(b, Bytes32(expected)); + } + + #[test] + fn test_from_str_very_short() { + // Short hex string + let b = Bytes32::from_str("0x1").unwrap(); + let expected = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0x1, + ]; + assert_eq!(b, Bytes32(expected)); + } + + #[test] + fn test_from_str_no_prefix() { + // Short hex string + let b = Bytes32::from_str("12345678").unwrap(); + let expected = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0x12, 0x34, 0x56, 0x78, + ]; + assert_eq!(b, Bytes32(expected)); + } + + #[test] + fn test_from_str_full() { + // Full-length hex string + let b = + Bytes32::from_str("0x0000000000000000000000000000000000000000000000000000000012345678") + .unwrap(); + let expected = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0x12, 0x34, 0x56, 0x78, + ]; + assert_eq!(b, Bytes32(expected)); + } + + #[test] + fn test_from_str_invalid_non_hex() { + let s = "0x123g5678"; // Invalid character 'g' + assert!(Bytes32::from_str(s).is_err()); + } + + #[test] + fn test_from_str_too_big() { + let s = + "0123456789ABCDEF0123456789ABCDEF01234567890123456789ABCDEF01234567890123456789ABCDEF0"; // 65 characters + assert!(Bytes32::from_str(s).is_err()); + } +} diff --git a/arbitrator/prover/src/prepare.rs b/arbitrator/prover/src/prepare.rs index ecfb517735..a485267f39 100644 --- a/arbitrator/prover/src/prepare.rs +++ b/arbitrator/prover/src/prepare.rs @@ -42,7 +42,6 @@ pub fn prepare_machine(preimages: PathBuf, machines: PathBuf) -> eyre::Result Date: Wed, 18 Sep 2024 18:47:30 +0200 Subject: [PATCH 15/17] Remove commented out implementation. --- arbitrator/arbutil/src/types.rs | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/arbitrator/arbutil/src/types.rs b/arbitrator/arbutil/src/types.rs index e92d4dfbc5..722a89b81e 100644 --- a/arbitrator/arbutil/src/types.rs +++ b/arbitrator/arbutil/src/types.rs @@ -109,22 +109,6 @@ impl FromStr for Bytes32 { Ok(Bytes32(b)) } } -/* -impl FromStr for Bytes32 { - type Err = hex::FromHexError; - - fn from_str(s: &str) -> Result { - let trimmed = match s.strip_prefix("0x") { - Some(t) => t, - None => s, - }; - let bytes = hex::decode(trimmed)?; - let mut b = [0u8; 32]; - b.copy_from_slice(&bytes); - Ok(Self(b)) - } -} -*/ impl TryFrom<&[u8]> for Bytes32 { type Error = std::array::TryFromSliceError; From c550c7ed5bc17b85b181e7fb62a7b59d8315590b Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Sat, 28 Sep 2024 16:50:59 +0300 Subject: [PATCH 16/17] Switch to funcional options for the inputs.Writer This change also saves the stack argument passed to the NewStatelessBlockValidator function to a member of StatelessBlockValidator so that the BlockValidator can use the `stack.InstanceDir()` method to set a reasonable base directory for storing validation inputs as json files. --- arbitrator/wasm-libraries/Cargo.lock | 122 +++++++++++++++++++++++++++ staker/block_validator.go | 6 +- staker/stateless_block_validator.go | 2 + system_tests/common_test.go | 3 +- validator/inputs/writer.go | 70 ++++++++------- validator/inputs/writer_test.go | 29 ++++--- 6 files changed, 187 insertions(+), 45 deletions(-) diff --git a/arbitrator/wasm-libraries/Cargo.lock b/arbitrator/wasm-libraries/Cargo.lock index be2bd828f3..a5a066e5c9 100644 --- a/arbitrator/wasm-libraries/Cargo.lock +++ b/arbitrator/wasm-libraries/Cargo.lock @@ -106,6 +106,12 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bincode" version = "1.3.3" @@ -218,6 +224,15 @@ dependencies = [ "rand_pcg", ] +[[package]] +name = "cc" +version = "1.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9540e661f81799159abee814118cc139a2004b3a3aa3ea37724a1b66530b90e0" +dependencies = [ + "shlex", +] + [[package]] name = "cfg-if" version = "0.1.10" @@ -264,6 +279,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.12" @@ -324,6 +345,16 @@ dependencies = [ "syn 2.0.72", ] +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + [[package]] name = "derivative" version = "2.2.0" @@ -614,6 +645,15 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +[[package]] +name = "js-sys" +version = "0.3.70" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "keccak" version = "0.1.5" @@ -651,6 +691,12 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + [[package]] name = "lru" version = "0.12.4" @@ -857,6 +903,12 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "proc-macro-crate" version = "3.1.0" @@ -1214,6 +1266,12 @@ dependencies = [ "keccak", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "simdutf8" version = "0.1.4" @@ -1509,6 +1567,61 @@ dependencies = [ "wee_alloc", ] +[[package]] +name = "wasm-bindgen" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +dependencies = [ + "cfg-if 1.0.0", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.72", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" + [[package]] name = "wasm-encoder" version = "0.215.0" @@ -1599,6 +1712,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-targets" version = "0.52.6" diff --git a/staker/block_validator.go b/staker/block_validator.go index 30df20a2d2..5a1f123693 100644 --- a/staker/block_validator.go +++ b/staker/block_validator.go @@ -288,11 +288,13 @@ func NewBlockValidator( fatalErr: fatalErr, prevBatchCache: make(map[uint64][]byte), } - valInputsWriter, err := inputs.NewWriter() + valInputsWriter, err := inputs.NewWriter( + inputs.WithBaseDir(ret.stack.InstanceDir()), + inputs.WithSlug("BlockValidator")) if err != nil { return nil, err } - ret.validationInputsWriter = valInputsWriter.SetSlug("BlockValidator") + ret.validationInputsWriter = valInputsWriter if !config().Dangerous.ResetBlockValidation { validated, err := ret.ReadLastValidatedInfo() if err != nil { diff --git a/staker/stateless_block_validator.go b/staker/stateless_block_validator.go index fa34842dc9..9257c5582a 100644 --- a/staker/stateless_block_validator.go +++ b/staker/stateless_block_validator.go @@ -41,6 +41,7 @@ type StatelessBlockValidator struct { streamer TransactionStreamerInterface db ethdb.Database dapReaders []daprovider.Reader + stack *node.Node } type BlockValidatorRegistrer interface { @@ -265,6 +266,7 @@ func NewStatelessBlockValidator( db: arbdb, dapReaders: dapReaders, execSpawners: executionSpawners, + stack: stack, }, nil } diff --git a/system_tests/common_test.go b/system_tests/common_test.go index ed098351e5..d5f65de43e 100644 --- a/system_tests/common_test.go +++ b/system_tests/common_test.go @@ -1712,9 +1712,8 @@ func recordBlock(t *testing.T, block uint64, builder *NodeBuilder) { break } } - validationInputsWriter, err := inputs.NewWriter() + validationInputsWriter, err := inputs.NewWriter(inputs.WithSlug(t.Name())) Require(t, err) - validationInputsWriter.SetSlug(t.Name()) inputJson, err := builder.L2.ConsensusNode.StatelessBlockValidator.ValidationInputsAt(ctx, inboxPos, rawdb.TargetWavm) if err != nil { Fatal(t, "failed to get validation inputs", block, err) diff --git a/validator/inputs/writer.go b/validator/inputs/writer.go index b8160a4fa5..1fd23dbb40 100644 --- a/validator/inputs/writer.go +++ b/validator/inputs/writer.go @@ -3,6 +3,7 @@ package inputs import ( "fmt" "os" + "path/filepath" "time" "github.com/offchainlabs/nitro/validator/server_api" @@ -43,6 +44,9 @@ type Writer struct { useTimestampDir bool } +// WriterOption is a function that configures a Writer. +type WriterOption func(*Writer) + // Clock is an interface for getting the current time. type Clock interface { Now() time.Time @@ -55,73 +59,81 @@ func (realClock) Now() time.Time { } // NewWriter creates a new Writer with default settings. -func NewWriter() (*Writer, error) { +func NewWriter(options ...WriterOption) (*Writer, error) { homeDir, err := os.UserHomeDir() if err != nil { return nil, err } baseDir := fmt.Sprintf("%s/.arbitrum/validation-inputs", homeDir) - return &Writer{ + w := &Writer{ clock: realClock{}, baseDir: baseDir, slug: "", - useTimestampDir: true}, nil + useTimestampDir: true, + } + for _, o := range options { + o(w) + } + return w, nil } -// SetClockForTesting sets the clock used by the Writer. +// withTestClock configures the Writer to use the given clock. // // This is only intended for testing. -func (w *Writer) SetClockForTesting(clock Clock) *Writer { - w.clock = clock - return w +func withTestClock(clock Clock) WriterOption { + return func(w *Writer) { + w.clock = clock + } } -// SetSlug configures the Writer to use the given slug as a directory name. -func (w *Writer) SetSlug(slug string) *Writer { - w.slug = slug - return w +// WithSlug configures the Writer to use the given slug as a directory name. +func WithSlug(slug string) WriterOption { + return func(w *Writer) { + w.slug = slug + } } -// ClearSlug clears the slug configuration. +// WithoutSlug clears the slug configuration. // -// This is equivalent to calling SetSlug("") but is more readable. -func (w *Writer) ClearSlug() *Writer { - w.slug = "" - return w +// This is equivalent to the WithSlug("") option but is more readable. +func WithoutSlug() WriterOption { + return WithSlug("") } -// SetBaseDir configures the Writer to use the given base directory. -func (w *Writer) SetBaseDir(baseDir string) *Writer { - w.baseDir = baseDir - return w +// WithBaseDir configures the Writer to use the given base directory. +func WithBaseDir(baseDir string) WriterOption { + return func(w *Writer) { + w.baseDir = baseDir + } } -// SetUseTimestampDir controls the addition of a timestamp directory. -func (w *Writer) SetUseTimestampDir(useTimestampDir bool) *Writer { - w.useTimestampDir = useTimestampDir - return w +// WithTimestampDirEnabled controls the addition of a timestamp directory. +func WithTimestampDirEnabled(useTimestampDir bool) WriterOption { + return func(w *Writer) { + w.useTimestampDir = useTimestampDir + } } // Write writes the given InputJSON to a file in JSON format. -func (w *Writer) Write(inputs *server_api.InputJSON) error { +func (w *Writer) Write(json *server_api.InputJSON) error { dir := w.baseDir if w.slug != "" { - dir = fmt.Sprintf("%s/%s", dir, w.slug) + dir = filepath.Join(dir, w.slug) } if w.useTimestampDir { t := w.clock.Now() tStr := t.Format("20060102_150405") - dir = fmt.Sprintf("%s/%s", dir, tStr) + dir = filepath.Join(dir, tStr) } if err := os.MkdirAll(dir, 0700); err != nil { return err } - contents, err := inputs.Marshal() + contents, err := json.Marshal() if err != nil { return err } if err = os.WriteFile( - fmt.Sprintf("%s/block_inputs_%d.json", dir, inputs.Id), + fmt.Sprintf("%s/block_inputs_%d.json", dir, json.Id), contents, 0600); err != nil { return err } diff --git a/validator/inputs/writer_test.go b/validator/inputs/writer_test.go index 5e80b9aa3a..59cb63dae7 100644 --- a/validator/inputs/writer_test.go +++ b/validator/inputs/writer_test.go @@ -33,13 +33,14 @@ func (c fakeClock) Now() time.Time { } func TestWriting(t *testing.T) { - w, err := NewWriter() + dir := t.TempDir() + w, err := NewWriter( + withTestClock(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}), + WithBaseDir(dir), + ) if err != nil { t.Fatal(err) } - w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) - dir := t.TempDir() - w.SetBaseDir(dir) err = w.Write(&server_api.InputJSON{Id: 24601}) if err != nil { t.Fatal(err) @@ -51,13 +52,15 @@ func TestWriting(t *testing.T) { } func TestWritingWithSlug(t *testing.T) { - w, err := NewWriter() + dir := t.TempDir() + w, err := NewWriter( + withTestClock(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}), + WithBaseDir(dir), + WithSlug("foo"), + ) if err != nil { t.Fatal(err) } - w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) - dir := t.TempDir() - w.SetBaseDir(dir).SetSlug("foo") err = w.Write(&server_api.InputJSON{Id: 24601}) if err != nil { t.Fatal(err) @@ -69,13 +72,15 @@ func TestWritingWithSlug(t *testing.T) { } func TestWritingWithoutTimestampDir(t *testing.T) { - w, err := NewWriter() + dir := t.TempDir() + w, err := NewWriter( + withTestClock(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}), + WithBaseDir(dir), + WithTimestampDirEnabled(false), + ) if err != nil { t.Fatal(err) } - w.SetClockForTesting(fakeClock{now: time.Date(2021, 1, 2, 3, 4, 5, 0, time.UTC)}) - dir := t.TempDir() - w.SetBaseDir(dir).SetUseTimestampDir(false) err = w.Write(&server_api.InputJSON{Id: 24601}) if err != nil { t.Fatal(err) From ea47d46d7557d3d600968c46d37674381d710081 Mon Sep 17 00:00:00 2001 From: Pepper Lebeck-Jobe Date: Sat, 28 Sep 2024 16:58:05 +0300 Subject: [PATCH 17/17] Fix two last instances of system-specific paths --- validator/inputs/writer.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/validator/inputs/writer.go b/validator/inputs/writer.go index 1fd23dbb40..a45e584f52 100644 --- a/validator/inputs/writer.go +++ b/validator/inputs/writer.go @@ -64,7 +64,7 @@ func NewWriter(options ...WriterOption) (*Writer, error) { if err != nil { return nil, err } - baseDir := fmt.Sprintf("%s/.arbitrum/validation-inputs", homeDir) + baseDir := filepath.Join(homeDir, ".arbitrum", "validation-inputs") w := &Writer{ clock: realClock{}, baseDir: baseDir, @@ -133,7 +133,7 @@ func (w *Writer) Write(json *server_api.InputJSON) error { return err } if err = os.WriteFile( - fmt.Sprintf("%s/block_inputs_%d.json", dir, json.Id), + filepath.Join(dir, fmt.Sprintf("block_inputs_%d.json", json.Id)), contents, 0600); err != nil { return err }