Repository navigation
fix(rs-dapi,sdk): decode base64 CBOR error messages from Tenderdash - #3350
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds permissive base64+CBOR decoding to extract embedded "message" strings from Tenderdash JSON Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant TenderdashJSON as Tenderdash JSON handler
participant DapiGRPC as DapiClient error converter
participant Metadata as JSON "data" / gRPC metadata
participant Decoder as Base64+CBOR Decoder
participant ErrorMapper as Error Mapper
Client->>TenderdashJSON: deliver JSON error (contains "message" and/or "data")
TenderdashJSON->>Metadata: inspect top-level "message" and "data"
alt top-level "message" missing/empty or "Internal error"
TenderdashJSON->>Decoder: attempt permissive base64 -> CBOR decode of "data"
Decoder-->>TenderdashJSON: optional "message" string
TenderdashJSON->>ErrorMapper: map using decoded message or fallback raw "data"
else top-level "message" present
TenderdashJSON->>ErrorMapper: map using top-level "message"
end
Client->>DapiGRPC: deliver gRPC Status + metadata
DapiGRPC->>Metadata: inspect `drive-error-data-bin` when Code::Internal
alt `drive-error-data-bin` present
DapiGRPC->>Decoder: CBOR-decode metadata bytes
Decoder-->>DapiGRPC: optional "message" string
DapiGRPC->>ErrorMapper: return Error::DriveInternalError(message) if found
else
DapiGRPC->>ErrorMapper: continue existing mapping / fallback
end
ErrorMapper-->>Client: mapped Error
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
Improves dash-sdk’s error conversion so callers can recover structured ConsensusError information even when DAPI does not provide the primary dash-serialized-consensus-error-bin metadata, by falling back to decoding drive-error-data-bin.
Changes:
- Add a fallback path in
From<DapiClientError> for Errorto parse CBORdrive-error-data-binand extract embeddedconsensus_errorbytes. - Add explicit defensive limits (8 KiB max metadata size, CBOR recursion limit 16) before deserializing untrusted metadata.
- Add unit tests covering the fallback behavior and precedence.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
b173ca5 to
4aa4910
Compare
When Tenderdash returns an error with `message: "Internal error"`, rs-dapi falls through to the `data` field. Previously, the raw base64 string was stored as the message, producing unintelligible gRPC status messages like "oWdtZXNzYWdleMVzdG9yYWdl...". Now `decode_data_message()` tries to decode the `data` field as base64 → CBOR and extract the human-readable `message` text. If decoding fails (plain text data), the raw string is preserved as before. This fixes the 99% case from production DET logs: GroveDB duplicate-key errors (code 13) where the actual message "storage: identity: a unique key with that hash already exists..." was buried in double-encoded CBOR. Co-Authored-By: Claude Opus 4.6 <[email protected]>
0fc9aee to
bfba2ef
Compare
There was a problem hiding this comment.
Pull request overview
Improves rs-dapi’s Tenderdash JSON-RPC error mapping by decoding base64-encoded CBOR stored in the Tenderdash data field (when the top-level message is unhelpful like "Internal error"), so gRPC clients receive human-readable error messages instead of base64 gibberish.
Changes:
- Added
decode_data_message()helper to decodedataas base64 → CBOR and extract the"message"field. - Updated
TenderdashStatus::from(serde_json::Value)to prefer decodeddata.messagewhen appropriate, while preserving prior fallback behavior. - Added unit tests for decoding behavior plus real-world DET log fixtures.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## v3.1-dev #3350 +/- ##
============================================
- Coverage 87.33% 87.17% -0.17%
============================================
Files 2584 2600 +16
Lines 315653 317961 +2308
============================================
+ Hits 275679 277173 +1494
- Misses 39974 40788 +814
🚀 New features to boost your workflow:
|
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Clean, well-scoped PR that adds base64→CBOR decoding for the Tenderdash error.data field, with good test coverage including real-world DET log fixtures. The new decode_data_message() function follows existing patterns in the module, reuses base64_decode() and walk_cbor_for_key(), and gracefully falls back on any decode failure. No blocking issues. Two suggestions worth considering: the pre-existing is_ascii() filter silently drops non-ASCII UTF-8 data strings (contradicting the 'raw string preserved' claim), and the other Tenderdash error ingestion paths (wait_for_state_transition_result) still pass data through without attempting CBOR decoding.
Reviewed commit: 7ae8846
🟡 3 suggestion(s)
1 additional finding
🟡 suggestion: Other Tenderdash error paths still pass `data` through without CBOR decoding
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (lines 151-161)
The new decode_data_message() is only invoked inside impl From<serde_json::Value>, which handles JSON-RPC error responses. The wait_for_state_transition_result path constructs TenderdashStatus::new() directly from ABCI tx_result.data (lines 151–161, 243) without attempting CBOR decoding.
This may be intentional — the ABCI responses could use a different encoding format than JSON-RPC errors. But if they can also carry the same base64-CBOR payloads, clients would still receive unreadable strings on those paths. Worth investigating whether TenderdashStatus::new() should optionally run the same decoding on its message parameter.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:
- [SUGGESTION] lines 313-314: Pre-existing `is_ascii()` filter silently discards non-ASCII UTF-8 data
The `.filter(|s| s.is_ascii())` on line 313 (pre-existing, not introduced by this PR) means that if Tenderdash ever returns a valid UTF-8 `data` string containing non-ASCII characters (e.g. localized or user-provided error text), it gets silently dropped — `message` becomes `None` and later code falls back to a generic message instead of preserving the server detail.
`serde_json::Value::as_str()` already guarantees well-formed UTF-8, and `base64_decode()` will simply return `None` for non-base64 input, so the `is_ascii()` guard provides no safety benefit here. Removing it would make the "raw string preserved on decode failure" claim fully accurate.
Since this PR is already touching this exact code path, it would be a good opportunity to fix this.
- [SUGGESTION] lines 830-841: No integration test for valid-base64-but-not-CBOR data field
The existing `from_json_value_preserves_plain_text_data` test uses text that fails at the base64 step. Adding a test for a `data` field that base64-decodes successfully but is NOT valid CBOR would confirm the end-to-end fallback through the full `From<serde_json::Value>` conversion, not just the unit function.
In `packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs`:
- [SUGGESTION] lines 151-161: Other Tenderdash error paths still pass `data` through without CBOR decoding
The new `decode_data_message()` is only invoked inside `impl From<serde_json::Value>`, which handles JSON-RPC error responses. The `wait_for_state_transition_result` path constructs `TenderdashStatus::new()` directly from ABCI `tx_result.data` (lines 151–161, 243) without attempting CBOR decoding.
This may be intentional — the ABCI responses could use a different encoding format than JSON-RPC errors. But if they can also carry the same base64-CBOR payloads, clients would still receive unreadable strings on those paths. Worth investigating whether `TenderdashStatus::new()` should optionally run the same decoding on its `message` parameter.
- T4: Use non-logging base64 decode in decode_data_message() to avoid noisy debug logs when data field is plain text (expected failure) - T5: Fix misleading test comment — decode_data_message returns None, caller falls back to raw string - T6: Remove pre-existing .filter(|s| s.is_ascii()) that silently discarded valid non-ASCII UTF-8 data strings - T7: Add test for valid-base64-but-not-CBOR data field fallback Co-Authored-By: Claude Opus 4.6 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Incremental Review
Single-commit push (25de8d2) addressing 2 of 3 prior suggestions. Changes are minimal, correct, and well-tested:
-
is_ascii()filter removed ✅ — resolves the pre-existing filter that silently dropped non-ASCII UTF-8 data strings. Thedecode_data_message()fallback now correctly handles all valid UTF-8. -
base64-non-CBOR integration test added ✅ — new
from_json_value_preserves_base64_non_cbor_dataconfirms end-to-end fallback for data that is valid base64 but not CBOR. -
Inline base64 engine — good call avoiding
base64_decode()debug logging for expected failures on plain-text data fields. The inlineGeneralPurposeengine keeps the same decode config.
All 36 tests pass (cargo test -p rs-dapi --lib error_mapping). No new findings.
Reviewed commit: 25de8d2
…-bin metadata When Drive returns a raw GroveDB storage error for a duplicate identity key (without a serialized ConsensusError), the SDK now checks the drive-error-data-bin gRPC metadata for CBOR-encoded error details. If the decoded message matches the identity key uniqueness pattern, the error is surfaced as Error::AlreadyExists instead of falling through to the opaque Error::DapiClientError. Also adds test fixtures for both the DAPI-level CBOR data field decoding and the SDK-level drive-error-data-bin handling. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/rs-sdk/src/error.rs (1)
193-194: Make duplicate-key matching resilient to casing changes.Line 193 and Line 194 use case-sensitive
contains(...). If upstream wording changes capitalization, this mapping silently falls back toError::DapiClientError(_).♻️ Suggested patch
- if message.contains("unique key") && message.contains("already exists") { + let normalized = message.to_ascii_lowercase(); + if normalized.contains("unique key") + && normalized.contains("already exists") + { return Self::AlreadyExists(message); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/rs-sdk/src/error.rs` around lines 193 - 194, The duplicate-key detection is using case-sensitive contains on the error message, so capitalization changes cause falls back to DapiClientError; update the matching in the function that returns Self::AlreadyExists (the branch that currently does if message.contains("unique key") && message.contains("already exists")) to perform case-insensitive matching — e.g. normalize the message with message.to_lowercase() (or use a case-insensitive regex) and then check for "unique key" and "already exists", ensuring the same Self::AlreadyExists variant is returned when those substrings appear in any casing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/rs-sdk/src/error.rs`:
- Around line 193-194: The duplicate-key detection is using case-sensitive
contains on the error message, so capitalization changes cause falls back to
DapiClientError; update the matching in the function that returns
Self::AlreadyExists (the branch that currently does if message.contains("unique
key") && message.contains("already exists")) to perform case-insensitive
matching — e.g. normalize the message with message.to_lowercase() (or use a
case-insensitive regex) and then check for "unique key" and "already exists",
ensuring the same Self::AlreadyExists variant is returned when those substrings
appear in any casing.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 557e7cca-577e-488e-8ca0-2ba378c1e050
📒 Files selected for processing (2)
packages/rs-dapi/src/services/platform_service/error_mapping.rspackages/rs-sdk/src/error.rs
|
✅ DashSDKFFI.xcframework built for this PR.
SwiftPM (host the zip at a stable URL, then use): .binaryTarget(
name: "DashSDKFFI",
url: "https://your.cdn.example/DashSDKFFI.xcframework.zip",
checksum: "8a7665f2904b11edc5480b8faa541542d8b2a31a9c5816ff5e63a530b1dc9bd6"
)Xcode manual integration:
|
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
The new drive-error-data-bin detection code has a semantic conflict with existing recovery logic. When a duplicate identity key error (key belongs to a different identity) is mapped to Error::AlreadyExists, the Identity::wait_for_response() handler misinterprets it as 'this identity was already created', tries to fetch an identity that doesn't exist, and produces a misleading 'identity was proved to not exist but was said to exist' error. The helper function and tests are well-structured but this classification issue needs to be resolved before merging.
Reviewed commit: b18c173
🔴 1 blocking | 🟡 3 suggestion(s) | 💬 1 nitpick(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-sdk/src/error.rs`:
- [BLOCKING] lines 190-198: Mapping duplicate-key errors to AlreadyExists triggers wrong recovery path in Identity::wait_for_response
This new branch converts any `drive-error-data-bin` message containing 'unique key' and 'already exists' into `Error::AlreadyExists`. However, `Identity::wait_for_response()` in `waitable.rs:98-115` catches *every* `Error::AlreadyExists` and assumes the identity was previously created — it extracts the identity ID from the state transition and calls `Identity::fetch(sdk, identity_id)`. For a duplicate-key conflict the *key* belongs to a different identity, but the identity being created does not yet exist. The fetch returns `None` and the user receives the misleading error 'identity was proved to not exist but was said to exist', losing the actual duplicate-key cause entirely.
Either introduce a dedicated variant like `Error::DuplicateIdentityKey(String)` that is not caught by the existing `AlreadyExists` recovery path, or keep the error as `Error::DapiClientError` and let the caller inspect it. If `AlreadyExists` must be reused, update `waitable.rs` to distinguish between 'identity already exists' and 'key already exists' before attempting the fetch.
- [SUGGESTION] lines 193-195: Brittle string matching creates invisible coupling to Drive error format
The pattern `message.contains("unique key") && message.contains("already exists")` matches against Drive/GroveDB's human-readable error text (`UniqueKeyAlreadyExists` display string). If GroveDB or Drive ever changes the wording — even a minor phrasing tweak — this detection silently breaks with no compile-time or test-time signal. A more durable approach would be a machine-readable error code in the CBOR payload (the `code` field is already present but not used for this classification).
- [SUGGESTION] lines 190-192: Silent error swallowing when to_bytes() fails — inconsistent with adjacent code
When `drive_error_value.to_bytes()` returns `Err`, the failure is silently discarded via `if let Ok(bytes)`. The adjacent `consensus_error_value.to_bytes()` path at lines 181-185 logs at debug level and returns a `Generic` error. Adding a `tracing::debug!` log here would maintain consistency and aid debugging.
- [SUGGESTION] lines 190-198: Detection only covers UniqueKeyAlreadyExists, not IdentityKeyAlreadyExists
Drive defines two duplicate-key error variants: `UniqueKeyAlreadyExists` (display: 'a unique key with that hash already exists: ...') and `IdentityKeyAlreadyExists` (display: 'identity key already exists for user error: ...'). The string heuristic only matches the first variant. The second variant has different semantics (same-identity duplicate vs. cross-identity conflict) so this may be intentional, but it's worth documenting the distinction.
…ror-data-bin metadata" This reverts commit b18c173.
…ue-key test
Bundle of small fixes against `services::platform_service::error_mapping`:
1. CMT-004 — defence in depth. Add `MAX_CBOR_INPUT_SIZE = 65_536` and
reject Tenderdash `data` / `info` payloads larger than 64 KiB before
handing them to `ciborium::from_reader`, so a malicious peer can't force
unbounded recursion via `a1 a1 a1 …`-style nested map openers. Mirrors
the rs-sdk-side cap landed earlier.
2. CMT-005 — engine config dedup. `decode_data_message` previously rebuilt
a `base64::engine::GeneralPurpose` per call. Move it to use the shared
`base64_decode` helper, with `base64_decode` now a pure decoder; the
single previous caller (`decode_consensus_error`) keeps the decode-
failure log at the call site (`decode_data_message` deliberately stays
silent because base64 failure there is the expected fall-through).
3. CMT-006 — discriminating assertion. The unique-key fixture test asserted
`contains("unique set")`, which also matches the non-unique fixture's
`non unique set`. Tighten to `contains("in the unique set")` (with
leading space + `in`) — the production message includes that phrase
verbatim.
4. CMT-007 — accepted duplication marker. Add an INTENTIONAL note on
`walk_cbor_for_key` pointing at the matching extract on the rs-sdk side,
so anyone editing one knows to mirror the other.
Addresses PR #3350 review threads CMT-004, CMT-005, CMT-006, CMT-007.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR head 8baeb63 is in solid shape on the Rust side: typed-variant matching now precedes substring heuristics in the FFI error mapper (with regression tests for the not found collision), CBOR decoding has explicit 64 KiB caps on both rs-sdk and rs-dapi sides, and prior simplification asks (base64 engine consolidation, fixture specificity) are addressed. One blocking cross-language gap persists: the Swift wrapper does not translate the new DashSDKErrorCode::DriveInternalError = 10, so Swift consumers receive .unknown and the PR's headline behavior is undelivered to Swift callers.
Reviewed commit: 8baeb63
🔴 1 blocking
1 additional finding
🔴 blocking: Swift wrapper drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (lines 322-392)
The Rust FFI now exports DashSDKErrorCode::DriveInternalError = 10 (packages/rs-sdk-ffi/src/error.rs:32), and the mapper at packages/rs-sdk-ffi/src/error.rs:114-118 correctly emits that code for dash_sdk::Error::DriveInternalError(_) ahead of any substring heuristic. But the Swift translation in SDKError.fromDashSDKError(_:) only enumerates raw values 1-9 and 99 (lines 339-358), and the SDKError enum (lines 322-333) has no driveInternalError case. Any error returned with code = 10 falls through default: at line 359 and becomes .unknown(message), rendered as "Unknown Error: ..." by the LocalizedError extension at line 388-389. End-to-end, the dedicated FFI code added by this PR cannot be observed from Swift — exactly the surface this PR advertises (DET in particular distinguishing Drive storage-level internals from generic network/unknown errors) is not consumable. Add a driveInternalError(String) case to SDKError, a matching case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm in fromDashSDKError, and a corresponding branch in the LocalizedError extension so the new contract is actually consumable from Swift.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [BLOCKING] lines 322-392: Swift wrapper drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
The Rust FFI now exports `DashSDKErrorCode::DriveInternalError = 10` (packages/rs-sdk-ffi/src/error.rs:32), and the mapper at packages/rs-sdk-ffi/src/error.rs:114-118 correctly emits that code for `dash_sdk::Error::DriveInternalError(_)` ahead of any substring heuristic. But the Swift translation in `SDKError.fromDashSDKError(_:)` only enumerates raw values 1-9 and 99 (lines 339-358), and the `SDKError` enum (lines 322-333) has no `driveInternalError` case. Any error returned with code = 10 falls through `default:` at line 359 and becomes `.unknown(message)`, rendered as `"Unknown Error: ..."` by the `LocalizedError` extension at line 388-389. End-to-end, the dedicated FFI code added by this PR cannot be observed from Swift — exactly the surface this PR advertises (DET in particular distinguishing Drive storage-level internals from generic network/unknown errors) is not consumable. Add a `driveInternalError(String)` case to `SDKError`, a matching `case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message)` arm in `fromDashSDKError`, and a corresponding branch in the `LocalizedError` extension so the new contract is actually consumable from Swift.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR head 8baeb63 is solid on the Rust side: typed-variant matching precedes substring heuristics in the FFI mapper (with regression tests), CBOR decoding is size-capped on both rs-sdk and rs-dapi (64 KiB), and DriveInternalError is plumbed through rs-sdk -> rs-sdk-ffi. One blocking cross-language gap remains: the Swift wrapper has no case for the new DashSDKErrorCode::DriveInternalError = 10, so any Drive internal error returned across the C ABI is silently re-erased to .unknown on the Swift surface, defeating the headline behavior the PR advertises for Swift consumers (DET in particular).
Reviewed commit: 8baeb63
Fresh dispatcher run for this queue item. A same-SHA review already existed, so this records the fresh verification without duplicating inline threads.
Code Review
Reviewed commit: 8baeb63
🔴 1 blocking
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [BLOCKING] lines 322-392: Swift wrapper drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
The Rust FFI now exports `DashSDKErrorCode::DriveInternalError = 10` (packages/rs-sdk-ffi/src/error.rs:32) and the mapper at packages/rs-sdk-ffi/src/error.rs:114-118 correctly emits that code for `dash_sdk::Error::DriveInternalError(_)` ahead of any substring heuristic, with the regression test `drive_internal_error_with_not_found_substring_maps_to_drive_internal_error` (lines 219-226) locking that behavior in. The Swift translation layer in `SDKError.fromDashSDKError(_:)` (SDK.swift:335-362) has not been updated to match: the switch only enumerates raw values 1-9 and 99, the `SDKError` enum (lines 322-333) has no `driveInternalError(String)` case, and the `LocalizedError` extension (lines 365-392) has no matching arm. Any error with code 10 therefore falls through `default:` at line 359 and surfaces as `.unknown(message)`, rendered as `"Unknown Error: …"` (line 388-389). End-to-end: a Drive internal error decoded out of `drive-error-data-bin` (the entire raison d'être of this PR for storage-level failures like duplicate-key violations during identity create/update) crosses the Rust->C boundary correctly tagged as code 10, then is silently re-erased one layer up. Swift consumers cannot reliably distinguish Drive storage-level internals from generic un-mapped FFI failures and would be forced to substring-match attacker-influenceable strings on the Swift side — re-introducing exactly the heuristic that was deliberately removed on the Rust side. Add `case driveInternalError(String)` to `SDKError`, a `case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message)` arm in `fromDashSDKError`, and a corresponding branch in the `LocalizedError` extension so the new ABI contract is consumable from Swift.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR is in solid shape on the Rust side at HEAD 8baeb63: typed-variant matching now precedes substring heuristics in rs-sdk-ffi (with regression test), 64 KiB caps gate attacker-influenced CBOR on both rs-sdk and rs-dapi, and CBOR fixtures distinguish unique-set vs non-unique-set payloads. One blocking cross-language regression remains: the Swift wrapper has no case for the new DashSDKErrorCode::DriveInternalError = 10, so Swift consumers silently re-erase the new classification to .unknown — defeating the headline behavior of the PR for Swift callers. Two non-blocking hardening/cosmetic notes are included.
Reviewed commit: 8baeb63
Fresh dispatcher run for this queue item. A same-SHA review already existed, so this records the fresh verification without duplicating inline threads.
Code Review
Reviewed commit: 8baeb63
🔴 1 blocking | 🟡 1 suggestion(s) | 💬 1 nitpick(s)
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [BLOCKING] lines 322-392: Swift wrapper drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
rs-sdk-ffi now exports DashSDKErrorCode::DriveInternalError = 10 (packages/rs-sdk-ffi/src/error.rs:32) and the mapper at packages/rs-sdk-ffi/src/error.rs:114-118 emits that code for dash_sdk::Error::DriveInternalError(_) ahead of any substring heuristic, with the regression test drive_internal_error_with_not_found_substring_maps_to_drive_internal_error (lines 219-226) locking the behavior in. The Swift translation layer in SDKError.fromDashSDKError(_:) (SDK.swift:335-362) has not been updated: the SDKError enum (lines 322-333) has no driveInternalError(String) case, the switch enumerates only raw values 1–9 and 99, and the LocalizedError extension (lines 365-392) has no matching arm. Any error with raw value 10 therefore falls through default at line 359-360 and surfaces to Swift callers as .unknown(message), rendered as "Unknown Error: …" (lines 388-389). End-to-end: a Drive internal error decoded out of drive-error-data-bin (the principal motivation of this PR for storage-level failures like GroveDB duplicate-key violations during identity create/update) crosses the Rust→C boundary correctly tagged as code 10, then is silently re-erased one layer up. Swift consumers cannot reliably distinguish Drive storage-level internals from generic un-mapped FFI failures, and would be forced to substring-match attacker-influenceable strings on the Swift side — reintroducing exactly the heuristic that was deliberately removed on the Rust side. Add case driveInternalError(String) to SDKError, a case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm in fromDashSDKError, and a corresponding branch in the LocalizedError extension so the new ABI contract is consumable from Swift.
In `packages/rs-sdk/src/error.rs`:
- [SUGGESTION] lines 252-273: drive-error-data-bin CBOR decode is bounded only by byte size, not depth
extract_drive_error_message is invoked on bytes pulled from status.metadata().get_bin("drive-error-data-bin"), supplied by the remote DAPI peer on every Code::Internal response. After the 64 KiB length gate it calls ciborium::from_reader::<ciborium::Value, _> and walks the resulting tree, which is recursive in ciborium with no explicit depth cap. With 64 KiB of bytes a malicious peer can encode tens of thousands of nested map levels (a1 60 a1 60 …), each consuming a stack frame in the Value deserializer. In practice tonic's gRPC metadata limit (~8 KiB by default) caps this well below the tokio worker stack today, so it is not directly exploitable. It is fragile under two foreseeable changes: (a) anyone bumping tonic's metadata limit, and (b) any caller that decodes this payload from a non-gRPC source (mock harnesses, replay tests, future transports) where the 64 KiB cap is the only bound. The same pattern exists in rs-dapi's decode_data_message (packages/rs-dapi/src/services/platform_service/error_mapping.rs:309-327) on the Tenderdash data field. Both sites already carry a TODO(CMT-004) for a depth-limited reader; an interim hardening would be to deserialize directly into a small typed struct (#[derive(Deserialize)] struct DriveErrorDataBin { message: Option<String>, .. }) instead of a generic ciborium::Value, which avoids materializing nested attacker-chosen structure that is never consulted.
…review) ciborium 0.2 from_reader is fully recursive on the call stack and the 64 KiB byte cap does not bound structural depth — a payload of nested single-pair map openers (one byte per level) can blow the worker stack. Route both crates' CBOR decode call sites through a `decode_cbor_value` helper that wraps from_reader in std::panic::catch_unwind, turning the unwinding panic into None instead of aborting the worker. Add tests that pin the behaviour with a 60_000-deep payload. Tighten the cap rustdoc to stop implying the cap prevents unbounded recursion; the real bound today is the call stack via catch_unwind. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- DriveInternalError public rustdoc: trim operational guidance ("if pre-
validation is working correctly...") to a present-state description of
what the variant carries.
- decode_data_message rustdoc: stop claiming we detect "base64-encoded
CBOR"; the function accepts any base64 input and lets the CBOR step
filter non-CBOR bytes.
- INTENTIONAL(CMT-007) blurbs on the duplicated walk: shrink to one-line
MIRROR cross-references. The longer rationale was inaccurate (both
crates already pull ciborium) and read like history; the present-state
fact is "these two implementations must stay in sync".
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR is in good shape on the Rust side: the typed-variant FFI classification is locked in by a regression test, attacker-influenced CBOR is bounded by a 64 KiB cap and a catch_unwind guard, and the duplicate base64 engine has been collapsed. One blocking cross-language gap remains: Swift's SDKError still drops the new DashSDKErrorCode::DriveInternalError = 10 into .unknown, silently re-erasing the new ABI contract one layer above the C boundary. Two non-blocking concerns: catch_unwind is a no-op under panic=abort (which build-wasm.sh sets globally for WASM builds), and the C-string message double-prefixes the variant name now that DriveInternalError has its own typed code.
Reviewed commit: 61e3b3c
🔴 1 blocking | 🟡 1 suggestion(s) | 💬 1 nitpick(s)
1 additional finding
🔴 blocking: Swift SDKError drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (lines 332-402)
rs-sdk-ffi now exports DashSDKErrorCode::DriveInternalError = 10 (packages/rs-sdk-ffi/src/error.rs:32) and the From mapper at lines 114-118 emits that code for dash_sdk::Error::DriveInternalError(_) ahead of any substring heuristic, with the regression test at lines 219-225 locking the typed-variant precedence in. The Swift translation layer was not updated alongside: SDKError (lines 332-343) has no driveInternalError(String) case, fromDashSDKError(_:) (lines 345-372) only switches over raw values 1-9 and 99, and the LocalizedError extension (lines 375-401) has no matching arm. Any error with raw value 10 therefore falls through default: at line 369-370 and surfaces to Swift consumers as .unknown(message), rendered as "Unknown Error: Drive internal error: …" — defeating the headline behavior of this PR for Swift consumers and forcing them to substring-match on attacker-influenceable strings (the exact heuristic that was deliberately removed on the Rust side). Per packages/swift-sdk/CLAUDE.md the Swift SDK is supposed to be a thin marshalling bridge that exposes typed FFI codes without decision-making, so this is exactly the trivial bridge update the rule calls for. Add case driveInternalError(String) to SDKError, a case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm in fromDashSDKError, and a corresponding LocalizedError description.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [BLOCKING] lines 332-402: Swift SDKError drops DashSDKErrorCode::DriveInternalError = 10 into .unknown
rs-sdk-ffi now exports `DashSDKErrorCode::DriveInternalError = 10` (packages/rs-sdk-ffi/src/error.rs:32) and the From<FFIError> mapper at lines 114-118 emits that code for `dash_sdk::Error::DriveInternalError(_)` ahead of any substring heuristic, with the regression test at lines 219-225 locking the typed-variant precedence in. The Swift translation layer was not updated alongside: SDKError (lines 332-343) has no `driveInternalError(String)` case, `fromDashSDKError(_:)` (lines 345-372) only switches over raw values 1-9 and 99, and the LocalizedError extension (lines 375-401) has no matching arm. Any error with raw value 10 therefore falls through `default:` at line 369-370 and surfaces to Swift consumers as `.unknown(message)`, rendered as "Unknown Error: Drive internal error: …" — defeating the headline behavior of this PR for Swift consumers and forcing them to substring-match on attacker-influenceable strings (the exact heuristic that was deliberately removed on the Rust side). Per packages/swift-sdk/CLAUDE.md the Swift SDK is supposed to be a thin marshalling bridge that exposes typed FFI codes without decision-making, so this is exactly the trivial bridge update the rule calls for. Add `case driveInternalError(String)` to SDKError, a `case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message)` arm in fromDashSDKError, and a corresponding LocalizedError description.
In `packages/rs-sdk/src/error.rs`:
- [SUGGESTION] lines 236-246: catch_unwind is a no-op under panic=abort; WASM builds lose the stack-overflow guard
`decode_cbor_value` wraps ciborium's recursive decoder in `std::panic::catch_unwind` to convert a hostile-CBOR stack-overflow panic into `None`. The comment correctly notes this is bypassed under `panic = "abort"` and bypassed when recursion exhausts the OS thread stack (SIGSEGV/SIGBUS, no unwinding). For workspace test/CLI builds the guard is effective because Cargo ignores the package-local `[profile.release] panic = "abort"` in rs-sdk-ffi/Cargo.toml and wasm-sdk/Cargo.toml. However, packages/scripts/build-wasm.sh:172 invokes cargo with `--config 'profile.release.panic="abort"'`, which DOES apply globally to the WASM build. In that build, catch_unwind is optimized out and the new `extract_drive_error_message` is reachable on every Code::Internal response from a remote DAPI peer; a malicious peer can craft a `drive-error-data-bin` metadata payload of nested single-pair-map openers (`0xA1 0xA1 …`) up to the 64 KiB MAX_CBOR_INPUT_SIZE cap and trap the WASM module on stack overflow. Same site mirrored in packages/rs-dapi/src/services/platform_service/error_mapping.rs. The 64 KiB cap is the only real bound on WASM. Defense-in-depth fix is to deserialize directly into a small typed struct (e.g. `#[derive(Deserialize)] struct DriveErrorDataBin { message: Option<String>, .. }`) so attacker-chosen nested structure is rejected by serde rather than materialized into a recursive `ciborium::Value`, or wait for ciborium's depth-limited reader (TODO(CMT-004)) and tighten the WASM-side cap meanwhile. Not a defect at current configuration for non-WASM builds; the in-tree test exercises a 2 MiB host stack that fits ciborium's internal recursion check, not the wasm32 stack budget.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
The CBOR decoding itself is mostly well-contained, but the fix is incomplete on two broadcast paths that still forward Tenderdash's raw data string unchanged, so clients can continue to receive the unreadable base64/CBOR payload this PR is trying to eliminate. I also confirmed one client-facing integration miss in Swift and two smaller follow-up issues in the new decoder/export layers.
Reviewed commit: 2e6fec4
🔴 2 blocking | 🟡 4 suggestion(s)
4 additional findings
🔴 blocking: `broadcast_tx_sync` errors still bypass the new CBOR message decoder
packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs (lines 79-92)
This branch still chooses broadcast_result.data or broadcast_result.info verbatim and passes that string into map_broadcast_error(). The new decode_data_message() helper only runs in impl From<serde_json::Value> for TenderdashStatus, which is the JSON-RPC error object path, not the normal broadcast_tx_sync result envelope. When Tenderdash reports a Drive internal error through result.data, rs-dapi will still serialize the raw base64 CBOR blob into the gRPC error message and drive-error-data-bin, so SDK callers continue to see the unreadable payload on the main broadcast path.
🔴 blocking: WebSocket transaction errors still forward undecoded Tenderdash `data`
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (lines 230-244)
The WebSocket error path constructs TenderdashStatus::new(code as i64, data, consensus_error) directly from the transaction event. That means TransactionResult::Error.data becomes the final user-facing message without ever going through decode_data_message(). waitForStateTransitionResult therefore still returns the raw base64 CBOR string for Drive internal errors even though the decoder exists elsewhere in the PR.
🟡 suggestion: Swift does not map the new FFI `DriveInternalError` code
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (lines 332-370)
Rust added DashSDKErrorCode::DriveInternalError = 10 in rs-sdk-ffi, but the Swift bridge still recognizes only codes 1...9 and 99. Any Rust-side DriveInternalError therefore falls into default and becomes .unknown(message) on iOS. That drops the new classification the PR is explicitly adding for FFI consumers, so Swift callers cannot distinguish decoded Drive storage errors from unrelated unknown failures.
🟡 suggestion: Adding `DriveInternalError` mid-enum changes the public wasm enum discriminants
packages/wasm-sdk/src/error.rs (lines 8-42)
WasmSdkErrorKind is exported with #[wasm_bindgen], so its numeric discriminants are part of the JS-facing ABI. Inserting DriveInternalError before the helper variants renumbers InvalidArgument, SerializationError, and NotFound for all existing consumers of error.kind. That is a silent breaking change for callers that compare or persist numeric enum values. Public wasm enums need explicit discriminants or append-only growth to stay ABI-stable.
💡 Suggested change
#[wasm_bindgen]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum WasmSdkErrorKind {
Config = 0,
Drive = 1,
DriveProofError = 2,
Protocol = 3,
Proof = 4,
InvalidProvedResponse = 5,
DapiClientError = 6,
DapiMocksError = 7,
CoreError = 8,
MerkleBlockError = 9,
CoreClientError = 10,
MissingDependency = 11,
TotalCreditsNotFound = 12,
EpochNotFound = 13,
TimeoutReached = 14,
AlreadyExists = 15,
InvalidCreditTransfer = 16,
Generic = 17,
ContextProviderError = 18,
Cancelled = 19,
StaleNode = 20,
StateTransitionBroadcastError = 21,
NonceOverflow = 22,
IdentityNonceNotFound = 23,
InvalidArgument = 24,
SerializationError = 25,
NotFound = 26,
DriveInternalError = 27,
}
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs`:
- [BLOCKING] lines 79-92: `broadcast_tx_sync` errors still bypass the new CBOR message decoder
This branch still chooses `broadcast_result.data` or `broadcast_result.info` verbatim and passes that string into `map_broadcast_error()`. The new `decode_data_message()` helper only runs in `impl From<serde_json::Value> for TenderdashStatus`, which is the JSON-RPC `error` object path, not the normal `broadcast_tx_sync` result envelope. When Tenderdash reports a Drive internal error through `result.data`, rs-dapi will still serialize the raw base64 CBOR blob into the gRPC error message and `drive-error-data-bin`, so SDK callers continue to see the unreadable payload on the main broadcast path.
In `packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs`:
- [BLOCKING] lines 230-244: WebSocket transaction errors still forward undecoded Tenderdash `data`
The WebSocket error path constructs `TenderdashStatus::new(code as i64, data, consensus_error)` directly from the transaction event. That means `TransactionResult::Error.data` becomes the final user-facing message without ever going through `decode_data_message()`. `waitForStateTransitionResult` therefore still returns the raw base64 CBOR string for Drive internal errors even though the decoder exists elsewhere in the PR.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [SUGGESTION] lines 332-370: Swift does not map the new FFI `DriveInternalError` code
Rust added `DashSDKErrorCode::DriveInternalError = 10` in `rs-sdk-ffi`, but the Swift bridge still recognizes only codes `1...9` and `99`. Any Rust-side `DriveInternalError` therefore falls into `default` and becomes `.unknown(message)` on iOS. That drops the new classification the PR is explicitly adding for FFI consumers, so Swift callers cannot distinguish decoded Drive storage errors from unrelated unknown failures.
In `packages/rs-sdk/src/error.rs`:
- [SUGGESTION] lines 225-245: `catch_unwind` does not make deeply nested CBOR safe against stack-overflow aborts
This helper relies on `catch_unwind` around `ciborium::from_reader`, but a real stack overflow is not an ordinary unwinding panic on this toolchain. I verified locally that overflowing the stack still aborts the process even inside `catch_unwind`, which matches Rust's documented behavior. Because the only bound here is payload size, not structural depth, a hostile peer can still feed very deep CBOR to the recursive decoder; on `panic = "abort"` consumers such as `rs-sdk-ffi` and `wasm-sdk`, that remains a process-kill path rather than a safe `None` fallthrough. The mirrored helper in `rs-dapi` has the same weakness.
In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:
- [SUGGESTION] lines 315-332: Empty CBOR `message` replaces the original `data` string with an empty error
`decode_data_message()` currently returns `Some("")` when the CBOR payload contains `{"message": ""}`. The caller at lines 354-357 only falls back to the raw `data` string on `None`, so an empty CBOR message becomes the final gRPC status message and suppresses the original payload completely. The mirrored SDK-side extractor already rejects empty messages, so the two implementations have drifted and the server side is strictly less informative here.
In `packages/wasm-sdk/src/error.rs`:
- [SUGGESTION] lines 8-42: Adding `DriveInternalError` mid-enum changes the public wasm enum discriminants
`WasmSdkErrorKind` is exported with `#[wasm_bindgen]`, so its numeric discriminants are part of the JS-facing ABI. Inserting `DriveInternalError` before the helper variants renumbers `InvalidArgument`, `SerializationError`, and `NotFound` for all existing consumers of `error.kind`. That is a silent breaking change for callers that compare or persist numeric enum values. Public wasm enums need explicit discriminants or append-only growth to stay ABI-stable.
ciborium 0.2.2 already caps recursion at depth 256 and returns Error::RecursionLimitExceeded (a normal Err, not a panic) for deeper input. The catch_unwind in decode_cbor_value therefore guarded a panic that ciborium never raises for ciborium::Value deserialization. Remove the dead catch_unwind/AssertUnwindSafe wrapper in both rs-sdk and rs-dapi and rely on idiomatic Result propagation; the existing MAX_CBOR_INPUT_SIZE length cap remains as the memory bound. Correct the inaccurate comments and drop TODO(CMT-004), and simplify the deep-nesting tests to call the decoder directly (no spawned 2 MiB stack thread needed). Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
|
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
HEAD 4eadafe correctly resolves the catch_unwind/recursion concerns (ciborium 0.2.2 enforces depth-256 internally and returns a normal Err) and locks in the typed DriveInternalError classification in rs-sdk-ffi with regression tests. However, three blocking delivery gaps remain: the broadcast_tx_sync error path (broadcast_state_transition.rs:79-92) and both wait_for_state_transition_result.rs paths (existing-tx at 151-159 and streamed event at 230-244) still feed Tenderdash's raw data field directly into TenderdashStatus without going through decode_data_message(), so the headline behavior is not delivered on the principal motivating workload. The Swift bridge still has no case for DashSDKErrorCode::DriveInternalError=10, silently re-erasing the typed classification to .unknown. Two structural concerns remain: inserting DriveInternalError mid-enum in WasmSdkErrorKind silently renumbers existing wasm-bindgen discriminants, and decode_data_message in rs-dapi returns Some("") for empty CBOR message (drifts from rs-sdk's filter).
Reviewed commit: 4eadafe
🔴 4 blocking | 🟡 2 suggestion(s)
5 additional findings
🔴 blocking: broadcast_tx_sync error path forwards Tenderdash's raw base64-CBOR `data` undecoded
packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs (lines 79-92)
decode_data_message() is only invoked in impl From<serde_json::Value> for TenderdashStatus (the JSON-RPC error-envelope path). On the main synchronous broadcast path, broadcast_result.data is selected verbatim into error_message (lines 80-84) and handed to map_broadcast_error(), which constructs TenderdashStatus::new(code, error_message, ..) without any base64/CBOR decoding. Drive internal errors that come back through broadcast_tx_sync — exactly the identity create/update failures called out in the PR description — therefore still surface the unreadable oWdtZXNzYWdl… base64-CBOR blob in both the gRPC status message and the drive-error-data-bin trailer. Route error_message through decode_data_message(&broadcast_result.data).unwrap_or_else(|| broadcast_result.data.clone()) (or analogous) before building the status so the broadcast path benefits from the new decoder.
🔴 blocking: Streamed transaction-event errors build TenderdashStatus with raw undecoded `data`
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (lines 230-244)
The WebSocket TransactionResult::Error branch decodes info into consensus_error but feeds data straight into TenderdashStatus::new(code as i64, data, consensus_error) at line 243. The downstream conversion serializes that raw string into both the gRPC status message and drive-error-data-bin, so waitForStateTransitionResult continues to return the unreadable base64-CBOR string for Drive internal errors arriving over the event stream. The new decoder only runs in the JSON-RPC From<serde_json::Value> path; this transport bypasses it entirely. Run data through decode_data_message() (falling back to the raw string if decode fails) before constructing the status.
🔴 blocking: build_response_from_existing_tx forwards raw tx_result.data without CBOR decoding
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (lines 143-160)
When the transaction is already present in Tenderdash history, this branch decodes tx_result.info into consensus_error but selects tx_result.data verbatim into TenderdashStatus (lines 151-159). Same defect as the streamed-event path: Drive internal errors recorded in the transaction result come back as raw base64-CBOR rather than the decoded message text, so clients polling waitForStateTransitionResult after the fact still see gibberish. Route the data string through decode_data_message() before constructing the status.
🔴 blocking: Swift SDKError drops DashSDKErrorCode::DriveInternalError=10 into .unknown
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (lines 332-401)
rs-sdk-ffi exports DashSDKErrorCode::DriveInternalError = 10 (rs-sdk-ffi/src/error.rs:32) and the From mapper emits that code for dash_sdk::Error::DriveInternalError() ahead of any substring heuristic, locked in by the drive_internal_error_with_not_found_substring_maps_to_drive_internal_error regression test (lines 219-225). The Swift bridge has not been updated: SDKError has no driveInternalError(String) case, fromDashSDKError(:) (lines 348-371) only covers raw values 1-9 and 99, and the LocalizedError extension has no matching arm. Any error with code 10 falls through default: at lines 369-370 and surfaces to Swift consumers as .unknown("Drive internal error: …"), silently re-erasing the new classification at the C→Swift boundary — exactly the layer the PR description advertises as benefiting from it. Per packages/swift-sdk/CLAUDE.md, the Swift SDK is a thin marshalling bridge; add case driveInternalError(String) to SDKError, a case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm, and a matching LocalizedError description.
🟡 suggestion: Inserting DriveInternalError mid-enum silently renumbers WasmSdkErrorKind discriminants
packages/wasm-sdk/src/error.rs (lines 10-42)
WasmSdkErrorKind is exported with #[wasm_bindgen] and has no explicit discriminants, so wasm-bindgen assigns numeric values 0,1,2,… by source order. The PR inserts DriveInternalError at line 36 between IdentityNonceNotFound (was 23) and the // Local helper kinds block, shifting InvalidArgument/SerializationError/NotFound from 24/25/26 to 25/26/27 in the generated JS enum. JS consumers comparing or persisting the numeric error.kind (switch tables, telemetry pipelines, snapshots) silently observe a different code for the same variant after this PR. The name() string getter still works because it does its own match, but the numeric ABI is a silent break. Either append DriveInternalError at the end of the enum (strictly additive), or assign explicit = N discriminants to every variant so future inserts cannot silently renumber neighbours.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs`:
- [BLOCKING] lines 79-92: broadcast_tx_sync error path forwards Tenderdash's raw base64-CBOR `data` undecoded
decode_data_message() is only invoked in `impl From<serde_json::Value> for TenderdashStatus` (the JSON-RPC error-envelope path). On the main synchronous broadcast path, broadcast_result.data is selected verbatim into `error_message` (lines 80-84) and handed to map_broadcast_error(), which constructs TenderdashStatus::new(code, error_message, ..) without any base64/CBOR decoding. Drive internal errors that come back through broadcast_tx_sync — exactly the identity create/update failures called out in the PR description — therefore still surface the unreadable `oWdtZXNzYWdl…` base64-CBOR blob in both the gRPC status message and the drive-error-data-bin trailer. Route error_message through `decode_data_message(&broadcast_result.data).unwrap_or_else(|| broadcast_result.data.clone())` (or analogous) before building the status so the broadcast path benefits from the new decoder.
In `packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs`:
- [BLOCKING] lines 230-244: Streamed transaction-event errors build TenderdashStatus with raw undecoded `data`
The WebSocket TransactionResult::Error branch decodes `info` into consensus_error but feeds `data` straight into `TenderdashStatus::new(code as i64, data, consensus_error)` at line 243. The downstream conversion serializes that raw string into both the gRPC status message and drive-error-data-bin, so waitForStateTransitionResult continues to return the unreadable base64-CBOR string for Drive internal errors arriving over the event stream. The new decoder only runs in the JSON-RPC `From<serde_json::Value>` path; this transport bypasses it entirely. Run `data` through decode_data_message() (falling back to the raw string if decode fails) before constructing the status.
- [BLOCKING] lines 143-160: build_response_from_existing_tx forwards raw tx_result.data without CBOR decoding
When the transaction is already present in Tenderdash history, this branch decodes tx_result.info into consensus_error but selects tx_result.data verbatim into TenderdashStatus (lines 151-159). Same defect as the streamed-event path: Drive internal errors recorded in the transaction result come back as raw base64-CBOR rather than the decoded `message` text, so clients polling waitForStateTransitionResult after the fact still see gibberish. Route the data string through decode_data_message() before constructing the status.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [BLOCKING] lines 332-401: Swift SDKError drops DashSDKErrorCode::DriveInternalError=10 into .unknown
rs-sdk-ffi exports DashSDKErrorCode::DriveInternalError = 10 (rs-sdk-ffi/src/error.rs:32) and the From<FFIError> mapper emits that code for dash_sdk::Error::DriveInternalError(_) ahead of any substring heuristic, locked in by the drive_internal_error_with_not_found_substring_maps_to_drive_internal_error regression test (lines 219-225). The Swift bridge has not been updated: SDKError has no driveInternalError(String) case, fromDashSDKError(_:) (lines 348-371) only covers raw values 1-9 and 99, and the LocalizedError extension has no matching arm. Any error with code 10 falls through `default:` at lines 369-370 and surfaces to Swift consumers as `.unknown("Drive internal error: …")`, silently re-erasing the new classification at the C→Swift boundary — exactly the layer the PR description advertises as benefiting from it. Per packages/swift-sdk/CLAUDE.md, the Swift SDK is a thin marshalling bridge; add `case driveInternalError(String)` to SDKError, a `case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message)` arm, and a matching LocalizedError description.
In `packages/wasm-sdk/src/error.rs`:
- [SUGGESTION] lines 10-42: Inserting DriveInternalError mid-enum silently renumbers WasmSdkErrorKind discriminants
WasmSdkErrorKind is exported with #[wasm_bindgen] and has no explicit discriminants, so wasm-bindgen assigns numeric values 0,1,2,… by source order. The PR inserts DriveInternalError at line 36 between IdentityNonceNotFound (was 23) and the `// Local helper kinds` block, shifting InvalidArgument/SerializationError/NotFound from 24/25/26 to 25/26/27 in the generated JS enum. JS consumers comparing or persisting the numeric `error.kind` (switch tables, telemetry pipelines, snapshots) silently observe a different code for the same variant after this PR. The `name()` string getter still works because it does its own match, but the numeric ABI is a silent break. Either append DriveInternalError at the end of the enum (strictly additive), or assign explicit `= N` discriminants to every variant so future inserts cannot silently renumber neighbours.
In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:
- [SUGGESTION] lines 307-325: decode_data_message returns Some("") for empty CBOR `message`, suppressing original `data`
decode_data_message ends with `walk_cbor_for_key(&raw_value, &["message"]).and_then(|v| v.as_text().map(|s| s.to_string()))`, with no empty-string filter, so a CBOR payload `{"message": ""}` returns Some(""). The sole caller (line 349) does `decode_data_message(s).unwrap_or_else(|| s.to_string())`, which only falls back to the raw string on None — an empty CBOR message thus replaces the original base64 payload with the empty string, strictly worse for diagnostics than the raw payload. The mirrored extract_drive_error_message in rs-sdk (packages/rs-sdk/src/error.rs) already filters empty strings via `if !msg.is_empty()`, and the two functions are explicitly marked `MIRROR:`-tagged to be kept in sync — they have drifted on the same wire format. Add the same non-empty filter here.
…staclaw review)
decode_data_message returned Some("") for {"message": ""}, replacing the
original data payload with an empty gRPC status; filter it out to match the rs-sdk mirror.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…refix (thepastaclaw review) DriveInternalError already classifies via DashSDKErrorCode::DriveInternalError; strip the duplicated "Drive internal error: " prefix from the FFI C-string. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… cbor decode change) #3350 commit 4eadafe introduced ciborium:: usage in rs-sdk/src/error.rs without declaring the crate, breaking cargo check -p dash-sdk; mirror rs-dapi's ciborium = "0.2". Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
PR #3350 decodes Tenderdash/Drive CBOR error data into human-readable messages, but the new decode_data_message is only wired into the JSON-RPC error-object path. The very common wait_for_state_transition_result paths still forward raw tx_result.data strings to clients, which is the exact regression this PR set out to fix and warrants blocking. Several validated suggestions follow: the Swift binding ignores the new DriveInternalError = 10 code, the new WasmSdkErrorKind variant is inserted mid-enum (shifting JS-visible discriminants), the 64 KiB CBOR cap is applied only after the base64 buffer is allocated, the ciborium = "0.2" declaration drops the 0.2.2 pin that the safety comment depends on, and decode_data_message returns None for {message:""} causing callers to fall back to the raw base64 string.
Reviewed commit: 43c359d
🔴 1 blocking | 🟡 8 suggestion(s) | 💬 1 nitpick(s)
5 additional findings
🔴 blocking: State-transition wait responses still emit raw base64 CBOR `tx_result.data` as the user-visible message
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (lines 143-247)
The new decode_data_message helper added in this PR is only invoked from impl From<serde_json::Value> for TenderdashStatus (error_mapping.rs:352) — the JSON-RPC error-object path. Both indexed-tx and event paths in wait_for_state_transition_result.rs bypass it:
build_response_from_existing_tx(lines 143-160) passestx_result.data.clone()straight intoTenderdashStatus::newas themessageargument.build_response_from_event(lines 230-247) does the same withdatafromTransactionResult::Error.
TenderdashStatus::grpc_message() returns self.message verbatim when present, so StateTransitionBroadcastError.message ends up containing exactly the base64+CBOR strings (e.g. oWdtZXNzYWdle...) that the SDK then surfaces to callers via packages/rs-sdk/src/platform/transition/broadcast.rs. This is the exact regression the PR set out to fix; it is observable on the normal broadcast-and-wait flow whenever the tx is found through tx() or the subscription event rather than the JSON-RPC error path.
Apply decode_data_message (or move the decode logic into TenderdashStatus::new/grpc_message) before constructing the message on these two paths, with the same plain-text fallback already used for the JSON-RPC path.
🟡 suggestion: Swift `fromDashSDKError` does not handle the new `DriveInternalError = 10` code
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (lines 276-316)
The Rust FFI now emits DashSDKErrorCode::DriveInternalError = 10 (packages/rs-sdk-ffi/src/error.rs:32) whenever the SDK surfaces dash_sdk::Error::DriveInternalError. The Swift wrapper still switches over hardcoded raw values 1–9 and 99 only, so a DashSDKError { code = 10, ... } is reclassified as .unknown(message) in the default branch. The typed signal added on the Rust side is dropped at the Swift binding — Swift consumers cannot distinguish Drive storage-level failures from any other unexpected error, which defeats the purpose of the new variant. SDKError itself would also need a new case (e.g., driveInternalError(String)) to expose the classification. A grep of packages/swift-sdk confirms no reference to DriveInternalError anywhere on the Swift side, including the hand-maintained mock headers in SwiftTests/SwiftDashSDK.h and SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h.
🟡 suggestion: Inserting `DriveInternalError` mid-enum shifts JS-visible discriminants of `InvalidArgument`/`SerializationError`/`NotFound`
packages/wasm-sdk/src/error.rs (lines 10-42)
WasmSdkErrorKind is a #[wasm_bindgen] C-style enum with no explicit discriminants. The new DriveInternalError variant was inserted between IdentityNonceNotFound and the // Local helper kinds section, which shifts the auto-assigned integer values for InvalidArgument, SerializationError, and NotFound by +1. wasm-bindgen exposes these to JS as both named accessors and integer constants — code that compares err.kind === WasmSdkErrorKind.NotFound keeps working, but anything that stored the raw integer (logs, IndexedDB rows, cross-version comparisons, persisted analytics) silently sees different values for the same logical variant. This is invisible at compile time and only surfaces across version boundaries. Either append DriveInternalError after NotFound, or — preferable — give every variant an explicit discriminant the way DashSDKErrorCode does on the FFI side (Success = 0, ..., InternalError = 99).
🟡 suggestion: Typed-variant match does not unwrap `NoAvailableAddressesToRetry`, so wrapped `DriveInternalError` still misclassifies as `NotFound`
packages/rs-sdk-ffi/src/error.rs (lines 106-154)
The typed-variant precedence (if let Error::DriveInternalError(inner) = sdk_err) was added to avoid mis-mapping Drive messages containing substrings like "not found". However dash_sdk::Error::NoAvailableAddressesToRetry(Box<Error>) (packages/rs-sdk/src/error.rs:125-126) wraps a boxed inner error and its Display flattens to e.g. "no available addresses to retry, last error: Drive internal error: data contract not found ...". The outer variant is not DriveInternalError, so the if let does not fire, error_str contains "not found", and the existing else if error_str.contains("not found") branch (line 143) maps it back to DashSDKErrorCode::NotFound — exactly the misclassification the typed-variant ordering was added to prevent. Recursively unwrap NoAvailableAddressesToRetry(inner) before classifying, and add a test covering the wrapped case.
💬 nitpick: Hand-maintained Swift mock C headers are stale relative to `DashSDKErrorCode`
packages/swift-sdk/SwiftTests/SwiftDashSDK.h (lines 22-23)
packages/swift-sdk/SwiftTests/SwiftDashSDK.h and packages/swift-sdk/SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h carry a comment stating "This represents what would be generated by cbindgen," but neither contains SwiftDashErrorCode_DriveInternalError = 10 to match the new variant in packages/rs-sdk-ffi/src/error.rs:32. Test-only material so no runtime FFI breakage, but tests that exercise the Swift error-mapping path against the mock will not cover code 10, and the headers will mislead anyone reading them as a reference for the current FFI surface.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
In `packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs`:
- [BLOCKING] lines 143-247: State-transition wait responses still emit raw base64 CBOR `tx_result.data` as the user-visible message
The new `decode_data_message` helper added in this PR is only invoked from `impl From<serde_json::Value> for TenderdashStatus` (error_mapping.rs:352) — the JSON-RPC error-object path. Both indexed-tx and event paths in `wait_for_state_transition_result.rs` bypass it:
- `build_response_from_existing_tx` (lines 143-160) passes `tx_result.data.clone()` straight into `TenderdashStatus::new` as the `message` argument.
- `build_response_from_event` (lines 230-247) does the same with `data` from `TransactionResult::Error`.
`TenderdashStatus::grpc_message()` returns `self.message` verbatim when present, so `StateTransitionBroadcastError.message` ends up containing exactly the base64+CBOR strings (e.g. `oWdtZXNzYWdle...`) that the SDK then surfaces to callers via `packages/rs-sdk/src/platform/transition/broadcast.rs`. This is the exact regression the PR set out to fix; it is observable on the normal broadcast-and-wait flow whenever the tx is found through `tx()` or the subscription event rather than the JSON-RPC error path.
Apply `decode_data_message` (or move the decode logic into `TenderdashStatus::new`/`grpc_message`) before constructing the message on these two paths, with the same plain-text fallback already used for the JSON-RPC path.
In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:
- [SUGGESTION] lines 276-316: Swift `fromDashSDKError` does not handle the new `DriveInternalError = 10` code
The Rust FFI now emits `DashSDKErrorCode::DriveInternalError = 10` (packages/rs-sdk-ffi/src/error.rs:32) whenever the SDK surfaces `dash_sdk::Error::DriveInternalError`. The Swift wrapper still switches over hardcoded raw values 1–9 and 99 only, so a `DashSDKError { code = 10, ... }` is reclassified as `.unknown(message)` in the default branch. The typed signal added on the Rust side is dropped at the Swift binding — Swift consumers cannot distinguish Drive storage-level failures from any other unexpected error, which defeats the purpose of the new variant. `SDKError` itself would also need a new case (e.g., `driveInternalError(String)`) to expose the classification. A grep of `packages/swift-sdk` confirms no reference to `DriveInternalError` anywhere on the Swift side, including the hand-maintained mock headers in `SwiftTests/SwiftDashSDK.h` and `SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h`.
In `packages/wasm-sdk/src/error.rs`:
- [SUGGESTION] lines 10-42: Inserting `DriveInternalError` mid-enum shifts JS-visible discriminants of `InvalidArgument`/`SerializationError`/`NotFound`
`WasmSdkErrorKind` is a `#[wasm_bindgen]` C-style enum with no explicit discriminants. The new `DriveInternalError` variant was inserted between `IdentityNonceNotFound` and the `// Local helper kinds` section, which shifts the auto-assigned integer values for `InvalidArgument`, `SerializationError`, and `NotFound` by +1. wasm-bindgen exposes these to JS as both named accessors and integer constants — code that compares `err.kind === WasmSdkErrorKind.NotFound` keeps working, but anything that stored the raw integer (logs, IndexedDB rows, cross-version comparisons, persisted analytics) silently sees different values for the same logical variant. This is invisible at compile time and only surfaces across version boundaries. Either append `DriveInternalError` after `NotFound`, or — preferable — give every variant an explicit discriminant the way `DashSDKErrorCode` does on the FFI side (`Success = 0, ..., InternalError = 99`).
In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:
- [SUGGESTION] lines 198-320: Base64 size guard runs after the decoded buffer is allocated
`decode_consensus_error` and `decode_data_message` both call `base64_decode(input)` first and only check `decoded_bytes.len() > MAX_CBOR_INPUT_SIZE` afterwards (lines 246-257 and 311-320). A hostile or compromised upstream returning a multi-MB base64 `info`/`data` string causes a ~3/4-input-size `Vec<u8>` allocation before the cap rejects it. Tenderdash here is a locally-trusted sibling, so this is not exploitable end-to-end, but it removes the only remaining defense-in-depth at this layer. Cheap fix: pre-check on the encoded-length side (e.g. `input.len() / 4 * 3 > MAX_CBOR_INPUT_SIZE`) inside `base64_decode` or at each call site before invoking it, so the allocation is bounded by the documented cap rather than by whatever upstream body-size limit happens to be in effect.
- [SUGGESTION] lines 307-355: Empty-CBOR-message fallback surfaces raw base64 to the gRPC status
When `data` is base64-encoded CBOR with `{"message": ""}`, `decode_data_message` returns `None` (the `filter(|s| !s.is_empty())` rule) and the caller at line 352 unconditionally falls back to `s.to_string()`, where `s` is the **base64** form. So a buggy or hostile peer can cause the user-visible message to be base64 gibberish like `oWdtZXNzYWdlYA==` — the exact regression this PR is meant to eliminate. The previous `filter(|s| s.is_ascii())` safety net was removed in this PR. The `decode_data_message_empty_cbor_message_returns_none` test documents the inner return value but does not exercise the caller, which is what the user sees. Distinguish 'successfully base64+CBOR-decoded but no usable message' from 'not base64 at all' — in the former case, fall back to the literal `"Internal error"` or keep `raw_message`, never to `s` itself.
In `packages/rs-sdk/Cargo.toml`:
- [SUGGESTION] line 27: `ciborium = "0.2"` drops the 0.2.2 pin that the documented stack-safety property depends on
Both `packages/rs-sdk/src/error.rs:225-239` and `packages/rs-dapi/src/services/platform_service/error_mapping.rs:178-191` document the only thing bounding CBOR nesting depth (and therefore stack consumption in `decode_cbor_value` and the recursive `walk_cbor_for_key`) as "ciborium's own recursion limit (256)". That limit was added in ciborium 0.2.2; earlier 0.2.x releases lack it. The previous `rs-sdk` declaration was an explicit `version = "0.2.2"` — it was removed and reintroduced in this PR as `"0.2"` (commit `43c359d0d6`). With `"0.2"`, a fresh resolve or `cargo update -p ciborium --precise 0.2.0` would silently downgrade to a version without the depth limit, regressing the same input the new `test_deeply_nested_cbor_rejected_without_stack_exhaustion` test stress-checks. The 64 KiB byte cap alone does not prevent this: 64 KiB of `0xA1` is tens of thousands of nesting frames. Pin to `"0.2.2"` (or stricter) in both `rs-sdk/Cargo.toml` and `rs-dapi/Cargo.toml`.
In `packages/rs-sdk-ffi/src/error.rs`:
- [SUGGESTION] lines 106-154: Typed-variant match does not unwrap `NoAvailableAddressesToRetry`, so wrapped `DriveInternalError` still misclassifies as `NotFound`
The typed-variant precedence (`if let Error::DriveInternalError(inner) = sdk_err`) was added to avoid mis-mapping Drive messages containing substrings like "not found". However `dash_sdk::Error::NoAvailableAddressesToRetry(Box<Error>)` (`packages/rs-sdk/src/error.rs:125-126`) wraps a boxed inner error and its `Display` flattens to e.g. `"no available addresses to retry, last error: Drive internal error: data contract not found ..."`. The outer variant is not `DriveInternalError`, so the `if let` does not fire, `error_str` contains "not found", and the existing `else if error_str.contains("not found")` branch (line 143) maps it back to `DashSDKErrorCode::NotFound` — exactly the misclassification the typed-variant ordering was added to prevent. Recursively unwrap `NoAvailableAddressesToRetry(inner)` before classifying, and add a test covering the wrapped case.
In `packages/rs-sdk/src/error.rs`:
- [SUGGESTION] lines 196-212: Drive-error metadata path silently falls through to generic `DapiClientError` on CBOR failure
When `Code::Internal` carries a `drive-error-data-bin` metadata entry and `extract_drive_error_message` returns `None` (size cap exceeded, malformed CBOR, missing/empty `message`), the code drops to `Self::DapiClientError(value)` and surfaces only the bare gRPC text (typically just "Internal error"). The caller has no signal that a Drive metadata blob was present but unusable — same outward symptom as if no metadata had been sent. Since this branch was added explicitly to surface Drive-internal causes, log at `info!`/`warn!` (not just `debug!` on the `to_bytes` error path; today nothing logs at all if bytes parsed but CBOR decode failed) when metadata is present-but-undecodable, so protocol drift between Drive's emitter and the SDK's decoder is diagnosable.
- [SUGGESTION] lines 225-271: CBOR decoder + size cap duplicated across rs-sdk and rs-dapi with manual MIRROR comments
`MAX_CBOR_INPUT_SIZE = 65_536`, `decode_cbor_value`, the recursion-safety doc-comment, and the CBOR map-walking logic are all duplicated between `packages/rs-sdk/src/error.rs` and `packages/rs-dapi/src/services/platform_service/error_mapping.rs`. The author flagged the divergence risk with `// MIRROR: keep in sync with ...` comments, but the two implementations have already drifted: rs-sdk walks a single top-level `message` key with a hand-rolled loop, while rs-dapi uses a recursive `walk_cbor_for_key` over key paths. Since this is security-hardening code (size cap, recursion-limit assumptions) where any future tightening must be applied in both places, factor the shared pieces into one authoritative module — e.g. a tiny helper crate or in `rs-dapi-client` (which both depend on) — and re-export. Reuse the generic walker on both sides so a single-key lookup and `["data", "serializedError"]` lookup go through the same code path.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
All 10 prior findings from 43c359d remain STILL VALID at c355582 — the latest delta is only a v3.1-dev merge that did not touch any PR-specific files. Two blocking transport gaps persist: wait_for_state_transition_result.rs (both existing-tx and event-stream branches) and broadcast_state_transition.rs's sync path still forward raw base64-CBOR data into TenderdashStatus without invoking the new decode_data_message helper, so the headline regression (unreadable error messages on the broadcast→wait flow) is still unfixed. Remaining suggestions span Swift FFI mapping for DriveInternalError = 10, wasm-bindgen enum ABI stability, NoAvailableAddressesToRetry unwrap miss, base64/CBOR defense-in-depth, the dropped ciborium 0.2.2 pin, empty-CBOR-message fallback to raw base64, silent drive-error-data-bin metadata fallthrough, and helper duplication.
Reviewed commit: c355582
🔴 2 blocking | 🟡 8 suggestion(s)
1. [BLOCKING] packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs:143-247: Wait-for-state-transition error responses still emit raw base64-CBOR `tx_result.data` on both indexed-tx and event-stream paths
VERIFIED STILL VALID on current head. decode_data_message (error_mapping.rs:307-328) is only invoked from impl From<serde_json::Value> for TenderdashStatus (error_mapping.rs:352, the JSON-RPC error-envelope path). Both wait paths bypass it:
build_response_from_existing_tx(lines 143-160): whentx_result.code != 0, line 156 placestx_result.data.clone()directly intoTenderdashStatus::new(...)without any base64/CBOR decoding.build_response_from_event(lines 230-247): theTransactionResult::Error { code, info, data }branch decodesinfointoconsensus_errorbut feedsdataraw intoTenderdashStatus::new(code as i64, data, consensus_error)at line 243.
TenderdashStatus::grpc_message() returns self.message verbatim, so the base64 blob (oWdtZXNzYWdle...) ends up as both the gRPC status message and the StateTransitionBroadcastError.message on the wire. This is the principal broadcast→wait flow the PR description targets and the failure surface producing the bulk of the DET-log occurrences. Route the data string through decode_data_message(&data).unwrap_or_else(|| data.clone()) before constructing the status — or, preferably, move the decode into TenderdashStatus::new/grpc_message so every construction site benefits uniformly. Add a regression test mirroring from_json_value_decodes_cbor_data_field_* covering both paths.
2. [BLOCKING] packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs:79-92: `broadcast_tx_sync` error path still forwards Tenderdash's raw base64-CBOR `data` undecoded
VERIFIED STILL VALID on current head. On the synchronous broadcast path, broadcast_result.data is selected verbatim into error_message (lines 80-84) and passed to map_broadcast_error(), which constructs TenderdashStatus::new(code, message, ...) without any base64/CBOR decoding. decode_data_message is only invoked in impl From<serde_json::Value> for TenderdashStatus (the JSON-RPC error-envelope path), so identity create/update failures returned through broadcast_tx_sync — precisely the workload called out in the PR description — still produce unreadable oWdtZXNzYWdle... base64-CBOR blobs in the gRPC status message and drive-error-data-bin trailer. Route error_message through decode_data_message(&broadcast_result.data).unwrap_or_else(|| broadcast_result.data.clone()) (or analogous) before building the status. Centralizing the decode in TenderdashStatus::new would fix this and the wait-result paths uniformly.
3. [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift:289-316: Swift `fromDashSDKError` drops `DriveInternalError = 10` into `.unknown`
VERIFIED STILL VALID. The Rust FFI emits DashSDKErrorCode::DriveInternalError = 10 (rs-sdk-ffi/src/error.rs:120) ahead of substring heuristics, with regression tests locking in that ordering. The Swift bridge has not been updated: SDKError has no driveInternalError(String) case, fromDashSDKError only covers raw values 1-9 and 99 (verified at SDK.swift:292-315), and the LocalizedError extension (lines 319-346) has no matching arm. A code-10 DashSDKError falls through default: and becomes .unknown(message), silently re-erasing the new classification at the C→Swift boundary — the exact layer the PR description claims benefits from it. Per packages/swift-sdk/CLAUDE.md the Swift SDK is a thin marshalling bridge, so add case driveInternalError(String) to SDKError, a case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm, and a corresponding errorDescription. The mock C headers at packages/swift-sdk/SwiftTests/SwiftDashSDK.h and SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h also lack SwiftDashErrorCode_DriveInternalError = 10; update them together so mock-based tests can exercise the new code path.
4. [SUGGESTION] packages/wasm-sdk/src/error.rs:10-47: Mid-enum `DriveInternalError` insertion shifts JS-visible discriminants of `InvalidArgument`/`SerializationError`/`NotFound`
VERIFIED STILL VALID. WasmSdkErrorKind is #[wasm_bindgen] and has no explicit discriminants; DriveInternalError is inserted at line 36 between IdentityNonceNotFound and the // Local helper kinds block, shifting the auto-assigned integer values of InvalidArgument/SerializationError/NotFound by +1 versus the pre-PR JS ABI. wasm-bindgen exposes these to JS as both named accessors and integer constants, so err.kind === WasmSdkErrorKind.NotFound keeps working, but anything that persisted or compared the raw integer (logs, IndexedDB rows, cross-version analytics) silently sees different values for the same logical variant. The new NotImplemented variant (line 46) was correctly appended at the tail, demonstrating the team understands the append-only discipline — but DriveInternalError is still mid-enum, and without explicit discriminants the next contributor has no compile-time guard against further silent renumbering. Either move DriveInternalError after NotImplemented, or — preferably — assign explicit = N discriminants to every variant the way DashSDKErrorCode does on the FFI side, so future inserts cannot silently renumber neighbours.
5. [SUGGESTION] packages/rs-sdk-ffi/src/error.rs:106-154: Typed-variant match does not unwrap `NoAvailableAddressesToRetry`, so wrapped `DriveInternalError` still misclassifies as `NotFound`
VERIFIED STILL VALID. The if let dash_sdk::Error::DriveInternalError(inner) = sdk_err precedence at lines 114-120 was added explicitly so that messages like data contract not found inside a Drive error don't get re-classified as NotFound — the drive_internal_error_with_not_found_substring_maps_to_drive_internal_error regression test enforces this. However, dash_sdk::Error::NoAvailableAddressesToRetry(Box<Error>) (rs-sdk/src/error.rs:125-126) wraps a boxed inner Error and its Display impl flattens to e.g. "no available addresses to retry, last error: Drive internal error: data contract not found ...". The outer variant is not DriveInternalError, so the if let does not fire; error_str.contains("not found") is true; classification falls to DashSDKErrorCode::NotFound at lines 143-144 — the exact misclassification the typed match was added to prevent. Recursively unwrap NoAvailableAddressesToRetry(inner) (and any other transparent wrappers) before classifying, and add a wrapped-case regression test.
6. [SUGGESTION] packages/rs-dapi/src/services/platform_service/error_mapping.rs:307-355: Empty CBOR `message` falls back to the raw base64 string in the gRPC status
VERIFIED STILL VALID. decode_data_message (lines 307-328) returns None for CBOR {"message": ""} because of the .filter(|s| !s.is_empty()) clause at line 326. The sole caller at line 352 does decode_data_message(s).unwrap_or_else(|| s.to_string()), where s is the base64 form. So a peer returning base64 CBOR with an empty message causes the user-visible message to be base64 gibberish like oWdtZXNzYWdlYA== — the exact regression this PR set out to eliminate for that input. The decode_data_message_empty_cbor_message_returns_none test documents the inner None return but does not exercise the caller. Distinguish 'successfully base64+CBOR-decoded but no usable message' from 'not base64-CBOR at all' — e.g. by returning a small enum (Decoded(String) | DecodedEmpty | NotCbor) so the caller can substitute the literal "Internal error" (or drop to the consensus_error/code-based fallback) in the empty case, never the encoded blob.
7. [SUGGESTION] packages/rs-sdk/Cargo.toml:27: `ciborium = "0.2"` drops the 0.2.2 pin the stack-safety reasoning depends on (also in rs-dapi/Cargo.toml)
VERIFIED STILL VALID. The safety doc-comments in rs-sdk/src/error.rs:225-239 and rs-dapi/src/services/platform_service/error_mapping.rs:178-191 document that the only thing bounding CBOR nesting depth (and stack consumption in decode_cbor_value/walk_cbor_for_key) is ciborium's built-in recursion limit of 256, added in 0.2.2; earlier 0.2.x releases lack it. Both packages/rs-sdk/Cargo.toml:27 and packages/rs-dapi/Cargo.toml:28 currently declare ciborium = "0.2", even though sibling crates in the workspace (rs-platform-value, rs-drive, rs-dpp, rs-drive-abci) all pin to "0.2.2". Cargo.lock resolves to 0.2.2 today, but cargo update -p ciborium --precise 0.2.0 or a fresh resolve picking an older entry from a stale lockfile would silently regress the property that test_deeply_nested_cbor_rejected_without_stack_exhaustion is meant to guarantee. The 64 KiB byte cap alone does not help — 64 KiB of 0xA1 is tens of thousands of nesting frames. Tighten both manifests to "0.2.2".
8. [SUGGESTION] packages/rs-dapi/src/services/platform_service/error_mapping.rs:198-320: Base64 size cap runs after the decoded buffer is allocated
VERIFIED STILL VALID. decode_consensus_error (lines 246-257) and decode_data_message (lines 311-320) both call base64_decode(input) first and only compare decoded_bytes.len() > MAX_CBOR_INPUT_SIZE afterwards. base64_decode (line 198) allocates a Vec<u8> of size ~3/4 of the encoded input before the cap is consulted, so a peer that controls the data/info strings (a multi-MB base64 blob in a JSON-RPC body) can force a proportionally large allocation per Tenderdash error response. Tenderdash is a locally-trusted sibling, so end-to-end exploitability is bounded by upstream body-size limits — this is defense-in-depth weakening, not an exploitable hole. Cheap mitigation: short-circuit on the encoded length before allocating (e.g. if input.len() / 4 * 3 > MAX_CBOR_INPUT_SIZE { return None; } inside base64_decode or at each caller). This keeps the allocation bounded by the documented 64 KiB cap regardless of what upstream body-size limits happen to be in effect.
9. [SUGGESTION] packages/rs-sdk/src/error.rs:196-212: Drive-error metadata path silently falls through to generic `DapiClientError` on CBOR failure with no log
VERIFIED STILL VALID. When a gRPC Code::Internal status carries a drive-error-data-bin metadata entry and extract_drive_error_message returns None (size cap exceeded, malformed CBOR, missing or empty message), execution drops past the if let Some(message) = ... block at line 200 with no log, then through the Code::AlreadyExists check, and finally returns Self::DapiClientError(value) at line 221. The caller cannot distinguish 'Drive metadata was present but undecodable' from 'no metadata was sent' — the outward symptom is the same bare "Internal error" gRPC text. Since this branch exists specifically to surface Drive-internal causes, emit a warn!/info! (not just the existing debug! on the to_bytes Err path; today nothing logs at all if bytes parsed but extract_drive_error_message returned None) when metadata is present-but-undecodable, so protocol drift between Drive's emitter and the SDK's decoder is diagnosable in production.
10. [SUGGESTION] packages/rs-sdk/src/error.rs:225-271: CBOR decoder + size cap duplicated across rs-sdk and rs-dapi with already-divergent implementations
VERIFIED STILL VALID. MAX_CBOR_INPUT_SIZE = 65_536, decode_cbor_value, the recursion-safety doc-comment, and the CBOR map-walking logic are duplicated between packages/rs-sdk/src/error.rs:225-271 and packages/rs-dapi/src/services/platform_service/error_mapping.rs:178-239. The author flagged the divergence risk with // MIRROR: keep in sync with ... comments, but the two implementations have already drifted: rs-sdk walks a single top-level message key with a hand-rolled loop (extract_drive_error_message), while rs-dapi uses a recursive walk_cbor_for_key over arbitrary key paths and has different empty-string filtering at the call site rather than inside the helper. Since this is security-hardening code (size cap, recursion-limit assumption, ConsensusError deserialization sanity check) where any future tightening must apply to both sides, factor the shared pieces into one authoritative location — e.g. a small helper module in rs-dapi-client (which both crates already depend on) — and reuse a single key-path walker on both sides.
Inline posting hit GitHub HTTP 422, so I posted the same verified findings as a top-level review body.
thepastaclaw
left a comment
There was a problem hiding this comment.
Code Review
Cumulative review at HEAD 27fb7ab. The latest delta only moves the base64 size-cap ahead of allocation in rs-dapi and pins ciborium 0.2.2 in rs-sdk. Two blocking issues persist: the principal broadcast→wait error flow (broadcast_tx_sync and both wait_for_state_transition_result branches) still forwards raw base64-CBOR data undecoded because decode_data_message is wired only into the JSON-RPC envelope path. Seven additional carried-forward issues remain (Swift/wasm/FFI ABI gaps, empty-CBOR base64 fallback, rs-dapi ciborium unpinned, undiagnosable Drive metadata failure, mirrored-decoder drift) plus one new nit on inconsistent size-cap metrics between the two decoders in error_mapping.rs.
🔴 2 blocking | 🟡 7 suggestion(s) | 💬 1 nitpick(s)
10 additional finding(s)
blocking: Wait-for-state-transition error responses still emit raw base64-CBOR `tx_result.data` on both indexed-tx and event-stream paths
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (line 143)
Verified at HEAD 27fb7ab — file unchanged in the latest delta. decode_data_message (error_mapping.rs:310-330) is invoked only from impl From<serde_json::Value> for TenderdashStatus (error_mapping.rs:354 — the JSON-RPC error-envelope path). Both wait paths bypass it:
build_response_from_existing_tx(lines 143-161): whentx_result.code != 0, line 156 placesSome(tx_result.data.clone())directly intoTenderdashStatus::new(...)with no base64/CBOR decoding.build_response_from_event(lines 230-247): theTransactionResult::Error { code, info, data }branch decodesinfointoconsensus_errorbut feedsdataraw intoTenderdashStatus::new(code as i64, data, consensus_error)at line 243.
TenderdashStatus::grpc_message() returns self.message verbatim, so the base64 blob (oWdtZXNzYWdle...) ends up as both the gRPC status message and StateTransitionBroadcastError.message on the wire. This is precisely the broadcast→wait flow the PR description set out to fix. Route the data string through decode_data_message(&data).unwrap_or_else(|| data.clone()) before constructing the status — preferably by moving the decode into TenderdashStatus::new/grpc_message so every construction site benefits. Add regression tests mirroring from_json_value_decodes_cbor_data_field_* covering both paths.
blocking: `broadcast_tx_sync` error path still forwards Tenderdash's raw base64-CBOR `data` undecoded
packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs (line 79)
Verified at HEAD 27fb7ab. On the synchronous broadcast path, broadcast_result.data is selected verbatim into error_message (lines 80-84) and passed to map_broadcast_error(), which constructs TenderdashStatus::new(code, message, ...) at lines 232-236 without base64/CBOR decoding. Since decode_data_message is only invoked from impl From<serde_json::Value> for TenderdashStatus, identity create/update failures returned via broadcast_tx_sync — the workload called out in the PR description — still produce unreadable oWdtZXNzYWdle... base64-CBOR blobs in the gRPC status message and drive-error-data-bin trailer. Route error_message through decode_data_message(&broadcast_result.data).unwrap_or_else(|| broadcast_result.data.clone()) before building the status; centralizing the decode in TenderdashStatus::new would fix this and the wait-result paths uniformly.
suggestion: Swift `fromDashSDKError` drops `DriveInternalError = 10` into `.unknown`
packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift (line 289)
Verified at HEAD 27fb7ab. The Rust FFI emits DashSDKErrorCode::DriveInternalError = 10 (rs-sdk-ffi/src/error.rs:114-120) with structural matching ahead of substring heuristics, locked in by regression tests. The Swift bridge (SDK.swift:292-315) only switches on raw values 1...9 and 99 — there is no case DashSDKErrorCode(rawValue: 10): arm and SDKError has no driveInternalError(String) case. A code-10 DashSDKError falls through default: and becomes .unknown(message), silently re-erasing the new classification at the C→Swift boundary. Per packages/swift-sdk/CLAUDE.md the Swift SDK is a thin marshalling bridge — add case driveInternalError(String) to SDKError, a case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message) arm, and a matching errorDescription. The mock C headers at packages/swift-sdk/SwiftTests/SwiftDashSDK.h and SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h also lack SwiftDashErrorCode_DriveInternalError = 10; update them together so mock-based tests can exercise the new code path.
suggestion: Mid-enum `DriveInternalError` insertion shifts JS-visible discriminants of `InvalidArgument`/`SerializationError`/`NotFound`
packages/wasm-sdk/src/error.rs (line 10)
WasmSdkErrorKind is #[wasm_bindgen] with no explicit discriminants, and DriveInternalError is placed at line 36 between IdentityNonceNotFound and the // Local helper kinds block, shifting the auto-assigned integer values of InvalidArgument/SerializationError/NotFound by +1 versus the pre-PR JS ABI. wasm-bindgen exposes these to JS as both named accessors and integer constants, so err.kind === WasmSdkErrorKind.NotFound keeps working — but anything that persisted or compared the raw integer (logs, IndexedDB rows, cross-version analytics, telemetry) silently sees different values for the same logical variant. NotImplemented (line 46) was correctly appended at the tail, showing the team understands the append-only discipline; DriveInternalError is the outlier. Either move DriveInternalError after NotImplemented, or assign explicit = N discriminants to every variant the way DashSDKErrorCode does on the FFI side so future inserts cannot silently renumber neighbours.
suggestion: FFI classifier does not unwrap `NoAvailableAddressesToRetry`, so wrapped `DriveInternalError` still misclassifies as `NotFound`
packages/rs-sdk-ffi/src/error.rs (line 106)
Verified at HEAD 27fb7ab. The if let dash_sdk::Error::DriveInternalError(inner) = sdk_err precedence at lines 114-120 was added so that messages like data contract not found inside a Drive error don't get re-classified as NotFound, and the regression test drive_internal_error_with_not_found_substring_maps_to_drive_internal_error enforces this for the unwrapped variant. But dash_sdk::Error::NoAvailableAddressesToRetry(Box<Error>) (rs-sdk/src/error.rs) wraps a boxed inner Error whose Display impl flattens to e.g. "no available addresses to retry, last error: Drive internal error: data contract not found ...". The outer variant is not DriveInternalError, so the if let at line 114 does not fire; error_str.contains("not found") is true at line 143; classification falls to DashSDKErrorCode::NotFound (=7) at the C boundary — the exact misclassification the typed match was added to prevent. Recursively unwrap NoAvailableAddressesToRetry(inner) (and any other transparent wrappers) before classifying, and add a wrapped-case regression test.
suggestion: Empty CBOR `message` falls back to the raw base64 string in the gRPC status
packages/rs-dapi/src/services/platform_service/error_mapping.rs (line 310)
decode_data_message (lines 310-330) returns None for CBOR {"message": ""} because of the .filter(|s| !s.is_empty()) clause at line 328. The sole caller at line 354 does decode_data_message(s).unwrap_or_else(|| s.to_string()), where s is the base64 form — so a peer returning base64 CBOR with an empty message causes the user-visible message to be base64 gibberish like oWdtZXNzYWdlYA==, the exact regression this PR set out to eliminate for that input. The decode_data_message_empty_cbor_message_returns_none test documents the inner None return but does not exercise the caller. The API shape conflates not decodable at all with decodable but empty — return a small enum (Decoded(String) | DecodedEmpty | NotCbor) so the caller can substitute the literal "Internal error" (or fall back to the consensus_error/code path) for the empty case, never the encoded blob.
suggestion: `ciborium = "0.2"` still unpinned in rs-dapi — the stack-safety doc-comment relies on the 0.2.2 recursion limit
packages/rs-dapi/Cargo.toml (line 28)
Partially fixed: packages/rs-sdk/Cargo.toml:30 is now ciborium = { version = "0.2.2" }, but packages/rs-dapi/Cargo.toml:28 still declares ciborium = "0.2". The safety doc-comment in error_mapping.rs:178-191 explicitly relies on ciborium's built-in recursion limit of 256 — added only in 0.2.2 — to bound stack consumption in decode_cbor_value/walk_cbor_for_key on attacker-influenced CBOR. Cargo.lock resolves to 0.2.2 today, but cargo update -p ciborium --precise 0.2.0 or a fresh resolve from a stale lockfile would silently regress the property test_deeply_nested_cbor_rejected_without_stack_exhaustion is meant to guarantee. The 64 KiB byte cap is not equivalent — 64 KiB of 0xA1 is tens of thousands of nesting frames. Tighten rs-dapi to match rs-sdk.
ciborium = "0.2.2"
suggestion: Drive-error metadata path silently falls through to generic `DapiClientError` on CBOR failure with no log
packages/rs-sdk/src/error.rs (line 196)
When a gRPC Code::Internal status carries a drive-error-data-bin metadata entry and extract_drive_error_message returns None (size cap exceeded, malformed CBOR, missing/empty message), execution drops past the if let Some(message) = ... block at line 200 with no log, then through the Code::AlreadyExists check, and finally returns Self::DapiClientError(value) at line 221. The caller cannot distinguish metadata absent from metadata present but undecodable — the outward symptom is the same bare "Internal error" gRPC text. Since this branch exists specifically to surface Drive-internal causes, emit a warn!/info! (not just the existing debug! on the to_bytes Err path — today nothing logs at all if bytes parse but extract_drive_error_message returned None) when metadata is present-but-undecodable, so protocol drift between Drive's emitter and the SDK's decoder is diagnosable in production.
suggestion: CBOR decoder + size cap duplicated across rs-sdk and rs-dapi with already-divergent implementations
packages/rs-sdk/src/error.rs (line 225)
MAX_CBOR_INPUT_SIZE = 65_536, decode_cbor_value, the recursion-safety doc-comment, and the CBOR map-walking logic are duplicated between packages/rs-sdk/src/error.rs:225-271 and packages/rs-dapi/src/services/platform_service/error_mapping.rs:178-330. The author flagged the divergence risk with // MIRROR: keep in sync with ... comments, but the two implementations have already drifted: rs-sdk walks a single top-level message key with a hand-rolled loop, while rs-dapi uses a recursive walk_cbor_for_key over arbitrary key paths with different empty-string filtering. The latest delta widened the gap further — the size-cap pre-check was applied in rs-dapi (using decoded_len_estimate and data.len()) and the ciborium pin was applied in rs-sdk, but neither was mirrored. Since this is security-hardening code where any future tightening must apply to both sides, factor the shared pieces into one authoritative location (e.g. a small helper module in rs-dapi-client, which both crates already depend on) and reuse a single key-path walker.
nitpick: Inconsistent size-cap semantics between `decode_consensus_error` and `decode_data_message`
packages/rs-dapi/src/services/platform_service/error_mapping.rs (line 245)
The delta moved size-cap checks to before base64 allocation in both helpers (good), but they use different metrics:
decode_consensus_error(line 245):base64::decoded_len_estimate(info_base64.len())— caps the decoded size at 64 KiB, allowing up to ~87 KiB of encoded input.decode_data_message(line 311):data.len() > MAX_CBOR_INPUT_SIZE— caps the encoded size at 64 KiB, which corresponds to only ~48 KiB of decoded payload.
Both are correct for memory bounding, but the asymmetry means a payload with ~48-64 KiB of decoded CBOR is accepted by one path and rejected by the other in the same file. Pick one metric — decoded_len_estimate matches the documented intent of the cap — and apply it uniformly.
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.
- [BLOCKING] In `packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs`:143-247: Wait-for-state-transition error responses still emit raw base64-CBOR `tx_result.data` on both indexed-tx and event-stream paths
Verified at HEAD 27fb7ab2 — file unchanged in the latest delta. `decode_data_message` (error_mapping.rs:310-330) is invoked only from `impl From<serde_json::Value> for TenderdashStatus` (error_mapping.rs:354 — the JSON-RPC error-envelope path). Both wait paths bypass it:
- `build_response_from_existing_tx` (lines 143-161): when `tx_result.code != 0`, line 156 places `Some(tx_result.data.clone())` directly into `TenderdashStatus::new(...)` with no base64/CBOR decoding.
- `build_response_from_event` (lines 230-247): the `TransactionResult::Error { code, info, data }` branch decodes `info` into `consensus_error` but feeds `data` raw into `TenderdashStatus::new(code as i64, data, consensus_error)` at line 243.
`TenderdashStatus::grpc_message()` returns `self.message` verbatim, so the base64 blob (`oWdtZXNzYWdle...`) ends up as both the gRPC status message and `StateTransitionBroadcastError.message` on the wire. This is precisely the broadcast→wait flow the PR description set out to fix. Route the data string through `decode_data_message(&data).unwrap_or_else(|| data.clone())` before constructing the status — preferably by moving the decode into `TenderdashStatus::new`/`grpc_message` so every construction site benefits. Add regression tests mirroring `from_json_value_decodes_cbor_data_field_*` covering both paths.
- [BLOCKING] In `packages/rs-dapi/src/services/platform_service/broadcast_state_transition.rs`:79-92: `broadcast_tx_sync` error path still forwards Tenderdash's raw base64-CBOR `data` undecoded
Verified at HEAD 27fb7ab2. On the synchronous broadcast path, `broadcast_result.data` is selected verbatim into `error_message` (lines 80-84) and passed to `map_broadcast_error()`, which constructs `TenderdashStatus::new(code, message, ...)` at lines 232-236 without base64/CBOR decoding. Since `decode_data_message` is only invoked from `impl From<serde_json::Value> for TenderdashStatus`, identity create/update failures returned via `broadcast_tx_sync` — the workload called out in the PR description — still produce unreadable `oWdtZXNzYWdle...` base64-CBOR blobs in the gRPC status message and `drive-error-data-bin` trailer. Route `error_message` through `decode_data_message(&broadcast_result.data).unwrap_or_else(|| broadcast_result.data.clone())` before building the status; centralizing the decode in `TenderdashStatus::new` would fix this and the wait-result paths uniformly.
- [SUGGESTION] In `packages/swift-sdk/Sources/SwiftDashSDK/SDK.swift`:289-316: Swift `fromDashSDKError` drops `DriveInternalError = 10` into `.unknown`
Verified at HEAD 27fb7ab2. The Rust FFI emits `DashSDKErrorCode::DriveInternalError = 10` (rs-sdk-ffi/src/error.rs:114-120) with structural matching ahead of substring heuristics, locked in by regression tests. The Swift bridge (SDK.swift:292-315) only switches on raw values `1...9` and `99` — there is no `case DashSDKErrorCode(rawValue: 10):` arm and `SDKError` has no `driveInternalError(String)` case. A code-10 `DashSDKError` falls through `default:` and becomes `.unknown(message)`, silently re-erasing the new classification at the C→Swift boundary. Per packages/swift-sdk/CLAUDE.md the Swift SDK is a thin marshalling bridge — add `case driveInternalError(String)` to `SDKError`, a `case DashSDKErrorCode(rawValue: 10): return .driveInternalError(message)` arm, and a matching `errorDescription`. The mock C headers at `packages/swift-sdk/SwiftTests/SwiftDashSDK.h` and `SwiftTests/Sources/SwiftDashSDKMock/SwiftDashSDK.h` also lack `SwiftDashErrorCode_DriveInternalError = 10`; update them together so mock-based tests can exercise the new code path.
- [SUGGESTION] In `packages/wasm-sdk/src/error.rs`:10-47: Mid-enum `DriveInternalError` insertion shifts JS-visible discriminants of `InvalidArgument`/`SerializationError`/`NotFound`
`WasmSdkErrorKind` is `#[wasm_bindgen]` with no explicit discriminants, and `DriveInternalError` is placed at line 36 between `IdentityNonceNotFound` and the `// Local helper kinds` block, shifting the auto-assigned integer values of `InvalidArgument`/`SerializationError`/`NotFound` by +1 versus the pre-PR JS ABI. `wasm-bindgen` exposes these to JS as both named accessors and integer constants, so `err.kind === WasmSdkErrorKind.NotFound` keeps working — but anything that persisted or compared the raw integer (logs, IndexedDB rows, cross-version analytics, telemetry) silently sees different values for the same logical variant. `NotImplemented` (line 46) was correctly appended at the tail, showing the team understands the append-only discipline; `DriveInternalError` is the outlier. Either move `DriveInternalError` after `NotImplemented`, or assign explicit `= N` discriminants to every variant the way `DashSDKErrorCode` does on the FFI side so future inserts cannot silently renumber neighbours.
- [SUGGESTION] In `packages/rs-sdk-ffi/src/error.rs`:106-154: FFI classifier does not unwrap `NoAvailableAddressesToRetry`, so wrapped `DriveInternalError` still misclassifies as `NotFound`
Verified at HEAD 27fb7ab2. The `if let dash_sdk::Error::DriveInternalError(inner) = sdk_err` precedence at lines 114-120 was added so that messages like `data contract not found` inside a Drive error don't get re-classified as `NotFound`, and the regression test `drive_internal_error_with_not_found_substring_maps_to_drive_internal_error` enforces this for the unwrapped variant. But `dash_sdk::Error::NoAvailableAddressesToRetry(Box<Error>)` (rs-sdk/src/error.rs) wraps a boxed inner Error whose `Display` impl flattens to e.g. `"no available addresses to retry, last error: Drive internal error: data contract not found ..."`. The outer variant is not `DriveInternalError`, so the `if let` at line 114 does not fire; `error_str.contains("not found")` is true at line 143; classification falls to `DashSDKErrorCode::NotFound` (=7) at the C boundary — the exact misclassification the typed match was added to prevent. Recursively unwrap `NoAvailableAddressesToRetry(inner)` (and any other transparent wrappers) before classifying, and add a wrapped-case regression test.
- [SUGGESTION] In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:310-357: Empty CBOR `message` falls back to the raw base64 string in the gRPC status
`decode_data_message` (lines 310-330) returns `None` for CBOR `{"message": ""}` because of the `.filter(|s| !s.is_empty())` clause at line 328. The sole caller at line 354 does `decode_data_message(s).unwrap_or_else(|| s.to_string())`, where `s` is the **base64** form — so a peer returning base64 CBOR with an empty `message` causes the user-visible message to be base64 gibberish like `oWdtZXNzYWdlYA==`, the exact regression this PR set out to eliminate for that input. The `decode_data_message_empty_cbor_message_returns_none` test documents the inner `None` return but does not exercise the caller. The API shape conflates `not decodable at all` with `decodable but empty` — return a small enum (`Decoded(String) | DecodedEmpty | NotCbor`) so the caller can substitute the literal `"Internal error"` (or fall back to the consensus_error/code path) for the empty case, never the encoded blob.
- [SUGGESTION] In `packages/rs-dapi/Cargo.toml`:28-28: `ciborium = "0.2"` still unpinned in rs-dapi — the stack-safety doc-comment relies on the 0.2.2 recursion limit
Partially fixed: `packages/rs-sdk/Cargo.toml:30` is now `ciborium = { version = "0.2.2" }`, but `packages/rs-dapi/Cargo.toml:28` still declares `ciborium = "0.2"`. The safety doc-comment in `error_mapping.rs:178-191` explicitly relies on ciborium's built-in recursion limit of 256 — added only in 0.2.2 — to bound stack consumption in `decode_cbor_value`/`walk_cbor_for_key` on attacker-influenced CBOR. `Cargo.lock` resolves to 0.2.2 today, but `cargo update -p ciborium --precise 0.2.0` or a fresh resolve from a stale lockfile would silently regress the property `test_deeply_nested_cbor_rejected_without_stack_exhaustion` is meant to guarantee. The 64 KiB byte cap is not equivalent — 64 KiB of `0xA1` is tens of thousands of nesting frames. Tighten rs-dapi to match rs-sdk.
- [SUGGESTION] In `packages/rs-sdk/src/error.rs`:196-221: Drive-error metadata path silently falls through to generic `DapiClientError` on CBOR failure with no log
When a gRPC `Code::Internal` status carries a `drive-error-data-bin` metadata entry and `extract_drive_error_message` returns `None` (size cap exceeded, malformed CBOR, missing/empty `message`), execution drops past the `if let Some(message) = ...` block at line 200 with no log, then through the `Code::AlreadyExists` check, and finally returns `Self::DapiClientError(value)` at line 221. The caller cannot distinguish `metadata absent` from `metadata present but undecodable` — the outward symptom is the same bare "Internal error" gRPC text. Since this branch exists specifically to surface Drive-internal causes, emit a `warn!`/`info!` (not just the existing `debug!` on the `to_bytes` Err path — today nothing logs at all if bytes parse but `extract_drive_error_message` returned `None`) when metadata is present-but-undecodable, so protocol drift between Drive's emitter and the SDK's decoder is diagnosable in production.
- [SUGGESTION] In `packages/rs-sdk/src/error.rs`:225-271: CBOR decoder + size cap duplicated across rs-sdk and rs-dapi with already-divergent implementations
`MAX_CBOR_INPUT_SIZE = 65_536`, `decode_cbor_value`, the recursion-safety doc-comment, and the CBOR map-walking logic are duplicated between `packages/rs-sdk/src/error.rs:225-271` and `packages/rs-dapi/src/services/platform_service/error_mapping.rs:178-330`. The author flagged the divergence risk with `// MIRROR: keep in sync with ...` comments, but the two implementations have already drifted: rs-sdk walks a single top-level `message` key with a hand-rolled loop, while rs-dapi uses a recursive `walk_cbor_for_key` over arbitrary key paths with different empty-string filtering. The latest delta widened the gap further — the size-cap pre-check was applied in rs-dapi (using `decoded_len_estimate` and `data.len()`) and the ciborium pin was applied in rs-sdk, but neither was mirrored. Since this is security-hardening code where any future tightening must apply to both sides, factor the shared pieces into one authoritative location (e.g. a small helper module in `rs-dapi-client`, which both crates already depend on) and reuse a single key-path walker.
- [NITPICK] In `packages/rs-dapi/src/services/platform_service/error_mapping.rs`:245-318: Inconsistent size-cap semantics between `decode_consensus_error` and `decode_data_message`
The delta moved size-cap checks to before base64 allocation in both helpers (good), but they use different metrics:
- `decode_consensus_error` (line 245): `base64::decoded_len_estimate(info_base64.len())` — caps the *decoded* size at 64 KiB, allowing up to ~87 KiB of encoded input.
- `decode_data_message` (line 311): `data.len() > MAX_CBOR_INPUT_SIZE` — caps the *encoded* size at 64 KiB, which corresponds to only ~48 KiB of decoded payload.
Both are correct for memory bounding, but the asymmetry means a payload with ~48-64 KiB of decoded CBOR is accepted by one path and rejected by the other in the same file. Pick one metric — `decoded_len_estimate` matches the documented intent of the cap — and apply it uniformly.
Inline posting hit GitHub HTTP 422, so I posted the same verified findings as a top-level review body.
shumkov
left a comment
There was a problem hiding this comment.
Is there any way to re-use this logic?
Issue being fixed or feature implemented
When Tenderdash returns errors with
message: "Internal error", rs-dapi falls through to thedatafield. Tenderdash wraps Drive's CBOR error payload in the JSON-RPCdatafield as a base64 string, but rs-dapi stored it raw — producing unintelligible gRPC status messages likeoWdtZXNzYWdleMVzdG9yYWdl...on the wire.Related: dashpay/dash-evo-tool#766 (DET workaround using message-text matching)
Evidence from DET production logs
144 gRPC errors across all DET logs. Four patterns:
drive-error-data-bindash-serialized-consensus-error-binconsensus_errorin CBORThe majority of errors (99/144) are GroveDB duplicate-key errors during identity create/update where the actual human-readable message was buried in double-encoded CBOR. The 2 consensus errors (DPP 10530) already work correctly via the existing
dash-serialized-consensus-error-binpath.What was done?
rs-dapi (error_mapping.rs)
Added
decode_data_message()helper that tries to decode thedatafield as base64 → CBOR → extract human-readablemessagetext. If decoding fails (plain text data), the raw string is preserved — no regression for existing behavior.rs-sdk (error.rs)
Added
DriveInternalError(String)variant to the SDKErrorenum. When gRPC status isCode::Internalanddrive-error-data-binmetadata is present, the CBOR payload is decoded and the human-readable message is surfaced viaDriveInternalErrorinstead of being lost in a genericDapiClientError.rs-sdk-ffi (error.rs)
Added
DashSDKErrorCode::DriveInternalError = 10and string match branch so FFI consumers (C/Swift) get a dedicated error code instead of falling through toNetworkError.wasm-sdk (error.rs)
Added
WasmSdkErrorKind::DriveInternalErrormapping for the new variant.How Has This Been Tested?
Automated
cargo test -p rs-dapi --lib error_mapping— all 36 tests pass (29 existing + 7 new)cargo test -p dash-sdk --lib— 111 tests pass (4 new fordrive-error-data-binpath)cargo clippy -p rs-dapi -p dash-sdk -p dash-sdk-ffi— cleancargo fmt --all— cleanSDK test coverage added
test_drive_error_data_bin_maps_to_drive_internal_errorCode::Internal→DriveInternalErrortest_internal_error_without_drive_metadata_falls_throughCode::Internalwithout metadata →DapiClientErrortest_non_internal_code_with_drive_metadata_not_interceptedCode::Unavailable+ metadata → NOT interceptedtest_malformed_cbor_in_drive_error_data_bin_falls_throughManual integration test
To reproduce with a real network:
IdentityCreatestate transitionInternalerror with messageoWdtZXNzYWdleMVzdG9yYWdl...(base64 CBOR gibberish)Internalerror with messagestorage: identity: a unique key with that hash already exists: the key already exists in the unique set [...]Breaking Changes
None. Plain text
datafields are preserved as-is. Only base64-encoded CBOR with amessagekey is decoded. The newDriveInternalErrorvariant extends theErrorenum (pre-1.0 SDK, follows platform release cycle).Checklist:
For repository code-owners and collaborators only
🤖 Co-authored by Claudius the Magnificent AI Agent