Skip to content

feat(keystore): sealed signing (TWStoredKeySign*) for EVM, UTXO, Tron, Solana with error codes — Security Layer S2.1 - #4845

Merged
PandaXadnaP merged 33 commits into
masterfrom
feat/s2.1-storedkey-sealed-sign
Dec 3, 2026
Merged

PandaXadnaP merged 33 commits into
masterfrom
feat/s2.1-storedkey-sealed-sign

Conversation

@PandaXadnaP

@PandaXadnaP PandaXadnaP commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Security Layer — Phase 2 (sealed signing), S2.1

Lets the app sign with a TWPrivateKey handle, so the private key bytes never have to reach Kotlin, Swift or JS, where they can't be wiped. The app gets the handle from the existing keystore API (StoredKey.privateKey(coin, password) or HDWallet.getKey(coin, path)), passes it with a key-less SigningInput or a message, and gets back only the signed output. The key stays in the C++ PrivateKey, which is wiped when the handle is deleted, and only leaves the library if the caller reads PrivateKey.data.

This implements the signing part of Phase 2 (Epic 151885 / SC-149301, Epic 185507) for the Top-8 chains: every EVM coin, the BitcoinV2 UTXO family, Tron (SC-187659) and Solana (SC-187660), plus the message types the app signs today that had no TWPrivateKey API.

The first version took a StoredKey + address + password and did the account lookup, decryption and error mapping inside wallet-core. Per review, it was replaced by the handle API (#4964, #4963), which reuses the existing keystore functions and removes that layer.

API

  • TWAnySignerSignWithPrivateKey(input, coin, key) — signs a SigningInput that carries no key of its own with key. Returns the SigningOutput exactly as TWAnySignerSign does (a chain error stays in its error field), or null if the coin is unsupported, the input doesn't parse, or the input carries a key.
    • EVM coins: Ethereum.SigningInput with an empty private_key.
    • UTXO coins (Bitcoin, Litecoin, Dogecoin, Bitcoin Cash, Dash, Viacoin, DigiByte, Ravencoin, Firo, Qtum, Zcash, Flux, Groestlcoin, Decred): Bitcoin.SigningInput with signing_v2 set, coin_type == coin, and no keys in private_key or signing_v2.private_keys. The key is injected into signing_v2.private_keys (single-address model).
    • Tron: Tron.SigningInput with transaction or raw_json and an empty private_key. raw_json keeps the signer's txID / raw_data_hex checks.
    • Solana: Solana.SigningInput, including raw_message. private_key, fee_payer_private_key and create_nonce_account.nonce_account_private_key must be empty.
  • Messages that had no TWPrivateKey API:
    • TWEthereumMessageSignerSignBizUserOpHash(key, …) — the Biz smart-account hash, with sender fixed to the key's own address, so a signature can only authorize that account's operations.
    • TWEthereumMessageSignerSignEip7702Authorization(key, chainId, contract, nonce) — the same JSON as TWEip7702SignAuthorization, without passing the key as a hex string.
    • TWSolanaMessageSignerSignMessage(key, message) — raw ed25519 over the message bytes, as the app signs dApp messages. Bytes that are exactly a Solana transaction message are refused, so it never produces a transaction signature.
    • personal_sign, EIP-712 and Tron messages use the existing TWEthereumMessageSigner* / TWTronMessageSignerSignMessage, which already take a TWPrivateKey.
  • TWSolanaTransactionIsTransactionMessage(message) — the app's transaction-message rule (SC-140951), implemented on the Rust Solana decoder and exposed so the app can drop its own TS/Kotlin copies. It returns true for an unreadable pointer, so a caller that refuses transaction messages fails closed.
  • Bindings: Swift AnySigner.nativeSignWithPrivateKey(data:coin:key:), Java AnySigner.signWithPrivateKey(input, coin, key, parser); the message functions are generated as usual.

Implementation

  • C++ CoinEntry::supportsSigningWithPrivateKey() / signWithPrivateKey(coin, input, key, output) (default: not supported), implemented for Ethereum, Solana, the BitcoinV2 entries, Decred and Tron; Rust CoinEntry::set_private_key and the FFI tw_any_signer_sign_with_private_key for the chains signed in Rust. Each path rejects an input that already carries a key, injects the key, signs, and wipes the injected copy.
  • Fewer key copies left in memory on the signing paths: Rust FFI TWData / TWString zeroize on drop and free_string wipes before freeing; PrivateKey::sign / getPublicKey read the key in place instead of through temporary copies; the serialized Ethereum message input and the Biz / EIP-7702 hex key are wiped, and so is the derived scrypt key when decryption fails on an invalid cipher; TWStoredKey* reads the password in place.

Notes for the SDK

  • Call delete() on the PrivateKey (and HDWallet) right after signing. Kotlin/Java handles are otherwise only freed, and wiped, when the GC runs; WASM handles must always be deleted. Swift frees them deterministically.
  • Never read PrivateKey.data on this path: it copies the key into an immutable, non-wiped byte array.
  • Failures are null, with no error code. Wrong password / decryption errors come from StoredKey.privateKey (null) before signing.
  • wallet-core no longer checks that the key matches an expected address. If the SDK needs that guarantee, compare coin.deriveAddress(key) with the address it expects.

Tests

  • C++ tests/chains/{Ethereum,Bitcoin,Tron,Solana}/TWSealedSignerTests.cpp (UTXO: Bitcoin, Litecoin, Bitcoin Cash, Groestlcoin, Zcash, Decred): each result is compared byte for byte with signing the same input with the key bytes through the existing API, plus every refusal (input with a key, invalid input, transaction message).
  • Rust: sign-with-key tests for Ethereum, Solana and Bitcoin P2WPKH; solana_transaction_message_ffi.rs covers the app parity vectors (solana-transaction-message.parity.test.ts), a wallet-core-built message (refused) and the same message padded by one byte (signed), an alias-encoded length, and a null pointer (fails closed).
  • Swift SignWithPrivateKeyTests.swift: the same comparisons through the generated bindings.

Verification (on d2bbdd7ef)

  • C++ full suite 2392/2392.
  • Rust full suite, cargo fmt --check and clippy -D warnings.
  • Swift (iOS simulator) 620/620.
  • Kotlin tools/kotlin-build.

Scope / known limitations

  • Taproot is not covered by the byte-identical tests (Schnorr signatures use aux randomness). Verify it by signature validity and on-chain acceptance.
  • EIP-7702 delegation is not restricted. The key signs a delegation to whatever contract the caller supplies, as in today's flow. An allowlist of Biz delegate addresses is deferred.
  • Only the single-address UTXO model is supported.
  • Not covered: EIP-155 message variants (no app caller), Tron raw_data_hex blind signing, TON, XRP. Kotlin KMP and WASM typed signWithPrivateKey wrappers are not added yet.
  • Before default-on: end-to-end in the host app, and broadcasts on Tron Nile / Solana devnet / a Taproot testnet.

No existing behavior changes: this only adds new API, none of which has been released.

@PandaXadnaP
PandaXadnaP requested review from a team and BSCSecChef as code owners August 18, 2026 09:56
@octane-security-app

Copy link
Copy Markdown

Summary by Octane

New Contracts

  • SealedSigner.cpp: The smart contract enables Ethereum signing by decrypting and injecting private keys into signing inputs, ensuring security through key wiping.

Updated Contracts

No contracts were updated.


🔗 Commit Hash: 53fb9f4

@github-actions

Copy link
Copy Markdown

⚠️ Backward-compatibility check needed

This PR touches persistence-sensitive files: include/TrustWalletCore/TWStoredKey.h, src/Keystore/SealedSigner.cpp, src/Keystore/SealedSigner.h.

Post a comment with one of:

  • [bc-check: Pass] — audit run, Verdict: SAFE. Must include audit output.
  • [bc-check: Mitigated] — audit found RISK or BLOCKER; you fixed it in code. Must include the post-fix audit output.
  • [bc-check: Risk-Accepted] — audit found RISK or BLOCKER; investigation confirms blast radius is effectively zero (no user data in the wild can trigger it). Must include audit output + explicit evidence (who confirmed it, what data or reasoning).
  • [bc-check: N/A] — scanner fired on a file with zero BC relevance (comment edit, test fixture, renamed variable). Invalid if the audit found a real risk.

Each token must be accompanied by >=60 chars of reasoning. The reasoning must be fresh — posted or edited at or after the HEAD commit.

Why audit evidence is required for Pass / Mitigated: humans don't reliably ask the right BC question on every PR. AI being in the loop is the whole point of this gate. The bot does not judge whether your reasoning is correct — reviewers do, like any other code review.

Things worth thinking about: could a previous version have written data this PR's new check would now reject? Was there a partial migration ("regenerate on next user action") that may not have completed for all users? Does this format live in iCloud / Google Drive backup, exported files, or sync payloads? See docs/bc-footguns.md for known cases.

Changed files (3)
  • include/TrustWalletCore/TWStoredKey.h
  • src/Keystore/SealedSigner.cpp
  • src/Keystore/SealedSigner.h
Copy this audit prompt into Claude Code on this branch (or run the /bc-check skill) for a structured analysis you can paste into your sign-off
You are auditing a Trust Wallet Core PR against origin/master
for **backward-compatibility risk against persisted user data and wire formats**.
Find cases where this PR will reject, mis-parse, or mishandle inputs that older
versions of our software already wrote to disk, to backups, or onto the network.

**Trust Wallet Core domain context:**
- src/Keystore/ — JSON keystore files (user encrypted keys/mnemonics).
  These live in iCloud, Google Drive, and manual exports.
  A parse failure = wallet inaccessible = user cannot access funds.
- src/proto/*.proto — Protobuf SigningInput/SigningOutput wire formats.
  Field numbers are permanent; reuse or removal silently corrupts binary data.
- include/TrustWalletCore/TW*.h — Public C ABI.
  Removing/renaming TW* functions or changing enum values breaks compiled bindings.
- registry.json — coin metadata (SLIP44, derivation path, curve, address encoding).
  Changing any of these re-derives different addresses for all existing wallets.

Do NOT trust the PR description's framing.
'Just a security fix' / 'stricter validation' is exactly the framing that hides this class of bug.
Read docs/bc-footguns.md first.

Walk these 5 steps. Cite file:line and commit SHA everywhere:

1. Classify: tightening validation? Parsing change? Exception type change?
   Removing 'if missing use default'? Moving validation into a constructor?
2. Historical baseline. For each tightened rule:
   - Could a prior version have PRODUCED data that violates the new rule? (cite SHA)
   - Was there a partial migration that may not have completed for all users?
   - Does the format ever leave the device (backup, export, sync)?
3. Concrete failure scenarios: old version -> action -> where stored -> code path
   (file:line) -> user symptom -> blast radius. No hand-waving.
4. Red-flag checklist (yes/no + file:line evidence):
   - New throw on a read/load/decode/import path?
   - Removed an 'if missing use default' branch?
   - New length/range/enum check on a >1-year-old field?
   - Constructor changed from lenient parse to parse+validate?
   - Changed which exception type a public API throws?
   - Format ever in backup/export/sync?
   - Prior PR shipped a 'regenerate on next user action' partial migration? (cite SHA)
   - Proto: field number reused or removed? Enum value renumbered/removed?
   - Keystore: JSON key renamed/removed/made required without default fallback?
   - Registry: slip44, curve, or address-encoding field changed?
5. Mitigations: accept legacy at read + normalize on write (preferred);
   gate strict check behind 'newly created' flag; one-time migration with clear UX;
   or apply tightening to write paths only.

Output a markdown report: Verdict (SAFE/RISK/BLOCKER) at top, then steps 1-5,
then a 'Suggested PR comment' block ([bc-check: Pass|Mitigated|N/A] + reasoning),
then a 'Suggested addition to docs/bc-footguns.md' block (or 'none').

Merge is blocked by verify-bc-check-comment until a tagged comment is posted.

@github-actions

github-actions Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Binary size comparison

➡️ aarch64-apple-ios:

- 14.39 MB
+ 14.42 MB 	 +29 KB

➡️ aarch64-apple-ios-sim:

- 14.40 MB
+ 14.43 MB 	 +29 KB

➡️ aarch64-linux-android:

- 18.86 MB
+ 18.91 MB 	 +47 KB

➡️ armv7-linux-androideabi:

- 16.27 MB
+ 16.30 MB 	 +38 KB

➡️ wasm32-unknown-emscripten:

- 13.76 MB
+ 13.79 MB 	 +34 KB

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
0.0% Coverage on New Code (required ≥ 80%)
8.8% Duplication on New Code (required ≤ 3%)
MINOR Bugs Severity on New Code (required < MINOR)
CRITICAL Code Smells Severity on New Code (required < MAJOR)

See analysis details on SonarQube Cloud

@octane-security-app

Copy link
Copy Markdown

Overview

Vulnerabilities found: 11                                                                                
Severity breakdown: 5 Medium, 6 Low
Warnings found: 2                                                                                

Detailed findings

rust/tw_evm/src/modules/tx_builder.rs

  • Missing EIP-7702 custom_signature signer binding in EVM tx builder with sealed-sign causes victim gas loss. See more

src/Keystore/SealedSigner.cpp

  • Unchecked protobuf parse in sealed signing (src/Keystore/SealedSigner.cpp) causes silent semantic changes in signed Ethereum transactions. See more
  • Missing chain_id validation in SealedSigner (EVM) causes unintended cross-network signing and potential fund loss. See more
  • Default-derivation key injection in sealed signing (TWStoredKeySign/sealedSign) causes unintended account signing and potential fund loss. See more
  • Unenforced keyless-input contract and extra pre-parse in sealed signing cause DoS and key remanence. See more
  • Unsynchronized accounts vector mutation during sealed signing in Keystore causes keystore corruption or crash. See more
  • Null-only failure signaling in sealed signing (TWStoredKeySign/SealedSigner) causes private-key export fallback on attacker-sized inputs. See more
  • Decrypt-before-parse ordering in SealedSigner::sealedSign (TWStoredKeySign path) causes CPU/memory DoS on malformed inputs. See more
  • Missing coin/curve/account binding for private-key keystores in sealed signing path causes unintended EVM signatures. See more
  • Stateful account auto-creation in mnemonic keystore during Ethereum sealed signing causes unexpected metadata changes. See more

src/Keystore/StoredKey.cpp

  • Untrusted keystore derivationPath used for key derivation in sealedSign causes wrong-key signing and potential fund loss. See more

Warnings

rust/tw_evm/src/modules/tx_builder.rs

  • Default-derived key injection in sealed signer for EVM SetCode with custom authorization causes unbroadcastable transactions. See more

src/Keystore/SealedSigner.cpp

  • Unwiped transient key copies in sealed signing flow cause private key disclosure risk. See more

🔗 Commit Hash: 53fb9f4
🛡️ Octane Dashboard: All vulnerabilities

@PandaXadnaP

Copy link
Copy Markdown
Contributor Author

[bc-check: Pass]

BC-risk audit — feat/s2.1-storedkey-sealed-sign → master @ dc547d7 — 2026-10-20T07:55:46Z

Verdict: SAFE

Purely additive. Adds one C ABI function TWStoredKeySign; no existing TW* function, *.proto, registry.json, or keystore load/save path (src/Keystore/StoredKey.cpp) is modified. sealedSign takes a const StoredKey& and never writes the keystore. The new fail-closed checks (exactly one account for the coin, default derivation path, derived address == stored address, keyless input) apply only to the new API: legacy keystores (custom path, multi-account, or accounts without a stored address) get null from TWStoredKeySign and remain fully usable via the unchanged legacy APIs. No persisted data becomes unreadable.

@PandaXadnaP PandaXadnaP changed the title feat(keystore): sealed signing (TWStoredKeySign), Ethereum — Security Layer S2.1 feat(keystore): sealed signing (TWStoredKeySign) for Ethereum + BTC/LTC/DOGE — Security Layer S2.1 Oct 20, 2026
@PandaXadnaP

PandaXadnaP commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

[bc-check: Pass]

BC-risk audit — feat/s2.1-storedkey-sealed-sign → master @ bfa85ef — 2026-12-03T07:56:15Z

Verdict: SAFE

No persistence risk: the diff against master stays additive. Re-audited after merging #4964 (d2bbdd7ef), which moves signing from a StoredKey to a TWPrivateKey handle (6f89cd555), moves the Solana transaction-message check to Rust (2f715d550, from #4963), wipes more key and password copies (fdefe388c, 2005088a8), and fixes a Swift test (40b2c1466). bfa85efe3 only addresses SonarCloud findings: reinterpret_cast → static_cast for TWData arguments (TWData is const void, same pointer) and two NOSONAR annotations, with no change in behaviour. TWStoredKeyError, TWStoredKeyResultData and the *WithStoredKey functions were never on master or in a release, so removing them breaks no consumer.

  • Keystore: StoredKey.cpp is identical to master. EncryptionParameters.cpp only wipes the derived key before the existing invalidCipher throw (same error, same condition). src/interface/TWStoredKey.cpp reads the password in place instead of copying it: the same bytes reach the same functions, so decryption, import and fixAddresses/fixEncryption behave as before.
  • PrivateKey: signing and getPublicKey read the key buffer in place instead of through the key()/extension()/secondKey() copies, at the same offsets (Cardano +32, +3*32). The Data&& constructors now wipe bytes they reject before the same invalid_argument throw; their only callers (src/interface/TWPrivateKey.cpp:29,41) validate first and never reuse the moved buffer. No validation rule changes, so every stored key loads and derives the same addresses.
  • C ABI: additions only against master: TWAnySignerSignWithPrivateKey, TWEthereumMessageSignerSignBizUserOpHash, TWEthereumMessageSignerSignEip7702Authorization, TWSolanaMessageSignerSignMessage and TWSolanaTransactionIsTransactionMessage. No existing TW* function is removed, renamed, or changes its return type or behaviour.
  • Rust FFI: TWData/TWString now zeroize on drop and free_string wipes before freeing; encode_hex returns the same string. Memory hygiene only, no format change.
  • Proto and registry: src/proto/*.proto and registry.json are untouched.

Red-flag checklist: every item is no. There is no new throw on a read path, no removed default, no new length/range/enum check, no proto field change, no keystore JSON change, no registry change and no existing TW* function removed or changed.

Tests: C++ 2392/2392 on bfa85efe3; on #4964's head 40b2c1466 (identical tree to d2bbdd7ef): full Rust suite with fmt and clippy, iOS 620/620 (the StoredKey Swift tests were replaced by SignWithPrivateKeyTests), and the Kotlin build all pass.

@PandaXadnaP PandaXadnaP changed the title feat(keystore): sealed signing (TWStoredKeySign) for Ethereum + BTC/LTC/DOGE — Security Layer S2.1 feat(keystore): sealed signing (TWStoredKeySign) for EVM + BTC/LTC/DOGE — Security Layer S2.1 Oct 21, 2026
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
Code smells with severity Major found (required < Major)

See analysis details on SonarQube Cloud

@PandaXadnaP PandaXadnaP changed the title feat(keystore): sealed signing (TWStoredKeySign) for EVM + BTC/LTC/DOGE — Security Layer S2.1 feat(keystore): sealed signing (TWStoredKeySign) for EVM + BitcoinV2 UTXO coins — Security Layer S2.1 Oct 22, 2026
@PandaXadnaP PandaXadnaP changed the title feat(keystore): sealed signing (TWStoredKeySign) for EVM + BitcoinV2 UTXO coins — Security Layer S2.1 feat(keystore): sealed signing (TWStoredKeySign*) for EVM + BitcoinV2 UTXO — Security Layer S2.1 Oct 22, 2026
@PandaXadnaP PandaXadnaP changed the title feat(keystore): sealed signing (TWStoredKeySign*) for EVM + BitcoinV2 UTXO — Security Layer S2.1 feat(keystore): sealed signing (TWStoredKeySign*) for EVM, UTXO, Tron, Solana with error codes — Security Layer S2.1 Nov 25, 2026
@PandaXadnaP

Copy link
Copy Markdown
Contributor Author

Local test report: sealed signing, from WalletCore to the Trust iOS app

Tested PR HEAD f640bfc3d locally, layer by layer, ending with the Security Layer SDK running inside the Trust iOS app (simulator) against a real app-created wallet. Every sealed result was compared byte for byte with today's path (export the key, sign with the public API). All comparisons match.

1. WalletCore (this PR)

Check Result
Sealed C++ tests (*SealedSigner*:*TWStoredKeySign*) 51 / 51 pass
Full C++ suite 2404 / 2404 pass
iOS Swift tests, incl. the new StoredKeySealedSignTests (11 tests) 621 tests, 0 failures
Kotlin JVM + Android compile (compileKotlinJvm, compileDebug/ReleaseKotlinAndroid) pass, after the codegen fix in a4a79f755

StoredKeySealedSignTests drives StoredKey.sign* through the generated Swift API: Ethereum / Tron / Solana transactions vs AnySigner; personal_sign and EIP-712 vs EthereumMessageSigner; Biz vs Biz; EIP-7702 vs Eip7702.signAuthorization; Tron vs TronMessageSigner; Solana vs the Solana message signer; plus each error code.

2. Binary xcframeworks

  • Built WalletCore.xcframework + WalletCoreSwiftProtobuf.xcframework (device + simulator slices, library evolution on). Each slice exports the 11 TWStoredKeySign* symbols.
  • Built the Security Layer SDK (mobile-security-layer, branch victor/feature/sc-187010/ios-sdk-sign-and-sign-message) as a binary SecurityLayer.xcframework against that WalletCore, with SEALED_SIGNING. The SDK script's own checks pass: WalletCore is linked dynamically (@rpath), not embedded, and absent from the public interface.
  • SDK tests against the local WalletCore: 37 / 37 pass (8 sealed transaction, 14 message, 7 key reading, 8 other).
  • A minimal host app calling the SDK: 9 / 9 cases match (ETH / Tron / Solana transfers, personal_sign, EIP-712, Tron message, Solana message, wrongPassword 1203, signingFailed 1401 for a Tron signer error).

3. Trust iOS app (mobile-monorepo, local only, not committed)

Integration.

  • ios/Packages/WalletCore points at the local xcframeworks and adds a SecurityLayer binary product. Keystore depends on it.
  • The app builds and runs on the iPhone 17 simulator (iOS 27.2). The bundle carries WalletCore, WalletCoreSwiftProtobuf and SecurityLayer, and SecurityLayer links the app's own WalletCore through @rpath.

Real wallet.

  • A KeyMaterialSource over the app's keystore. It reads the wallet's encrypted key file (wallet.keyURL), takes the password through the same getPasswordSecure read as the legacy path, and passes every account the wallet stores.

Shadow mode, DEBUG only.

  • The app still returns the legacy result. After each legacy signature, the same request is signed again through the SDK (sealed), and the two are compared. Only the outcome is logged.
  • Hooked at the app's real signing entries:
    • personal_sign: TrustKeystore.sign(ethereumMessage:), shared by RN, WalletConnect and other callers;
    • transactions: NativeWalletSignerModule.handleAnySign / signAnySilent, the RN AnySigner kernel.

Results on a wallet created in the app (nothing broadcast):

Request Account Result Time (simulator)
personal_sign (app flow during onboarding) m/44'/60'/0'/0/0 MATCH 111 ms
personal_sign × 3 (debug trigger) m/44'/60'/0'/0/0 MATCH × 3 101–115 ms
ETH transfer (sign) m/44'/60'/0'/0/0 MATCH, 209 B output 117 ms
Tron transfer (sign) m/44'/195'/0'/0/0 MATCH, 1001 B output 101 ms
Solana transfer (sign) m/44'/501'/0'/0' MATCH, 554 B output 101 ms

The time is mostly the keystore KDF, which is the same cost as today's key export.

Findings for integration

  1. The app needs this PR on top of WalletCore ≥ 4.10.0.
    • The Trust app already uses APIs added after 4.8.1 (e.g. EthereumChainID.arc), so a WalletCore built from this branch alone (based before 4.8.1) does not compile in the app.
    • Merging current master into it is conflict-free, and that build is what was tested above.
  2. Upgrading the app to 4.10.0 hits a breaking change unrelated to sealed signing: TezosMessageSigner.signMessage now returns String? (fix(tezos): validate MessageSigner payload, return Result #4949), so NativeWalletSignerModule+Signing.swift needs a nil check.
  3. The Kotlin codegen fix (a4a79f755) is required. Without it, StoredKeySignResult (a class that is only ever returned) fails to compile on Android/JVM and has no createFromNative for JNI.
  4. The SDK's extra SigningOutput.error check is now redundant. With 61038653f, a chain-signer error is already signingFailed with no data, and the SDK test for it still passes.

Not covered yet

  • dApp / WalletConnect-originated requests in the app (the in-app browser did not load pages in the local debug build).
  • UTXO sign from a real app flow.
  • Testnet broadcasts (Sepolia, Tron Nile, Solana devnet).
  • Old-version upgrade and iCloud-restored keystores.
  • Real-device runs (Secure Enclave password path).

PandaXadnaP and others added 13 commits November 30, 2026 13:01
Add StoredKey-based sealed signing: derive the key, inject it into the
SigningInput, sign via the internal dispatcher, and zeroize — the private
key is never returned to the caller.

- New Keystore::sealedSign(storedKey, coin, password, signingInput)
- Ethereum wired first; unsupported coins return empty (caller falls back)
- Decrypts once (single-key/account path); UTXO decrypt-once-derive-many
  and the C ABI TWStoredKeySign + bindings land in later increments
- Test: sealed output is byte-identical to extract-then-sign for Ethereum

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…yer S2.1)

Expose Keystore::sealedSign over the C ABI as TWStoredKeySign so iOS (Swift)
and Android (Kotlin/Java) can sign inside the keystore without ever receiving
the private key. Language bindings are generated from the header
(StoredKey.sign(coin:password:input:) in Swift; native byte[] sign(...) in Java).

- include/TrustWalletCore/TWStoredKey.h: TWStoredKeySign declaration
- src/interface/TWStoredKey.cpp: forwards to Keystore::sealedSign; returns null
  on failure or for coins not yet wired into the sealed path
- tests/interface/TWStoredKeySignTests.cpp: drives the C boundary; proves sealed
  output is byte-identical to extract-then-sign (TWStoredKeyPrivateKey +
  TWAnySignerSign) for Ethereum

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…gning

TWStoredKeySign / Keystore::sealedSign derive at the coin's DEFAULT derivation
and DEFAULT account only. A custom derivation path or a non-default account is
not yet supported — such a wallet would be signed with the default account's
key and would not match its address. Record this as an explicit follow-up:

- TWStoredKey.h: \note on the TWStoredKeySign contract
- SealedSigner.cpp: TODO(S2.1 follow-up) at the derivation site

Also add tools/run-sealed-tests to build + run the sealed-signing tests locally.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Reject (return null) unless the stored key holds exactly one account for
  the coin, at its default derivation path, whose address matches the
  derived key — instead of silently signing with the default account's key.
- Never mutate the stored key while signing (sealedSign takes const
  StoredKey&; no account auto-creation).
- Validate the SigningInput before decrypting: reject unparseable input and
  input that already carries a private_key.
- Zero protobuf's copy of the key and serialize without an intermediate
  std::string; drop the no-op wipe of a key copy.
- Rename file-scope test globals so the unity build (Linux CI) no longer
  clashes with StoredKeyTests.cpp's gPassword.
- Add tests: no account, custom path, multi-account, keyed input,
  malformed input, private-key keystore (match / other coin), wrong password.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…account by address

- TWStoredKeySign now takes the account address: the key is derived from that
  account's stored path and used only if it reproduces the address. This
  selects among SegWit/Legacy/Taproot Bitcoin accounts and lifts the
  default-account-only limitation (custom paths / non-default accounts sign
  with their own key; a stale or tampered account record fails closed).
- UTXO: accept only the BitcoinV2 envelope the app signs with
  (`signing_v2` set, `coin_type == coin`, no keys in `private_key` or
  `signing_v2.private_keys`); inject the account key into
  `signing_v2.private_keys`, sign via anyCoinSign(coin), wipe copies.
- One decrypt per call (single-address model: one key signs every input).
- Tests: byte-identical vs extract-then-sign for BTC SegWit/Legacy/Taproot,
  LTC, DOGE (multi-input), ETH custom-path account; rejections for unknown
  address, path/address mismatch, ambiguous records, coin_type mismatch,
  V1-only input, keyed input.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Route every coin whose blockchain is Ethereum (Smart Chain, Polygon,
Arbitrum, Ethereum Classic, ...) to the sealed Ethereum signer. The key
comes from the account of the coin itself and must reproduce its
address; the transaction is signed under Ethereum, matching the app's
current flow (chain selected by chain_id).

Tests: byte-identical for BSC/Polygon/Arbitrum (legacy + EIP-1559),
Ethereum Classic on its own derivation path, and a Smart Chain-only
private-key keystore.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Add Bitcoin Cash, Dash, Viacoin, DigiByte, Ravencoin, Firo, Qtum, Zcash,
Flux (Zelcash), Groestlcoin and Decred to the sealed UTXO path: the full
set of coins the app signs through the BitcoinV2 envelope.

Test: byte-identical for each coin using the app's chain info, including
Bitcoin Cash's SIGHASH_FORKID, the Zcash/Flux NU6 branch id, and Decred's
own SigningOutput.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…SetCode

Byte-identical tests for the two smart-account inputs the app signs:
a Biz4337 UserOperation v0.7 (full output incl. pre_hash) and an EIP-7702
SetCode transaction whose authorization is signed with the injected key.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Byte-identical test for the PSBT envelope the app's signPsbt builds
(signing_v2.psbt + account public key), on the THORChain swap PSBT
fixture; the sealed output also matches the known signed transaction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…iz, EIP-7702)

Add four TWStoredKey C ABI functions that sign EVM messages with the key
of the account selected by (coin, address), without exposing the key:

- TWStoredKeySignEthereumMessage: EIP-191 personal_sign
- TWStoredKeySignEthereumTypedData: EIP-712
- TWStoredKeySignBizUserOpHash: Biz smart-account hash, with sender
  fixed to the signing account
- TWStoredKeySignEip7702Authorization: EIP-7702 delegation authorization

Each computes its digest from structured input; none signs a
caller-supplied raw hash. Biz and EIP-7702 digests come from the
existing Rust functions without the key; the key only signs in C++.

Tests: byte-identical to the app's current extract-key paths
(keccak + PrivateKey.sign, EthereumAbi.encodeTyped, TWBizGetEncodedHash +
TWBizGetSignedHash, TWEip7702SignAuthorization); fail closed on non-EVM
coins, unknown addresses, wrong password, malformed typed data and
invalid contract addresses.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
TWStoredKeySign now accepts Tron: a Tron.SigningInput with `transaction`
or `raw_json` (dApp transaction) and an empty `private_key`. The key is
injected and signed through the normal Tron signer, so `raw_json` keeps
its checks: the transaction is rebuilt from `raw_data` and its hash must
equal `txID`, as must sha256(raw_data_hex) when present. A mismatch
yields the same Error_tx_hash_mismatch output as the normal path.

Add TWStoredKeySignTronMessage: keccak256("\x19TRON Signed Message:\n"
+ len + message), v = 27/28, as Tron::MessageSigner::signMessage. Only
Tron accounts sign. The secp256k1 digest signing shared with the EVM
message functions moves into signSecp256k1DigestRaw; each caller keeps
its own coin check.

Blind signing of a bare raw_data_hex is not supported.

Tests: native and TRC20 transfers (mnemonic and private-key keystores)
and raw_json inputs are byte-identical to the normal path; raw_json with
a wrong txID or raw_data_hex, a caller-supplied key, an unknown address
and a non-Tron coin are rejected. Tron messages match
TWTronMessageSignerSignMessage, including its known test vector.
TWStoredKeySign now accepts Solana: a Solana.SigningInput for a
library-built transaction or with `raw_message` (dApp transaction,
legacy or v0). private_key, fee_payer_private_key and
create_nonce_account.nonce_account_private_key must all be empty, so the
account key is the only key that signs; other signers' signatures may
still come in raw_message.signatures.

Add TWStoredKeySignSolanaMessage: ed25519 over the raw message bytes,
the same signature as the Solana message signer for a UTF-8 message and
as the app's dApp signMessage. Bytes that are exactly a transaction
message are refused before decryption, so it never produces a
transaction signature. The check is a line-for-line port of the app's
SC-140951 rule (solana-transaction-message.ts / SolanaTransactionMessage.kt):
a complete legacy or v0 message that passes the validator's header and
index rules and uses up every byte. Padded or truncated bytes, off-chain
(0xff) messages and other versions are signed, as in the app. Pure byte
parsing with no key; the key signs in C++.

Tests: SOL (legacy and v0) and SPL token transfers (mnemonic and
private-key keystores) and raw_message inputs are byte-identical to the
normal path, and raw_message re-signs to the original transaction.
Messages match the Solana message signer (UTF-8) or raw ed25519 (other
bytes). The transaction-message rule passes the app's parity vectors and
recognises wallet-core-built legacy, v0 and SPL messages. Rejected: any
of the three key fields set, unknown address, non-Solana coin, and
transaction messages. UnsupportedCoinReturnsEmpty now uses Cosmos.
Every sealed signing function (TWStoredKeySign and the six
TWStoredKeySign*Message / Biz / EIP-7702 functions) now returns a
TWStoredKeySignResult instead of null-on-failure: an error code
(TWStoredKeySignError), the output on success, and a fixed diagnostic
message. Callers can tell why signing failed, and the Security Layer
SDK no longer has to verify the password itself (a second scrypt run)
before calling WalletCore.

Errors, in the order they are checked: unsupportedCoin, invalidInput,
transactionBytesRefused (no key involved); accountNotFound (before
decryption, so a call that cannot succeed never runs the KDF);
unsupportedKeyFormat, wrongPassword (MAC mismatch), decryptionFailed
(MAC passes but the payload is not a valid mnemonic or key);
accountMismatch (ambiguous record or derived address differs);
signingFailed; internal. Chain-signer errors (e.g. a Tron raw_json txID
mismatch) stay a successful call whose SigningOutput carries the error,
as with AnySigner.

Messages are string literals by construction, so they never carry the
input, an address, a password or key material. The sealed functions
no longer throw. EIP-7702 returns its JSON as UTF-8 data. None of these
functions has been released, so the signatures change in place.

Tests: every byte-identical test now also asserts success; every
negative test asserts its specific error; new tests cover the
account-before-password order, corrupt payloads (decryptionFailed vs
wrongPassword), fixed messages, and C ABI failures. unsupportedKeyFormat
is mapped but not reachable from a loadable keystore (the JSON loader
rejects unknown KDFs and ciphers first).
Comment thread include/TrustWalletCore/TWStoredKey.h Resolved
Comment thread src/interface/TWStoredKey.cpp Resolved
Comment thread tools/run-sealed-tests Resolved
Comment thread src/Keystore/SealedSigner.cpp Resolved
Comment thread src/Keystore/SealedSigner.cpp Resolved
Comment thread src/Keystore/SealedSigner.cpp Resolved
Comment thread src/Keystore/SealedSigner.cpp Resolved
Comment thread src/Keystore/SealedSigner.cpp Resolved
PandaXadnaP and others added 6 commits December 2, 2026 18:41
Address the review of the sealed signing API: move it off TWStoredKey onto
the signers, reuse the existing chain signers instead of re-implementing
signing, and test through the C interface per chain.

- C API: TWAnySignerSignWithStoredKey, TWEthereumMessageSigner
  Sign{Message,TypedMessage,BizUserOpHash,Eip7702Authorization}WithStoredKey,
  TWTronMessageSignerSignMessageWithStoredKey and a new TWSolanaMessageSigner.
  TWStoredKey.h is back to master. Errors and results are the generic
  TWStoredKeyError (same codes as before) and TWStoredKeyResultData.
- CoinEntry::signWithPrivateKey: the key derived from the StoredKey is handed
  to the coin's entry. Rust gets CoinEntry::set_private_key and the regular
  FFI tw_any_signer_sign_with_private_key (Ethereum, Solana and the BitcoinV2
  entries); the C++ Bitcoin-family entries forward signing_v2 to it; Tron
  signs in C++.
- Messages reuse Ethereum::MessageSigner, Tron::MessageSigner and the Rust
  Biz and EIP-7702 signers; the local secp256k1 digest signer and EIP-7702
  JSON builder are gone. The Solana transaction-message check moves to
  src/Solana/TransactionMessage.
- Key material is held in ZeroizingData / ZeroizingString.
- Tests move to tests/chains/<Chain>/TWSealedSignerTests.cpp through the C
  interface, with an ANY_SIGN_WITH_STORED_KEY macro; shared key selection is
  tested in tests/common/Keystore/StoredKeySigningTests.cpp; Rust gets an
  assert_sign_with_private_key helper. tools/run-sealed-tests is removed.
- Swift and Android bindings for AnySigner.signWithStoredKey.

A chain signer's own error (e.g. a Tron raw_json txID mismatch) now stays in
the SigningOutput with an Ok result, as with TWAnySignerSign.
…validInput

Drop TWStoredKeyErrorTransactionBytesRefused, as asked in review. A Solana
message that is exactly a transaction message is still refused before the
key is decrypted, now with TWStoredKeyErrorInvalidInput. For that function
it is the only invalid input, so a caller can still tell the case apart.
The other error values are unchanged.
The unity build compiles them together with StoredKeyTests.cpp, whose
gPassword clashed with the one in StoredKeySigningTests.cpp.
withStoredKey's C-interface overload now takes the address and password as
C++ types; each TW function converts its arguments, and the password is no
longer copied.
…tionIsTransactionMessage)

Replace the hand-written C++ SolanaMessageReader with a Rust check that
reuses the existing VersionedMessage decoder:

- VersionedMessage::from_exact_bytes decodes with trailing bytes rejected.
- VersionedMessage::has_valid_indexes checks the header and instruction
  indexes (the app rule, SC-140951).
- SolanaTransaction::is_transaction_message combines both and is exported as
  TWSolanaTransaction.IsTransactionMessage. An unreadable pointer returns true,
  so a caller that refuses transaction messages fails closed.

The app parity vectors move to a Rust FFI test.
…dKey

The goal of sealed signing is that key bytes never reach Kotlin or Swift.
A TWPrivateKey handle already gives that: the key stays in the C++
PrivateKey and only crosses if the caller reads TWPrivateKeyData. So the
signing functions now take `const TWPrivateKey*` and the StoredKey layer
(account lookup, decryption, error codes) is removed.

- TWAnySignerSignWithPrivateKey(input, coin, key): the input must carry no
  key; returns the SigningOutput, or null if the coin is unsupported or the
  input does not parse or carries a key. Reuses the CoinEntry
  signWithPrivateKey / Rust set_private_key plumbing.
- TWEthereumMessageSignerSignBizUserOpHash and
  TWEthereumMessageSignerSignEip7702Authorization take the key as a handle
  instead of a hex string; Biz still fixes `sender` to the key's address.
- TWSolanaMessageSignerSignMessage(key, message) still refuses bytes that
  are exactly a transaction message.
- personal_sign, EIP-712 and Tron messages use the existing
  TWEthereumMessageSigner / TWTronMessageSigner functions, which already
  take a TWPrivateKey.
- Removed TWStoredKeyError, TWStoredKeyResultData, StoredKeySigning and
  the Kotlin companion codegen change only that result class needed.
- JNI/Java and Swift AnySigner wrappers and tests updated.
satoshiotomakan-dev and others added 5 commits December 3, 2026 00:11
Copies of the key that were freed or destroyed without being wiped:

- Rust FFI buffers: `TWData` and `TWString` now zeroize on drop. They carry
  the key into Rust (`tw_any_signer_sign_with_private_key`, the Biz and
  EIP-7702 hex key, `tw_private_key_create_with_data`) and serialized
  inputs that hold a key.
- `keyHex` (Biz, EIP-7702): `TW::hex` round-trips through a Rust string it
  frees unwiped; the key is now hex-encoded straight into a
  `ZeroizingString`.
- `Ethereum::signMessageRust` (personal_sign, EIP-712): the input proto and
  its serialized bytes held the key; it is now serialized into a
  `ZeroizingData` and the proto field is wiped.
- `Tron::Entry::signWithPrivateKey`: the injected key is also wiped when
  the signer throws.
- `PrivateKey::sign` / `getPublicKey`: `key()`, `extension()` and
  `secondKey()` returned temporary copies on every call; they now point into
  the key buffer. The `Data&&` constructors wipe rejected bytes they own.
- `EncryptedPayload::decrypt`: the derived key is wiped before the
  invalid-cipher throw.
- `TWStoredKey*`: the password is read in place instead of copied.
…g keys by hand

`keyHex` hex-encoded the key with a hand-written loop because `TW::hex`
left an unwiped copy in Rust. Fix that copy at the source instead:

- `free_string` wipes the string before freeing it.
- `encode_hex` writes into one buffer sized for the prefix and the nul, so
  `CString` never reallocates and leaves no stale copy behind.

`keyHex` is now `ZeroizingString(TW::hex(key))`, and any other caller that
hex-encodes a secret through `TW::hex` no longer leaves the Rust copy.
HDWallet.getKeyForCoin returns PrivateKey?, so makeKey did not compile.
…e-key

refactor(signing): sign with a TWPrivateKey handle instead of a StoredKey
…ning

- Read TWData arguments with static_cast (TWData is const void), as the other new interface code does.
- Mark the catch-all in Tron::Entry::signWithPrivateKey, which must wipe the injected key on any failure.
- Mark AnySigner.signWithPrivateKey's throws clause, which matches sign and plan.

@satoshiotomakan-dev satoshiotomakan-dev left a comment

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.

LGTM, thanks for the changes!

@BSCSecChef BSCSecChef left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. For this PR, Ronin is not updated? Ronin entry is child of ETH, but actual signing is done on Rust end, but no change in code to accept the key?

  2. Also no update for Wasm and Kotlin?

…d Kotlin (#4965)

Ronin: the C++ Ronin entry inherits `supportsSigningWithPrivateKey()` from
Ethereum, but the Rust Ronin entry did not implement `set_private_key`, so
`TWAnySignerSignWithPrivateKey` always returned null. The key injection now
lives in `tw_evm::Signer::set_private_key`, shared by the Ethereum and Ronin
entries. Tested against the broadcast Ronin transfer
(https://explorer.roninchain.com/tx/0xf13a2c4421700f8782ca73eaf16bb8baf82bcf093e23570a1ff062cdd8dbf6c3).

WASM and Kotlin: `AnySigner` is written by hand in each binding, and only
Java and Swift had `signWithPrivateKey`. Add it to WASM (`AnySigner.cpp`,
`AnySigner.d.ts`) and Kotlin Multiplatform (common, Android/JVM through JNI,
iOS, JS), returning null when the coin does not support it or the input
already carries a key.
* fix(eip7702): refuse chain id 0 when signing an authorization with a key handle

Under EIP-7702, an authorization with chain id 0 is valid on every chain,
so anyone could replay the delegation on any EVM chain where the account
nonce matches. Neither the C++ wrapper nor the Rust signer checked it, and
an empty `chainId` also reads as 0.

`TWEthereumMessageSignerSignEip7702Authorization` now returns null for a
zero or empty chain id. The released `TWEip7702SignAuthorization` is
unchanged.

* refactor(eip7702): refuse chain id 0 in the Rust authorization signer

Move the check from the C++ wrapper into
`tw_evm::modules::eip7702::sign_authorization`, so every caller of
`tw_eip7702_sign_authorization` gets it: both
`TWEthereumMessageSignerSignEip7702Authorization` and the released
`TWEip7702SignAuthorization` now return null for a zero or empty chain id,
instead of signing an authorization that is valid on every chain.

* fix(eip7702): refuse chain id 0 on every authorization signing path

The check in `sign_authorization` covered only `TWEip7702SignAuthorization`
and `TWEthereumMessageSignerSignEip7702Authorization`. Two other paths still
signed a chain-0 authorization, valid on every chain:

- `TWMessageSignerSign` with `MessageType_eip7702_authorization` (chain id
  from the JSON message).
- `SetCode` transactions, which sign their authorization with the
  transaction's chain id: with none set, the authorization could be copied
  out of the transaction and replayed on every chain.

Move the check into `Authorization::hash`, which all of them use, so it also
covers `TWEip7702GetAuthorizationHash` for external signing. An authorization
passed in already signed (`custom_signature`) is not affected.

* fix(eip7702): keep verifying chain id 0 authorizations

* refactor(eip7702): sign every EthMessage through signing_hash
@satoshiotomakan-dev

Copy link
Copy Markdown
Contributor

[bc-check: Pass]

BC-risk audit — feat/s2.1-storedkey-sealed-sign → master @ e3b4734 — 2026-12-03

Verdict: SAFE

This PR is additive only. It adds new *WithStoredKey C ABI functions (TWAnySignerSignWithStoredKey, TWEthereumMessageSigner*WithStoredKey, TWSolanaMessageSigner, TWTronMessageSigner*WithStoredKey) plus the TWStoredKeyError / TWStoredKeyResultData types. It also adds non-pure CoinEntry virtuals with defaults, and the matching Rust/JNI/Swift glue. No .proto, registry.json, TWCoinType.h, src/Keystore/StoredKey.* or Account/EncryptionParameters/ScryptParameters file is modified, so no persisted keystore is read, parsed or validated differently. No existing TW* signature or exception behaviour changes. The AccountMismatch address check runs only inside the new signing calls and never on load. One note: the codegen/lib/templates/kotlin/android_class.erb tweak only changes generated Kotlin for classes with a Delete and no other static members, so check the generated Kotlin diff for unintended companion objects.

@sonarqubecloud

sonarqubecloud Bot commented Dec 3, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
73.9% Coverage on New Code (required ≥ 80%)
New dependency risks too severe (required < 'low' severity)

See analysis details on SonarQube Cloud

@BSCSecChef BSCSecChef left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@PandaXadnaP
PandaXadnaP merged commit 1c9fc5d into master Dec 3, 2026
29 of 31 checks passed
@PandaXadnaP
PandaXadnaP deleted the feat/s2.1-storedkey-sealed-sign branch December 3, 2026 16:49
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.

3 participants