From 73465489a70e452a027e57b8a998563c6c2c7253 Mon Sep 17 00:00:00 2001 From: Manuel Wedler Date: Wed, 9 Sep 2026 17:31:40 +0200 Subject: [PATCH] Compare mustMatch/ifNotIn values numerically and keep hidden bundle slots - Decimal strings and JSON numbers in visible.mustMatch / visible.ifNotIn now compare as integers against decoded calldata words and EIP-712 message values. Signed ints compare as two's complement. - Hex literals compare case-insensitively so checksummed addresses match lowercase decoded addresses. - Hidden array elements inside a group keep an empty bundle slot, so bundled groups with mustMatch or never fields no longer fail the equal-length check in both the calldata and EIP-712 engines. Ref: ethereum/clear-signing-erc7730-registry#2598 --- CLAUDE.md | 2 + crates/clear-signing/src/eip712.rs | 2 + crates/clear-signing/src/engine.rs | 13 +- crates/clear-signing/src/types/display.rs | 107 ++++- crates/clear-signing/tests/spec_compliance.rs | 378 ++++++++++++++++++ 5 files changed, 494 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 408495a..2fdd681 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -159,6 +159,8 @@ The library supports v2 registry descriptor features: - **Unit SI prefix**: `prefix: true` enables k/M/G/T notation - **Maps `keyPath`**: Cross-field key resolution for map lookups - **`excluded` paths**: Deprecated v1 field now functional in rendering +- **`mustMatch`/`ifNotIn` value comparison**: Decimal strings and JSON numbers compare numerically against decoded words (signed ints as two's complement); hex literals compare case-insensitively so checksummed addresses match +- **Hidden fields in `bundled` groups**: A hidden array element keeps an empty slot, so `mustMatch`/`never` fields inside a bundled group do not break bundle alignment - **Intent as object**: `intent` can be string or `{"label": "..."}` object - **Interpolation escape sequences**: `{{` and `}}` produce literal braces - **Encryption (`encryption`)**: wallet-delegated decryption via `DataProvider::resolve_decrypted_value` (calldata and EIP-712 alike, sharing `encryption.rs`; behaviour mirrors the TypeScript library). The plaintext is re-read as the declared `plaintextType` — integers normalized to a 32-byte two's-complement word so `intN` keeps its sign, negatives required at full declared width, only `0x00` padding stripped — then rendered with the field's normal format. Decrypted once per value per render (memoized, so entry / `interpolatedIntent` / conditional visibility agree and the wallet prompts once); conditional `visible` rules see the plaintext, never the handle. A wallet that cannot decrypt renders `fallbackLabel` (or `[Encrypted]`) with a `decryption_failed` diagnostic, and `DisplayItem.raw_encrypted_value` reports the handle either way (spec RECOMMENDS showing it). A malformed annotation (no `scheme`/`plaintextType`, non-canonical type) is a descriptor bug: `Error::Descriptor` → `FormatFailure::InvalidDescriptor`, validated even for hidden fields diff --git a/crates/clear-signing/src/eip712.rs b/crates/clear-signing/src/eip712.rs index 473a58f..58f0e36 100644 --- a/crates/clear-signing/src/eip712.rs +++ b/crates/clear-signing/src/eip712.rs @@ -569,6 +569,8 @@ fn render_typed_group_field_kind<'a>( ) .await? { + // Keep the slot so bundled groups stay aligned. + bundles.push(Vec::new()); continue; } let rendered = if matches!(format.as_ref(), Some(FieldFormat::Calldata)) diff --git a/crates/clear-signing/src/engine.rs b/crates/clear-signing/src/engine.rs index 86bc4f0..6a0b4ef 100644 --- a/crates/clear-signing/src/engine.rs +++ b/crates/clear-signing/src/engine.rs @@ -487,6 +487,8 @@ fn render_group_field_kind<'a>( ) .await? { + // Keep the slot so bundled groups stay aligned. + bundles.push(Vec::new()); continue; } let rendered = if matches!(format.as_ref(), Some(FieldFormat::Calldata)) @@ -1201,6 +1203,15 @@ fn visibility_context(label: &str, path: &str) -> String { } } +/// JSON value used for `visible` comparisons. Signed integers become +/// decimal strings so `mustMatch: ["-1"]` matches a negative value. +fn visibility_json_value(val: &ArgumentValue) -> serde_json::Value { + match val { + ArgumentValue::Int(bytes) => serde_json::Value::String(int_to_bigint(bytes).to_string()), + _ => val.to_json_value(), + } +} + /// Check if a field should be visible based on the visibility rule and decoded value. fn check_visibility( rule: &VisibleRule, @@ -1226,7 +1237,7 @@ fn check_visibility( return Ok(true); }; - let json_val = val.to_json_value(); + let json_val = visibility_json_value(val); if cond.hides_for_if_not_in(&json_val) { return Ok(false); } diff --git a/crates/clear-signing/src/types/display.rs b/crates/clear-signing/src/types/display.rs index a383424..c34939a 100644 --- a/crates/clear-signing/src/types/display.rs +++ b/crates/clear-signing/src/types/display.rs @@ -1,6 +1,6 @@ //! Display configuration types: field formats, visibility rules, and layout groups. -use num_bigint::BigUint; +use num_bigint::{BigInt, BigUint, Sign}; use serde::{de, Deserialize, Deserializer, Serialize}; use std::collections::HashMap; @@ -238,15 +238,108 @@ pub struct VisibleCondition { impl VisibleCondition { pub fn hides_for_if_not_in(&self, value: &serde_json::Value) -> bool { - self.if_not_in - .as_ref() - .is_some_and(|excluded| excluded.contains(value)) + self.if_not_in.as_ref().is_some_and(|excluded| { + excluded + .iter() + .any(|expected| visibility_values_equal(expected, value)) + }) } pub fn matches_must_match(&self, value: &serde_json::Value) -> bool { - self.must_match - .as_ref() - .is_none_or(|required| required.contains(value)) + self.must_match.as_ref().is_none_or(|required| { + required + .iter() + .any(|expected| visibility_values_equal(expected, value)) + }) + } +} + +/// Integer parsed from a visibility value. +enum VisibilityInt { + /// Decimal literal, possibly negative. + Decimal(BigInt), + /// Hex literal with its bit width. + Hex(BigUint, u64), +} + +fn parse_visibility_int(text: &str) -> Option { + if let Some(hex_digits) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) { + let bytes = hex::decode(hex_digits).ok()?; + return Some(VisibilityInt::Hex( + BigUint::from_bytes_be(&bytes), + hex_digits.len() as u64 * 4, + )); + } + if !text + .strip_prefix('-') + .unwrap_or(text) + .bytes() + .all(|b| b.is_ascii_digit()) + { + return None; + } + text.parse::().ok().map(VisibilityInt::Decimal) +} + +fn visibility_scalar_text(value: &serde_json::Value) -> Option { + match value { + serde_json::Value::String(s) => Some(s.clone()), + serde_json::Value::Number(n) => Some(n.to_string()), + serde_json::Value::Bool(b) => Some(b.to_string()), + _ => None, + } +} + +fn is_hex_literal(text: &str) -> bool { + text.starts_with("0x") || text.starts_with("0X") +} + +/// Interpret a hex literal as two's complement of its own bit width. +fn hex_as_signed(magnitude: &BigUint, bits: u64) -> BigInt { + let signed = BigInt::from(magnitude.clone()); + if bits > 0 && magnitude.bit(bits - 1) { + signed - (BigInt::from(1) << bits) + } else { + signed + } +} + +/// Compare a descriptor `mustMatch` / `ifNotIn` value with a decoded value. +/// +/// Hex literals compare case-insensitively, so checksummed addresses match +/// lowercase decoded addresses. A decimal literal (string or JSON number) +/// compares as an integer against a hex word or another decimal. A negative +/// decimal reads a hex word as two's complement. +fn visibility_values_equal(expected: &serde_json::Value, actual: &serde_json::Value) -> bool { + if expected == actual { + return true; + } + let (Some(expected), Some(actual)) = ( + visibility_scalar_text(expected), + visibility_scalar_text(actual), + ) else { + return false; + }; + if is_hex_literal(&expected) && is_hex_literal(&actual) { + return expected.eq_ignore_ascii_case(&actual); + } + let (Some(expected), Some(actual)) = ( + parse_visibility_int(&expected), + parse_visibility_int(&actual), + ) else { + return false; + }; + match (expected, actual) { + (VisibilityInt::Decimal(a), VisibilityInt::Decimal(b)) => a == b, + (VisibilityInt::Decimal(dec), VisibilityInt::Hex(mag, bits)) + | (VisibilityInt::Hex(mag, bits), VisibilityInt::Decimal(dec)) => { + if dec.sign() == Sign::Minus { + hex_as_signed(&mag, bits) == dec + } else { + BigInt::from(mag) == dec + } + } + (VisibilityInt::Hex(..), VisibilityInt::Hex(..)) => false, } } diff --git a/crates/clear-signing/tests/spec_compliance.rs b/crates/clear-signing/tests/spec_compliance.rs index 14eab5a..1956b28 100644 --- a/crates/clear-signing/tests/spec_compliance.rs +++ b/crates/clear-signing/tests/spec_compliance.rs @@ -6583,3 +6583,381 @@ async fn test_eip712_encryption_falls_back_like_calldata() { ); } } + +#[tokio::test] +async fn test_visible_must_match_compares_decimal_and_checksummed_address() { + let descriptor = Descriptor::from_json( + r#"{ + "context": { "contract": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": { "owner": "test", "enums": {}, "constants": {}, "maps": {} }, + "display": { + "definitions": {}, + "formats": { + "show(uint8 kind,address zone,uint256 value)": { + "intent": "Show", + "fields": [ + { "path": "kind", "label": "Kind", "format": "raw", "visible": { "mustMatch": ["2", "3"] } }, + { "path": "zone", "label": "Zone", "format": "address", "visible": { "mustMatch": ["0xAbCdEf0000000000000000000000000000000001"] } }, + { "path": "value", "label": "Value", "format": "number" } + ] + } + } + } + }"#, + ) + .unwrap(); + + let calldata = build_calldata( + "show(uint8,address,uint256)", + &[ + uint_word(2), + addr_word("0xabcdef0000000000000000000000000000000001"), + uint_word(5), + ], + ); + let tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &calldata, + value: None, + from: None, + implementation_address: None, + }; + let result = format_calldata( + &wrap_rd(descriptor.clone(), 1, "0xabc"), + &tx, + &EmptyDataProvider, + ) + .await + .unwrap(); + assert_eq!(result.entries.len(), 1); + match &result.entries[0] { + DisplayEntry::Item(item) => assert_eq!(item.label, "Value"), + _ => panic!("expected Item"), + } + + let mismatching = build_calldata( + "show(uint8,address,uint256)", + &[ + uint_word(4), + addr_word("0xabcdef0000000000000000000000000000000001"), + uint_word(5), + ], + ); + let mismatching_tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &mismatching, + value: None, + from: None, + implementation_address: None, + }; + let err = format_calldata( + &wrap_rd(descriptor, 1, "0xabc"), + &mismatching_tx, + &EmptyDataProvider, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("visible.mustMatch")); +} + +#[tokio::test] +async fn test_visible_if_not_in_compares_json_number_with_decoded_uint() { + let descriptor = Descriptor::from_json( + r#"{ + "context": { "contract": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": { "owner": "test", "enums": {}, "constants": {}, "maps": {} }, + "display": { + "definitions": {}, + "formats": { + "show(uint256 value)": { + "intent": "Show", + "fields": [ + { "path": "value", "label": "Value", "format": "number", "visible": { "ifNotIn": [0] } } + ] + } + } + } + }"#, + ) + .unwrap(); + + let hidden = build_calldata("show(uint256)", &[uint_word(0)]); + let hidden_tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &hidden, + value: None, + from: None, + implementation_address: None, + }; + let hidden_result = format_calldata( + &wrap_rd(descriptor.clone(), 1, "0xabc"), + &hidden_tx, + &EmptyDataProvider, + ) + .await + .unwrap(); + assert!(hidden_result.entries.is_empty()); + + let shown = build_calldata("show(uint256)", &[uint_word(7)]); + let shown_tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &shown, + value: None, + from: None, + implementation_address: None, + }; + let shown_result = format_calldata( + &wrap_rd(descriptor, 1, "0xabc"), + &shown_tx, + &EmptyDataProvider, + ) + .await + .unwrap(); + assert_eq!(shown_result.entries.len(), 1); +} + +#[tokio::test] +async fn test_visible_must_match_compares_signed_int_as_decimal() { + let descriptor = Descriptor::from_json( + r#"{ + "context": { "contract": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": { "owner": "test", "enums": {}, "constants": {}, "maps": {} }, + "display": { + "definitions": {}, + "formats": { + "show(int256 delta,int256 mask,uint256 value)": { + "intent": "Show", + "fields": [ + { "path": "delta", "label": "Delta", "format": "number", "visible": { "mustMatch": ["-1"] } }, + { "path": "mask", "label": "Mask", "format": "number", "visible": { "mustMatch": ["0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"] } }, + { "path": "value", "label": "Value", "format": "number" } + ] + } + } + } + }"#, + ) + .unwrap(); + + let calldata = build_calldata( + "show(int256,int256,uint256)", + &[[0xffu8; 32], [0xffu8; 32], uint_word(5)], + ); + let tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &calldata, + value: None, + from: None, + implementation_address: None, + }; + let result = format_calldata(&wrap_rd(descriptor, 1, "0xabc"), &tx, &EmptyDataProvider) + .await + .unwrap(); + assert_eq!(result.entries.len(), 1); + match &result.entries[0] { + DisplayEntry::Item(item) => assert_eq!(item.label, "Value"), + _ => panic!("expected Item"), + } +} + +#[tokio::test] +async fn test_typed_visibility_must_match_compares_string_and_number() { + let descriptor = Descriptor::from_json( + r#"{ + "context": { "eip712": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": { "owner": "test", "enums": {}, "constants": {}, "maps": {} }, + "display": { + "definitions": {}, + "formats": { + "Permit(uint8 kind,address zone,uint256 value)": { + "intent": "Permit", + "fields": [ + { "path": "kind", "label": "Kind", "format": "raw", "visible": { "mustMatch": [1, "0x02"] } }, + { "path": "zone", "label": "Zone", "format": "address", "visible": { "mustMatch": ["0xAbCdEf0000000000000000000000000000000001"] } }, + { "path": "value", "label": "Value", "format": "number" } + ] + } + } + } + }"#, + ) + .unwrap(); + + let typed_data: TypedData = serde_json::from_value(serde_json::json!({ + "types": { + "EIP712Domain": [], + "Permit": [ + { "name": "kind", "type": "uint8" }, + { "name": "zone", "type": "address" }, + { "name": "value", "type": "uint256" } + ] + }, + "primaryType": "Permit", + "domain": { "chainId": 1, "verifyingContract": "0xabc" }, + "message": { + "kind": "2", + "zone": "0xabcdef0000000000000000000000000000000001", + "value": "9" + } + })) + .unwrap(); + + let result = format_typed_data( + &wrap_rd(descriptor, 1, "0xabc"), + &typed_data, + &EmptyDataProvider, + ) + .await + .unwrap(); + assert_eq!(result.entries.len(), 1); + match &result.entries[0] { + DisplayEntry::Item(item) => assert_eq!(item.label, "Value"), + _ => panic!("expected Item"), + } +} + +#[tokio::test] +async fn test_calldata_bundled_group_keeps_hidden_array_elements_aligned() { + let json = r#"{ + "context": { "contract": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": {"owner": "test", "enums": {}, "constants": {}, "maps": {}}, + "display": { + "definitions": {}, + "formats": { + "batch(address[] recipients,uint256[] amounts)": { + "intent": "Batch", + "fields": [{ + "label": "Transfers", + "iteration": "bundled", + "fields": [ + { + "path": "recipients.[]", + "label": "Recipient", + "format": "address", + "visible": { "mustMatch": ["0x0000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000002"] } + }, + {"path": "amounts.[]", "label": "Hidden amount", "format": "number", "visible": "never"}, + {"path": "amounts.[]", "label": "Amount", "format": "number"} + ] + }] + } + } + } + }"#; + + let descriptor = Descriptor::from_json(json).unwrap(); + let calldata = build_two_array_calldata( + "batch(address[],uint256[])", + &[ + "0x0000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000002", + ], + &[100, 200], + ); + let tx = TransactionContext { + chain_id: 1, + to: "0xabc", + calldata: &calldata, + value: None, + from: None, + implementation_address: None, + }; + + let result = format_calldata(&wrap_rd(descriptor, 1, "0xabc"), &tx, &EmptyDataProvider) + .await + .unwrap(); + match &result.entries[0] { + DisplayEntry::Group { + iteration, items, .. + } => { + assert!(matches!(iteration, GroupIteration::Bundled)); + assert_eq!(items.len(), 2); + assert_eq!(items[0].label, "Amount"); + assert_eq!(items[0].value, "100"); + assert_eq!(items[1].label, "Amount"); + assert_eq!(items[1].value, "200"); + } + _ => panic!("expected bundled group"), + } +} + +#[tokio::test] +async fn test_eip712_bundled_group_keeps_hidden_array_elements_aligned() { + let descriptor = Descriptor::from_json( + r##"{ + "context": { "eip712": { "deployments": [{"chainId": 1, "address": "0xabc"}] } }, + "metadata": { "owner": "test", "enums": {}, "constants": {}, "maps": {} }, + "display": { + "definitions": {}, + "formats": { + "Batch(Tip[] tips)Tip(uint8 itemType,address token,uint256 amount,address recipient)": { + "intent": "Batch", + "fields": [{ + "label": "Tips", + "iteration": "bundled", + "fields": [ + { "path": "tips.[].itemType", "label": "Tip type", "format": "raw", "visible": { "mustMatch": ["1", "2"] } }, + { "path": "tips.[].token", "label": "Tip token", "format": "address", "visible": "never" }, + { "path": "tips.[].amount", "label": "Tip amount", "format": "number" }, + { "path": "tips.[].recipient", "label": "Tip to", "format": "address" } + ] + }] + } + } + } + }"##, + ) + .unwrap(); + + let typed_data: TypedData = serde_json::from_value(serde_json::json!({ + "types": { + "EIP712Domain": [], + "Batch": [{ "name": "tips", "type": "Tip[]" }], + "Tip": [ + { "name": "itemType", "type": "uint8" }, + { "name": "token", "type": "address" }, + { "name": "amount", "type": "uint256" }, + { "name": "recipient", "type": "address" } + ] + }, + "primaryType": "Batch", + "domain": { "chainId": 1, "verifyingContract": "0xabc" }, + "message": { + "tips": [{ + "itemType": "1", + "token": "0x0000000000000000000000000000000000000001", + "amount": "100", + "recipient": "0x0000000000000000000000000000000000000002" + }] + } + })) + .unwrap(); + + let result = format_typed_data( + &wrap_rd(descriptor, 1, "0xabc"), + &typed_data, + &EmptyDataProvider, + ) + .await + .unwrap(); + match &result.entries[0] { + DisplayEntry::Group { + label, + iteration, + items, + } => { + assert_eq!(label, "Tips"); + assert!(matches!(iteration, GroupIteration::Bundled)); + assert_eq!(items.len(), 2); + assert_eq!(items[0].label, "Tip amount"); + assert_eq!(items[1].label, "Tip to"); + } + _ => panic!("expected bundled group"), + } +}