Skip to content

feat(encryption): support ERC-7730 encryption scheme - #10

Merged
llbartekll merged 3 commits into
llbartekll:mainfrom
melanciani:feat/erc7730-encryption
Aug 13, 2026
Merged

llbartekll merged 3 commits into
llbartekll:mainfrom
melanciani:feat/erc7730-encryption

Conversation

@melanciani

Copy link
Copy Markdown
Contributor

Ported the sourcify PR's behavior (sourcifyeth/clear-signing#56) to Rust :

  • provider.rs — new DataProvider::resolve_decrypted_value(chain_id, encrypted_value_hex, scheme, contract_address) with a default returning None, mirroring resolveDecryptedValue.
    Default impl means no existing implementor (or the FFI wrapper) breaks.
  • engine.rs — the substance: decrypt_field_value calls the wallet, re-interprets the returned hex bytes via the descriptor's plaintextType (parse_plaintext_type → category + byte
    width), and format_value renders the plaintext with the field's normal format. On failure it renders fallbackLabel/[Encrypted]. Includes the Issue-1 width bounds check (> upper bound,
    honoring leading-zero stripping). Plus the field-level-encryption parsing plumbing.
  • outcome.rs — decryption_failed and encryption_invalid_descriptor diagnostic codes.
  • types/display.rs, standard_token.rs, eip712.rs — field-level encryption on Simple/Reference and pass-through.

Verification

  • New tests (tests/zama_encryption_integration.rs, 7 cases): decrypt→"1 cUSDC"; no-provider→[Encrypted Amount]; wallet-returns-None→fallback; invalid hex→decryption_failed;
    over-width→decryption_failed; no-fallbackLabel→[Encrypted]; bad plaintextType→encryption_invalid_descriptor. 7/7 pass.
  • Full existing suite: no regressions.
  • --features uniffi,github-registry: compiles clean (FFI unaffected).
  • Zama registry testsv2 via cs-test (no decryptor, exactly as CI runs): 16/16 pass — encrypted fields hit the fallback and match the fixtures.

Two deliberate divergences from the TS PR (Rust model differences)

  1. Malformed annotation degrades, not fatal. The TS engine aborts the whole format; Rust's per-field renderer can only return a string, so I emit an encryption_invalid_descriptor
    diagnostic + render the fallback rather than blanking the transaction. (Arguably the better behavior — and I flagged the TS abort as debatable anyway.)
  2. No rawEncryptedValue output. Rust's DisplayItem is just {label, value} (a uniffi::Record with 21 construction sites); adding a field is invasive and touches the Swift/Kotlin
    bindings. The core decrypt/fallback behavior is complete without it — worth a follow-up if you want the RECOMMENDED raw-value display.

result: Ported the wallet-delegated resolve_decrypted_value encryption model to the Rust fork on branch feat/erc7730-encryption (uncommitted, 6 files +281/−14 plus a new 7-case
integration test). Verified: 7/7 new tests pass, full suite no regressions, uniffi feature compiles, and the Zama registry testsv2 fixtures pass 16/16 via cs-test with no decryptor
(fallback path). Two documented divergences: malformed annotations degrade instead of aborting, and rawEncryptedValue output is omitted (invasive on the FFI DisplayItem).

🤖 Generated with Claude Code

@melanciani

Copy link
Copy Markdown
Contributor Author

hey @llbartekll , did you get the time to have a look at this ?

@melanciani
melanciani force-pushed the feat/erc7730-encryption branch from 59435d1 to 9a29cb3 Compare July 30, 2026 20:24
@melanciani

melanciani commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor Author

hey again @llbartekll , without this feature, new integration like ethereum/clear-signing-erc7730-registry#2595 have failing tests. Would it be possible to have a look at this PR ? thanks !

@llbartekll llbartekll left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for porting this feature. I ran cargo fmt --check, the full test suite, the UniFFI/GitHub-registry feature tests, and Clippy with warnings denied; the existing checks pass. I am requesting changes because the wallet-facing callback plumbing is incomplete and targeted regression cases expose incorrect or inconsistent clear-signing output. In particular: Swift/Kotlin and CompositeDataProvider cannot reach the decryptor, an encrypted interpolated field is decrypted twice, signed intN values can be rendered with the wrong sign, visibility is evaluated on ciphertext, and EIP-712 never attempts decryption. Please address the inline findings and add coverage for these paths before merging.

/// re-interprets it via the descriptor's declared `plaintextType`. Return
/// `None` when the value cannot be decrypted (unsupported scheme, declined
/// signature, no access) — the field then renders its `fallbackLabel`.
fn resolve_decrypted_value(

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Please wire this callback through every public provider adapter before merging. DataProviderFfi has no corresponding method, so DataProviderFfiProxy inherits this default None; CompositeDataProvider also does not delegate it. Consequently every Swift/Kotlin integration, and any Rust decryptor wrapped in CompositeDataProvider, always renders the fallback even when the wallet can decrypt. Please add the FFI bridge/generated bindings, composite first-success delegation, and end-to-end tests.

// When decryption is unavailable the field renders its `fallbackLabel`; a
// malformed annotation degrades the same way, distinguished by diagnostic.
let decrypted_owned;
if let Some(enc) = params.and_then(|p| p.encryption.as_ref()) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This decryption runs inside format_value, which is invoked once while rendering entries and again when the same field appears in interpolatedIntent. The target Zama registry descriptor does interpolate the encrypted amount. A provider returning 0x2a and then None produces an entry of 42 but an intent containing [Encrypted], while an interactive provider may prompt twice and the second warning is discarded. Please decrypt once and reuse/cache that result for both outputs.

fn build_plaintext_value(kind: PlainKind, bytes: Vec<u8>) -> ArgumentValue {
match kind {
PlainKind::Uint => ArgumentValue::Uint(bytes),
PlainKind::Int => ArgumentValue::Int(bytes),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

The declared intN width is lost here. For plaintextType int64, the valid minimal positive encoding 0xc8 reaches int_to_bigint as a one-byte signed value and renders as -56 instead of 200. Preserve the declared bit width during signed conversion, and add tests for a positive top-bit-set value, a full-width value, and negative values.

if let Some(ref enc) = params.encryption {
if let Some(ref fallback) = enc.fallback_label {
return Ok(fallback.clone());
// Encryption (ERC-7730 `encryption`): decrypt via the wallet, then render the

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Decryption occurs too late for conditional visibility: render_fields and the group/array variants call check_visibility on the ciphertext before reaching format_value. A decrypted value of 200 with visible.mustMatch [200] currently fails as InvalidDescriptor before the provider is even called; ifNotIn is likewise evaluated against the handle. Resolve/decrypt once before conditional visibility, then pass the same plaintext through formatting and interpolation.

Comment thread crates/clear-signing/src/eip712.rs Outdated
};

// Check encryption fallback
// Check encryption fallback — opaque handle, cannot decrypt here.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

The typed-data path never invokes resolve_decrypted_value: it immediately returns the fallback and does not emit decryption_failed. Thus even a capable Rust provider cannot decrypt an encrypted EIP-712 field, which breaks the repository's calldata/EIP-712 parity guardrail. Please share the decryption/coercion path with calldata using the typed container chainId and verifyingContract, and add parity tests.

@melanciani

Copy link
Copy Markdown
Contributor Author

hey @llbartekll , thanks for the review, I've just pushed new changes to take into account your comments but also align this PR a bit more with what was included in sourcifyeth/clear-signing#56. I've made some additional decisions that led to further changes, so please let me know if some are not relevant.

Here is a summary:

Review fixes

  1. Wallet callback wasn't reachable — resolve_decrypted_value added to DataProviderFfi
    and bridged in DataProviderFfiProxy; CompositeDataProvider now delegates it first-success
    (and resolve_block_timestamp, which had the same gap). Swift bindings + FFI header
    regenerated; WalletMetadataProvider.swift and the Kotlin smoke consumer updated. Covered by
    an end-to-end test through clear_signing_format_calldata and a composite delegation test.

  2. Field decrypted twice — decryptions are memoized per render frame (DecryptionCache,
    keyed by ciphertext + scheme + plaintextType) on RenderContext and TypedContainerContext;
    nested calldata frames get their own. Test: a wallet scripted to answer Some then None
    yields entry and interpolatedIntent = 1 cUSDC with exactly one wallet call.

  3. Declared intN width lost — new encryption.rs fits the plaintext to the declared width,
    then normalizes integers to a 32-byte two's-complement word (the representation the decoder
    already produces). 0xc8 under int64 is +200; full-width and negative values round-trip.
    Only 0x00 padding is stripped, so a negative must arrive at its full declared width — the
    same rule as the TS library.

  4. Visibility evaluated on ciphertext — conditional rules now see the plaintext, via shared
    is_field_visible / is_typed_field_visible at all eight render sites (scalar, array, group ×
    both containers). Rules that don't inspect the value never trigger decryption, so a hidden
    field causes no wallet prompt.

  5. EIP-712 never decrypted — typed data takes the same path, sharing encryption.rs, using
    the domain's chainId and EIP-55-checksummed verifyingContract. Parity tests in
    spec_compliance.rs assert identical rendering, diagnostics and callback arguments across both
    containers, for decrypt and fallback.

Also aligned with sourcifyeth/clear-signing#56 (now merged)

  • DisplayItem.raw_encrypted_value reports the handle on success and on fallback (the spec
    RECOMMENDS showing it beside the placeholder).
  • A malformed encryption annotation (missing scheme/plaintextType, non-canonical type) is a
    descriptor bug: FormatFailure::InvalidDescriptor, validated even for hidden fields, instead of
    silently rendering the fallback. The encryption_invalid_descriptor diagnostic code is removed
    as a consequence.
  • The decryption-failed message names both causes ("no decryptor, or the wallet declined"), since
    a Rust DataProvider always has the method and can't distinguish them.

Consumer-visible changes

  • FFI: DataProviderFfi gains one method, DisplayItem gains one field → Kotlin needs
    regenerating (Swift is committed). Wallets only read DisplayItem, so that side is additive.
  • A descriptor with a malformed annotation now fails to format instead of rendering a fallback.

Verification

  • cargo fmt --check and clippy --all-targets -D warnings clean on default and
    uniffi,github-registry.
  • Tests: 436 (default) / 419 (uniffi) pass, vs 409 / 392 at the previous commit. Every
    pre-existing test still passes; the only removed name is
    invalid_descriptor_for_unsupported_plaintext_type, rewritten for the new fatal behaviour.
  • Registry testsv2: all 275 fixture files, 532/534 cases — byte-identical per-file results to
    the previous commit. The two failures (rarible EIP-712 meta-tx, flyingtulip enum mapping)
    pre-date this work and are unrelated to encryption.

Remaining known divergences from TS

  • Rust hard-fails on a descriptor error where TS degrades to a raw calldata preview — that's
    Rust's existing policy for every Error::Descriptor, not encryption-specific.
  • On a failed decryption, conditional visibility sees None rather than the handle (same outcome
    for both ifNotIn and mustMatch), and hidden encrypted fields are never decrypted (TS
    decrypts, then discards the result with the field). Both deliberate: same output, fewer prompts.

@llbartekll
llbartekll merged commit fe2cedc into llbartekll:main Aug 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants