Skip to content

fix: sort equal-length CBOR map keys bytewise - #555

Open
yanggu0t wants to merge 1 commit into
IntersectMBO:mainfrom
yanggu0t:fix/canonical-map-key-order
Open

yanggu0t wants to merge 1 commit into
IntersectMBO:mainfrom
yanggu0t:fix/canonical-map-key-order

Conversation

@yanggu0t

Copy link
Copy Markdown

Problem

Canonical map encoding currently sorts encoded keys only by length. For equal-length keys, the comparator returns zero, so the emitted bytes still depend on insertion order. This also affects custom encoding with sortMapKeys: true.

For example:

const value = new Map([
  [new Uint8Array([0, 2]), 20n],
  [new Uint8Array([0, 1]), 10n]
])
CBOR.toCBORHex(value, CBOR.CANONICAL_OPTIONS)
// Before: a2420002144200010a
// After:  a24200010a42000214

This surfaced as a Ledger transaction-hash mismatch in a downstream application: two equal-length token policy IDs were emitted in insertion order, while the wallet's hardware-signing request ordered them bytewise. Swapping only those two policies reproduced the device-returned hash. The regression fixtures here use synthetic values and contain no user wallet data.

Change

Add a bytewise tie-break after the existing encoded-key length comparison. This preserves the existing length-first ordering while making equal-length keys deterministic, as described in RFC 8949 section 4.2.3.

No API or dependency changes. Default unsorted encoding and explicitly captured format preservation remain unchanged. This does not change the existing length-first mode to RFC 8949 core deterministic lexicographic ordering.

Validation

  • Observed the new equal-length canonical regression fail before the source change.
  • 336 tests pass across 19 CBOR, transaction, multi-asset, mint and Plutus value test files.
  • Package TypeScript check and changed-file ESLint pass.
  • Regressions cover canonical/custom sorted maps, common-prefix byte keys, text keys, length-first precedence, nested policy/asset-name maps, and unchanged default/format-preserving behavior.

No hardware device was available for a new signing session; the downstream diagnosis used previously captured device responses. The full repository integration suite was not run.

This branch has not been deployed

No deployments
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.

1 participant