Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ members = ["crates/*"]
resolver = "2"

[workspace.package]
version = "0.19.0"
version = "0.20.0"
edition = "2021"
rust-version = "1.87"
authors = ["init4"]
Expand Down Expand Up @@ -34,19 +34,19 @@ debug = false
incremental = false

[workspace.dependencies]
signet-bundle = { version = "0.19.0", path = "crates/bundle" }
signet-constants = { version = "0.19.0", path = "crates/constants" }
signet-evm = { version = "0.19.0", path = "crates/evm" }
signet-extract = { version = "0.19.0", path = "crates/extract" }
signet-journal = { version = "0.19.0", path = "crates/journal" }
signet-node = { version = "0.19.0", path = "crates/node" }
signet-orders = { version = "0.19.0", path = "crates/orders" }
signet-sim = { version = "0.19.0", path = "crates/sim" }
signet-types = { version = "0.19.0", path = "crates/types" }
signet-tx-cache = { version = "0.19.0", path = "crates/tx-cache" }
signet-zenith = { version = "0.19.0", path = "crates/zenith" }
signet-bundle = { version = "0.20.0", path = "crates/bundle" }
signet-constants = { version = "0.20.0", path = "crates/constants" }
signet-evm = { version = "0.20.0", path = "crates/evm" }
signet-extract = { version = "0.20.0", path = "crates/extract" }
signet-journal = { version = "0.20.0", path = "crates/journal" }
signet-node = { version = "0.20.0", path = "crates/node" }
signet-orders = { version = "0.20.0", path = "crates/orders" }
signet-sim = { version = "0.20.0", path = "crates/sim" }
signet-types = { version = "0.20.0", path = "crates/types" }
signet-tx-cache = { version = "0.20.0", path = "crates/tx-cache" }
signet-zenith = { version = "0.20.0", path = "crates/zenith" }

signet-test-utils = { version = "0.19.0", path = "crates/test-utils" }
signet-test-utils = { version = "0.20.0", path = "crates/test-utils" }

# trevm
trevm = { version = "0.34.2", features = ["full_env_cfg", "asyncdb"] }
Expand Down
2 changes: 1 addition & 1 deletion crates/orders/src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ mod tests {
permitted: Vec<TokenPermissions>,
outputs: Vec<Output>,
) -> SignedOrder {
SignedOrder::new(
SignedOrder::new_unchecked(
Permit2Batch {
permit: PermitBatchTransferFrom {
permitted,
Expand Down
12 changes: 6 additions & 6 deletions crates/orders/src/stream/predicates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ mod tests {
assert!(!not_expired_at(|| 101)(&order));

// Cross-check against `SignedOrder::validate` to lock in the matching boundary.
order.validate(99).unwrap();
order.validate(100).unwrap();
order.validate(101).unwrap_err();
order.validate_at(99).unwrap();
order.validate_at(100).unwrap();
order.validate_at(101).unwrap_err();
}

#[test]
Expand All @@ -127,7 +127,7 @@ mod tests {
// A deadline that overflows u64 must saturate to u64::MAX, so the order is always
// considered alive against any u64 cutoff. This mirrors `SignedOrder::validate`, which
// uses `saturating_to::<u64>()`.
let order = SignedOrder::new(
let order = SignedOrder::new_unchecked(
Permit2Batch {
permit: PermitBatchTransferFrom {
permitted: vec![],
Expand All @@ -142,8 +142,8 @@ mod tests {

assert!(not_expired_at(|| 0)(&order));
assert!(not_expired_at(|| u64::MAX)(&order));
order.validate(0).unwrap();
order.validate(u64::MAX).unwrap();
order.validate_at(0).unwrap();
order.validate_at(u64::MAX).unwrap();
}

#[test]
Expand Down
3 changes: 3 additions & 0 deletions crates/test-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,7 @@ uuid = { workspace = true, features = ["v4"] }

[dev-dependencies]
chrono.workspace = true
proptest = "1.6"
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
tokio = { workspace = true, features = ["macros", "rt"] }
148 changes: 148 additions & 0 deletions crates/test-utils/tests/deserialization_fuzz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
//! Proptests covering `signet-types` deserialization paths that consume
//! untrusted JSON.
//!
//! Regression coverage for ENG-2288 (`SignedOrder::order_hash` panic on
//! malformed signatures) and a forward-looking guarantee that no
//! `serde::Deserialize` impl on a SDK-exposed type panics on arbitrary
//! input — every malformed payload must surface as a `serde_json::Error`,
//! never an unwinding panic.
use alloy::primitives::Bytes;
use proptest::prelude::*;
use serde::Deserialize;
use signet_types::SignedOrder;
use signet_zenith::serde_helpers::{deserialize_non_empty_vec, deserialize_signature_bytes};

#[derive(Debug, Deserialize)]
struct SigWrap {
#[serde(deserialize_with = "deserialize_signature_bytes")]
signature: Bytes,
}

#[derive(Debug, Deserialize)]
struct VecWrap {
#[serde(deserialize_with = "deserialize_non_empty_vec")]
items: Vec<u64>,
}

fn hex_string(bytes: &[u8]) -> String {
let mut s = String::with_capacity(2 + bytes.len() * 2);
s.push_str("0x");
for b in bytes {
use std::fmt::Write;
write!(&mut s, "{b:02x}").unwrap();
}
s
}

fn signed_order_json(sig_bytes: &[u8], permitted_count: usize, outputs_count: usize) -> String {
let permitted: Vec<String> = (0..permitted_count)
.map(|i| format!(r#"{{"token":"0x{:040x}","amount":"0x{i:x}"}}"#, i as u128))
.collect();
let outputs: Vec<String> = (0..outputs_count)
.map(|i| {
format!(
r#"{{"token":"0x{:040x}","amount":"0x{i:x}","recipient":"0x{:040x}","chainId":{i}}}"#,
i as u128, i as u128
)
})
.collect();
format!(
r#"{{
"permit": {{
"permitted": [{}],
"nonce": "0x0",
"deadline": "0xffffffffffffffff"
}},
"owner": "0x0000000000000000000000000000000000000000",
"signature": "{}",
"outputs": [{}]
}}"#,
permitted.join(","),
hex_string(sig_bytes),
outputs.join(",")
)
}

proptest! {
/// `deserialize_signature_bytes` accepts iff the decoded byte string
/// is exactly 65 bytes.
#[test]
fn signature_helper_accepts_only_65_bytes(bytes in prop::collection::vec(any::<u8>(), 0..200)) {
let json = format!(r#"{{"signature":"{}"}}"#, hex_string(&bytes));
match serde_json::from_str::<SigWrap>(&json) {
Ok(w) => prop_assert_eq!(w.signature.len(), 65),
Err(_) => prop_assert_ne!(bytes.len(), 65),
}
}

/// `deserialize_non_empty_vec` accepts iff the decoded vector is
/// non-empty.
#[test]
fn non_empty_vec_helper_rejects_empty(items in prop::collection::vec(any::<u64>(), 0..16)) {
let json = format!(
r#"{{"items":[{}]}}"#,
items.iter().map(u64::to_string).collect::<Vec<_>>().join(",")
);
match serde_json::from_str::<VecWrap>(&json) {
Ok(w) => prop_assert!(!w.items.is_empty()),
Err(_) => prop_assert!(items.is_empty()),
}
}

/// `SignedOrder` deserialization is total: any combination of
/// signature length, permitted count, and outputs count either
/// produces an `Ok` value satisfying all three structural
/// invariants, or an `Err`. It never panics.
#[test]
fn signed_order_deserialize_total(
sig_bytes in prop::collection::vec(any::<u8>(), 0..130),
permitted_count in 0usize..6,
outputs_count in 0usize..6,
) {
let json = signed_order_json(&sig_bytes, permitted_count, outputs_count);
match serde_json::from_str::<SignedOrder>(&json) {
Ok(order) => {
prop_assert_eq!(sig_bytes.len(), 65);
prop_assert!(permitted_count > 0);
prop_assert!(outputs_count > 0);
prop_assert_eq!(order.permit().signature.len(), 65);
prop_assert!(!order.permit().permit.permitted.is_empty());
prop_assert!(!order.outputs().is_empty());
// order_hash() must not panic on any value the
// Deserialize impl admits.
let _ = order.order_hash();
}
Err(_) => {
prop_assert!(
sig_bytes.len() != 65 || permitted_count == 0 || outputs_count == 0
);
}
}
}

/// Well-formed `SignedOrder` JSON survives a serde round-trip with a
/// stable `order_hash`.
#[test]
fn signed_order_roundtrip(
permitted_count in 1usize..6,
outputs_count in 1usize..6,
) {
let sig = vec![0u8; 65];
let json = signed_order_json(&sig, permitted_count, outputs_count);
let order: SignedOrder = serde_json::from_str(&json).unwrap();
let hash = *order.order_hash();
let reserialized = serde_json::to_string(&order).unwrap();
let decoded: SignedOrder = serde_json::from_str(&reserialized).unwrap();
prop_assert_eq!(decoded.order_hash(), &hash);
}
}

// Sanity check that arbitrary garbage JSON doesn't panic the
// deserializer — complements the structured proptests above by covering
// completely malformed shapes.
proptest! {
#[test]
fn arbitrary_string_never_panics(s in ".{0,256}") {
let _ = serde_json::from_str::<SignedOrder>(&s);
}
}
7 changes: 7 additions & 0 deletions crates/types/src/agg/fill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,13 @@ impl AggregateFills {
) -> Result<(), MarketError> {
self.check_aggregate(aggregate)?;

// SAFETY: the `check_aggregate` call above proves, for every
// `(output_asset, recipient)` pair in `aggregate`, that the entry
// exists in `self.fills` and that `filled >= amount`. We hold
// `&mut self` for the duration, so neither the map nor the
// recipient balances can change between the check and the
// mutation. The `get_mut`/`unwrap` and `checked_sub`/`unwrap`
// below are therefore infallible by construction.
Comment on lines +215 to +221
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude has spotted that this isn't really true. The following snippet probably explains the edge case best:

let mut context = AggregateFills::default();
let asset = Address::with_last_byte(1);
let present_recipient = Address::with_last_byte(99);
let missing_recipient = Address::with_last_byte(2);

// The outer `(chain, asset)` key exists in `self.fills`, but only `present_recipient` is in the inner map.
context.add_raw_fill(1, asset, present_recipient, U256::from(100));

// Zero-amount output to a recipient that is absent from `self.fills[(1, asset)]`.
// `check_aggregate` returns `Ok` here.
let mut aggregate = AggregateOrders::new();
aggregate.ingest_raw_output(1, asset, missing_recipient, U256::ZERO);

// Sanity check: the prior check the SAFETY comment leans on is currently a no-op for this input.
context.check_aggregate(&aggregate).unwrap();

// The unwrap inside `checked_remove_aggregate` panics here.
let _ = context.checked_remove_aggregate(&aggregate);

We probably want to tighten check_aggregate to fail for this case (and add a regression test)?

for (output_asset, recipients) in aggregate.outputs.iter() {
let context_recipients =
self.fills.get_mut(output_asset).expect("checked in check_aggregate");
Expand Down
6 changes: 6 additions & 0 deletions crates/types/src/agg/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ impl AggregateOrders {
token: *token,
amount: U256::from(*amount),
recipient: *recipient,
// SAFETY: signet chain IDs are protocol-defined to
// fit in `u32`; the on-chain `Output.chainId`
// field is itself `uint32`. A future protocol
// change permitting chain IDs above `u32::MAX`
// would require revisiting this cast and the
// contract type together.
chainId: ru_chain_id as u32,
});
}
Expand Down
Loading