Skip to content

fix(dpp): read $entropy as base64, not base58, in the create-transition map parser - #5072

Merged
shumkov merged 3 commits into
v5.0-devfrom
fix/document-create-entropy-base64
Oct 3, 2026
Merged

shumkov merged 3 commits into
v5.0-devfrom
fix/document-create-entropy-base64

Conversation

@shumkov

@shumkov shumkov commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

DocumentCreateTransitionV0::from_value_map read $entropy with remove_hash256_bytes, which
decodes a text value as base58 — the identifier convention. $entropy is raw bytes, which this
repository carries across JSON as base64.

One struct read one field two ways. In the same file, the hand-written Deserialize decodes
$entropy's text form as base64 (and says so), and the struct's doc comments state that
#[json_safe_fields] auto-injects crate::serialization::serde_bytes on entropy: [u8; 32] →
"base64 string in JSON HR, raw bytes in non-HR".

The writer settles which is correct. Value → JsonValue states the convention outright, in two
adjacent arms:

Value::Bytes(bytes)      => JsonValue::String(BASE64_STANDARD.encode(...)),
Value::Identifier(bytes) => JsonValue::String(bs58::encode(bytes.as_slice()).into_string()),

to_value_map() writes $entropy as Value::Bytes, so the JSON form emits base64 — and the parser
decoded it as base58. A transition did not survive a trip through its own JSON form.

remove_hash256_bytes's neutral name is what invites this: the helper family is split by
convention, not by name. remove_bytes/remove_hash256_bytes decode text as base58;
remove_bytes_32/remove_bytes_20/remove_binary_data decode base64.

Could it have decoded to wrong bytes rather than erroring?

The base58 and base64 alphabets overlap — base58 is base64 minus + / 0 O I l — so in general a
value free of those characters decodes under both and yields different bytes silently. Here it
could not, and the guard was the padding, not a length check.
Base64 of exactly 32 bytes is always
44 characters with exactly one trailing = (32 = 3·10 + 2, so the final quantum is always padded),
and = is outside the base58 alphabet. bs58::decode therefore always failed on the padded form,
loudly. to_hash256 does apply a 32-byte length check afterwards, but the padding rejection fired
first.

That guard was narrower than it looks. The correct reader is PADDING_INDIFFERENT, so an unpadded
43-character base64 body drawn only from the shared alphabet is also a valid base58 string, and 43
base58 characters decode to exactly 32 bytes for the large majority of inputs (1905 of 2000 sampled)
— the length check would not have caught those. No in-repo writer emits unpadded base64, so this
stayed theoretical.

What was done?

Switched the one wrong read to remove_bytes_32, the base64 member of the same helper family, with
.to_buffer() for the Bytes32 → [u8; 32] field type. The nearby remove_hash256_bytes callers
read $id, $dataContractId and $groupActionId — identifiers, where base58 is correct — and are
unchanged.

Added should_read_entropy_as_base64_from_the_json_form, which feeds $entropy as the base64 text
the JSON form writes and asserts the bytes come back intact.

How Has This Been Tested?

Red before green. Against the unfixed parser:

a base64 $entropy is what the JSON form writes, so it must parse:
  ValueError(StructureError("value was a string, but could not be decoded from base 58"))
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 4882 filtered out

After the change:

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 4882 filtered out

Full crate suite, which includes the two existing round-trip tests in this module:
4877 passed; 0 failed; 6 ignored; 0 filtered out. cargo fmt --check -p dpp clean;
cargo clippy -p dpp --all-features clean.

A round trip through to_object() cannot catch this defect — that path yields Value::Bytes32, not
Value::Text, so the text decoder is never consulted. The new test goes through the JSON form for
exactly that reason.

Breaking Changes

None.

This is not a consensus change, so no new protocol version is needed:

  • The consensus representation for state transitions is bincode. StateTransition is
    #[platform_serialize] and drive-abci decodes via
    StateTransition::deserialize_from_bytes_untrusted*; the bincode
    Encode/Decode/DecodeUntrusted derives on DocumentCreateTransitionV0 ignore serde
    attributes and never reach this parser.
  • from_value_map is pub(crate), called only from the DocumentTransitionObjectLike impl in
    document_create_transition/convertible.rs. That trait has no importer anywhere outside
    rs-dpp/src/state_transition (the sole other mention in the repo is a commented-out line in
    wasm-dpp), and inside rs-dpp only two #[cfg(test)] call sites use it.
  • The sibling JSON entry point never reached the bug: from_json_object normalises $entropy to
    Value::Bytes via ReplacementType::BinaryBytes (base64) before calling from_value_map. Only a
    Value::Text passed straight to from_object hit the base58 decoder.

So no released protocol version changes what it accepts, signs or stores. The behaviour change is
confined to a client/platform_value ingest path, which now accepts the encoding the matching
writer already produced.

Noticed, not fixed

ReplacementType::replace_value_in_place unconditionally base58-decodes, ignoring self, while
replace_leaf sixty lines below in the same file dispatches correctly. So one
ReplacementType::BinaryBytes means base58 through one function and base64 through the other. It is
dormant — neither caller has a caller outside that file's own tests — and an existing test pins the
base58 behaviour with a comment asserting it is intended, so settling it means deciding which of the
two is right. That belongs in its own change.

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 42716ec

  • Bots — coderabbitai ✓ · thepastaclaw ✓
  • Self-review — posted; again after any push
  • Within your 5 open PRs
  • Build green
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected parsing of document entropy from JSON so 32-byte values are preserved accurately.

…on map parser

`DocumentCreateTransitionV0::from_value_map` read `$entropy` with
`remove_hash256_bytes`, which decodes a text value as base58 — the
identifier convention. `$entropy` is raw bytes: it is the sole member of
the struct's `BINARY_FIELDS`, `to_value_map` writes it as `Value::Bytes`,
and `Value::Bytes` crosses JSON as base64 (`Value::Identifier` is what
crosses as base58). The struct's own hand-written `Deserialize` already
decoded the text form as base64, so one struct read one field two ways and
a transition did not survive a trip through its own JSON form.

Switch to `remove_bytes_32`, the base64 member of the same helper family.
The other `remove_hash256_bytes` callers nearby read `$id`,
`$dataContractId` and `$groupActionId` — identifiers, where base58 is
correct — and are left alone.

Not a consensus change. The consensus representation for state transitions
is bincode, whose `Encode`/`Decode` derives ignore serde and never touch
this parser. `from_value_map` is `pub(crate)` and reachable only through
`DocumentTransitionObjectLike`, a trait with no importer outside
`rs-dpp/src/state_transition`; `from_json_object` additionally normalises
`$entropy` to `Value::Bytes` (base64, via `ReplacementType::BinaryBytes`)
before calling it, so only a `Value::Text` handed straight to
`from_object` ever reached the base58 decoder.

Test would have caught this in CI: the new
`should_read_entropy_as_base64_from_the_json_form` fails on the unfixed
parser with `ValueError(StructureError("value was a string, but could not
be decoded from base 58"))` and passes after the change. A round trip
through `to_object()` cannot catch it, because that path yields
`Value::Bytes32` rather than `Value::Text`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions github-actions Bot added this to the v4.2.0 milestone Sep 27, 2026
@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 27, 2026
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: dashpay/platform/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 368073bd-8559-498d-9335-5fa4d025a120

📥 Commits

Reviewing files that changed from the base of the PR and between 7c41b5a and 42716ec.

📒 Files selected for processing (1)
  • packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

DocumentCreateTransitionV0::from_value_map now reads $entropy as 32-byte binary data. A comment describes its base64 JSON encoding, and a test checks that parsing base64 entropy returns the original bytes.

Changes

Document entropy parsing

Layer / File(s) Summary
Parse and verify entropy
packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs
from_value_map reads $entropy with remove_bytes_32. A comment documents the base64 JSON encoding. A test checks that parsing base64 input returns the original 32 bytes.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: quantumexplorer

Merge Risk: ⚪ Minimal · up to 42716

This change makes document-create transition parsing read $entropy as base64, matching how it is serialized to JSON. It is a small, tested fix with no identified regression, so merge risk is minimal.

Architecture Summary

Architecture risk: 🔵 Low · up to 42716

The change affects 1 system.

Changed systems: packages/rs-dpp

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — packages/rs-dpp (library) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs: from_value_map now reads $entropy as base64-encoded bytes with remove_bytes_32 and converts them to a buffer; it no longer uses the base58-decoding remove_hash256_bytes reader.
  • observed — Modified behavior in packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs: The comment now states that $entropy is serialized as Value::Bytes and read as base64, unlike identifier fields, which use base58.
  • observed — Modified behavior in packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs: Adds a test that supplies base64-encoded $entropy to from_object and checks that the resulting V0 transition contains the original 32-byte value.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: parsing $entropy as base64 instead of base58 in the create-transition map parser.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 1 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 42716ec) · triage: low

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

Verified the complete diff at a35582d against the supplied reviews. The parser now uses the base64 reader appropriate for raw entropy, retains 32-byte validation, and leaves consensus binary decoding untouched; the regression test detects reintroduction of the original bug. No actionable in-scope findings remain. Verification used source inspection and an independent encoding-fixture check; Rust tests were not rerun.

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: architecture-layering); reviewer 3: glm-5.3-flash (agent: phase1-reviewer, role: rust-quality); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: low by gpt-6-astra (effort low) — Small, well-contained parser fix in DocumentCreateTransitionV0 with a focused regression test, and although it affects peer-facing deserialization, it only corrects JSON-form parsing without changing consensus serialization or protocol behavior.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — architecture-layering (completed, effort high); agent phase1-reviewer, glm-5.3-flash — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 98% left, weekly 25% left; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 13% left, 5h 100% left)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer

@github-actions

github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Sep 27, 2026
The reader now says why it decodes base64 — because the writer twenty lines
below inserts `$entropy` as `Value::Bytes`, which crosses into JSON as a base64
string — and the writer says the same thing pointing the other way, so the pair
is findable from either end.

It also says the part that makes this easy to get wrong: `remove_hash256_bytes`
decodes base58 despite a name that sounds like it is about the width. Base58 is
the identifier convention, which is why the identifier fields in the same family
keep that reader and this one does not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Sep 29, 2026
The branch was 109 commits behind, and the continuous integration definitions
moved in that window, so its jobs asked for a runner image that no longer
exists. No conflicts; the change itself is still one file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@shumkov

shumkov commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

/self-reviewed

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

The parser fix is correct and matches the existing JSON writer: $entropy is now decoded as base64 while identifier fields remain base58. No consensus, layering, or runtime correctness issue was found; the only in-scope concern is that the regression test does not cover the unpadded base64/base58 alphabet-overlap case described in the PR.

🟡 1 suggestion(s)

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: architecture-layering); reviewer 3: glm-5.3-flash (agent: phase1-reviewer, role: rust-quality); reviewer 4: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: low by gpt-6-astra (effort low) — The diff makes a small, contained parser correction by switching one entropy field from a base58 helper to the existing base64 helper and adding a focused regression test, without introducing intricate logic or broad behavioral changes.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — architecture-layering (completed, effort high); agent phase1-reviewer, glm-5.3-flash — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 99% left, weekly 86% left; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 13% left, 5h 100% left)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer, gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer
🤖 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-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs`:
- [SUGGESTION] packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/batched_transition/document_create_transition/v0/mod.rs:761-783: Add coverage for the ambiguous unpadded base64/base58 case
  The regression test uses `BASE64_STANDARD.encode(entropy)` for 32 bytes, which includes a trailing `=`. That catches the old base58 reader because `=` is invalid in base58, but it does not exercise the silent-corruption case identified in the PR description: an unpadded 43-character base64 value using only characters shared with base58 can be accepted by both decoders and produce different 32-byte results. Add a test using an unpadded encoding of `[1_u8; 32]` and assert that the parsed entropy is exactly `[1_u8; 32]`. This pins both the base64 convention and the helper's padding-indifferent behavior.
Out-of-scope follow-up suggestions (2)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • ReplacementType::replace_value_in_place ignores its encoding dispatch — rs-platform-value's replace_value_in_place unconditionally decodes text through the base58 identifier path, while replace_leaf dispatches BinaryBytes and TextBase64 through base64. This is a concrete inconsistency in a public replacement API, but it is pre-existing, has no production callers in the repository, and is unrelated to this focused $entropy parser fix.
    • Follow-up: Track separately in rs-platform-value and decide the intended text encoding before changing the existing behavior and tests.
  • Per-call-site comments re-derive a convention that rs-platform-value should name at the helper level — NOT_ACTIONABLE: The changed call site is behaviorally correct and already documents why it uses the base64 helper. Renaming or documenting the shared rs-platform-value helper family is broader API-hardening work outside this focused parser fix.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

Comment on lines +761 to +783
fn should_read_entropy_as_base64_from_the_json_form() {
let data_contract = data_contract_with_dynamic_properties();
let entropy = [14_u8; 32];

let raw_document = platform_value!({
"$protocolVersion" : 0u32,
"$version" : "0".to_string(),
"$id" : Identifier::from([11_u8; 32]),
"$type" : "test",
"$dataContractId" : Identifier::from([13_u8; 32]),
"$identityContractNonce": 0u64,
"revision" : 1u32,
"$entropy" : BASE64_STANDARD.encode(entropy),
"$action": 0u8,
});

let transition = DocumentCreateTransition::from_object(raw_document, data_contract)
.expect("a base64 $entropy is what the JSON form writes, so it must parse");

match transition {
DocumentCreateTransition::V0(v0) => assert_eq!(v0.entropy, entropy),
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟡 Suggestion: Add coverage for the ambiguous unpadded base64/base58 case

The regression test uses BASE64_STANDARD.encode(entropy) for 32 bytes, which includes a trailing =. That catches the old base58 reader because = is invalid in base58, but it does not exercise the silent-corruption case identified in the PR description: an unpadded 43-character base64 value using only characters shared with base58 can be accepted by both decoders and produce different 32-byte results. Add a test using an unpadded encoding of [1_u8; 32] and assert that the parsed entropy is exactly [1_u8; 32]. This pins both the base64 convention and the helper's padding-indifferent behavior.

source: glm-5.3-flash (phase1-reviewer: general, architecture-layering, rust-quality)

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Sep 29, 2026
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the waiting-self-review Waiting for the author to post /self-reviewed label Oct 2, 2026
@shumkov
shumkov merged commit 4cf12f2 into v5.0-dev Oct 3, 2026
36 checks passed
@shumkov
shumkov deleted the fix/document-create-entropy-base64 branch October 3, 2026 09:16
@PastaPastaPasta PastaPastaPasta mentioned this pull request Oct 5, 2026
1 of 22 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants