did-btcr2-js

ADR 154: The JCS Serializer Sorts Every Object and Refuses NaN, Infinity, and a Lone Surrogate

Context

JSON Document Hashing uses JCS

The specification (Algorithms, JSON Document Hashing) has the step “Encode the document using JCS”. Each hash of the method uses this algorithm. Examples are the genesis bytes of an EXTERNAL DID and the sourceHash and targetHash of an update. Other examples are the hash of a signed update or a CAS Announcement, and the lookup tables of the sidecar data. The BIP340 cryptosuite also applies JCS to the document and to the proof configuration.

RFC 8785 has these rules:

JSON object properties MUST be sorted recursively, which means that JSON child Objects MUST have their properties sorted as well. (section 3.2.3)

Property name strings to be sorted are formatted as arrays of UTF-16 [UNICODE] code units. (section 3.2.3)

Note: Since invalid Unicode data like “lone surrogates” (e.g., U+DEAD) may lead to interoperability issues including broken signatures, occurrences of such data MUST cause a compliant JCS implementation to terminate with an appropriate error. (section 3.2.2.2)

Note: Since Not a Number (NaN) and Infinity are not permitted in JSON, occurrences of NaN or Infinity MUST cause a compliant JCS implementation to terminate with an appropriate error. (section 3.2.2.3)

Irrespective of the method used, the data to be serialized MUST be adapted for I-JSON [RFC7493] formatting (section 3.1)

The list after the last rule includes “JSON string data MUST be expressible as Unicode [UNICODE].” and “JSON number data MUST be expressible as IEEE 754 [IEEE754] double-precision values.” The rules thus apply to parsed data and to data that a program makes.

The old canonicalize did not apply four of these rules

canonicalize made a JSON copy with JSON.parse(JSON.stringify(value)) (ADR 014). Then it gave the copy to json-canonicalize 1.2.0. The table shows the results:

Input Old result RFC 8785
{"b":1,"toJSON":"x","a":2} {"b":1,"toJSON":"x","a":2} {"a":2,"b":1,"toJSON":"x"}
{"v":"\ud800"} (a lone surrogate) {"v":"\ud800"} an error
{"v":NaN}, also {"v":1e400} from JSON text {"v":null} an error
{"v":10n} (a BigInt), or a cycle a TypeError of JSON.stringify no JSON data, so no JCS text

The causes:

The effect on the method

The hash of an object with a data member named toJSON depended on the member order of that object and of each object in it. Example: an EXTERNAL DID whose genesis document has a top-level data member named toJSON. A conformant producer hashes the sorted text. The old resolver gave INVALID_DID for that genesis document in another member order. It gave INVALID_DID_UPDATE for an update that adds a member, because the text of the patched document had the new member at the end.

For a value with no JCS form, each hash step hashed the null form or the escape text. Thus the library made, signed, and verified updates that a conformant implementation refuses. Examples are an update with NaN in a patch value, and a document with a lone surrogate.

The specification names no error type for a JCS failure. The open specification issue 385 asks which errors the resolver raises. This ADR does not depend on an answer to the issue. Each error type below comes from the merged text of the step that hashes the value.

Decision

1. The common package writes JCS with its own serializer

canonicalize makes the JSON form of the value first. The JSON form is the result of JSON.parse(JSON.stringify(value)), as before. JSON.stringify calls each toJSON method, so a class instance and a plain object with the same content give the same text (ADR 014). A replacer function of JSON.stringify checks each value after its toJSON method, in input order. The check is necessary, because JSON.stringify writes NaN and Infinity as null.

Then the internal function serializeJcs writes the JSON form with the rules of RFC 8785 section 3.2:

The common package no longer depends on json-canonicalize.

2. A value with no JCS form gives a CanonicalizationError

canonicalize, canonicalHash, and canonicalHashBytes throw a CanonicalizationError with one of these types:

Type Value
NON_FINITE_NUMBER NaN, Infinity, or -Infinity. This includes a Number object, a number from a toJSON method, and a number that raw JSON text gives as Infinity.
LONE_SURROGATE A string or a member name with a lone surrogate. A surrogate pair is correct data.
NOT_JSON_DATA A BigInt (also a BigInt object), a cycle, or a top-level value with no JSON form, for example undefined.

data.path gives the location of the value as an RFC 6901 JSON Pointer into the JSON form. For a member name with a lone surrogate, the location is the object that holds the name, and the message does not print the name. Each lone surrogate in the location shows as \uXXXX text, so an error message has no lone surrogate.

The checks run in two passes. The replacer checks the numbers, the BigInt values, and the cycles in input order. serializeJcs checks the strings, the member names, and the numbers of raw JSON text in sorted order. The first error stops the canonicalization.

An error from a toJSON method, a getter, a Proxy trap, or a valueOf method passes through unchanged. A Number object is a value with a [[NumberData]] internal slot, so a changed Symbol.toStringTag does not hide it.

canonicalize sets no limit on the depth of a value. A value with too many levels for the call stack gives the error of the JavaScript engine, a RangeError in V8.

3. The resolver gives the error of the step that hashes the value

Step Value with no JCS form Error type
Resolver.external (also NeedGenesisDocument) the genesis document INVALID_DID_DOCUMENT
Resolver.provide for NeedSignedUpdate the signed update INVALID_SIGNAL_DATA
Resolver.provide for NeedCASAnnouncement the CAS Announcement MISSING_UPDATE_DATA

Each error is a ResolveError. data.cause gives the type and the message of the CanonicalizationError.

The other errors of a toJSON method or a getter pass through unchanged.

4. The sidecar maps leave out an item with no JCS form

Resolver.sidecarData puts no update and no CAS Announcement with no JCS form into its maps. No signal can name such an item, because it has no hash. If a beacon signal needs an item that is not in a map, the resolver asks for it with a data need. The caller can then provide it, and decision 3 applies, or the resolution ends with MISSING_UPDATE_DATA.

The basis is the rule for unused sidecar data (Resolve): “[Sidecar Data] that the resolver did not use has no effect on the result.” RFC 8785 section 5 says “If any of these steps fail, the operation in progress MUST be aborted.” That rule applies “before acting upon received data” in a signature scheme. The resolver does not act upon an unused item, and an item that a signal needs still fails. ADR 146, decision 2, ignores a sidecar SMT proof whose id does not decode for the same reason.

The CAS map keeps the JSON form of each announcement, as before (ADR 146, decision 5).

5. The write and create paths refuse a value with no JCS form

6. The cryptosuite gives a CryptosuiteError

7. The aggregation package refuses or catches a value with no JCS form

8. The api exports the two error classes

The api exports CanonicalizationError and CryptosuiteError, because a @throws tag of the facade names them (ADR 132, item 4). The @throws tags of hashDocument and CasApi.publish name CanonicalizationError. The tags of 7 functions of the crypto sub-facade name CryptosuiteError. The JSDoc of getInitialDocument, createExternalFromDocument, and constructUpdate names the new refusal. CasApi.publish publishes nothing for an object with no JCS form.

9. The cli keeps one copy of an entry with no JCS form

The merge of sidecar data keys each entry by its canonical hash, so two entries with the same hash are one entry. An entry with no JCS form has no hash. Its key is json: and its JSON text, so the merge keeps one copy and does not throw. If an entry has no key, it doubles at each write, because each update writes the record again. The resolver does not use such an entry (decision 4).

10. Each judgment call conforms to the specification texts

Judgment call Text Result
Sort an object with a data member named toJSON. RFC 8785 section 3.2.3: “JSON object properties MUST be sorted recursively”. Conforms. A member named toJSON is a property of a JSON object.
Keep the JSON copy before JCS, so a toJSON method gives the JSON form. BIP340 cryptosuite, Transformation (bip340-jcs-2025), step 2: JCS applies “to a JSON serialization of the unsecuredDocument”. Conforms. The JSON serialization of a class instance is the output of its toJSON method.
Refuse NaN, Infinity, and -Infinity, also in a Number object and in raw JSON text. RFC 8785 section 3.2.2.3: “occurrences of NaN or Infinity MUST cause a compliant JCS implementation to terminate with an appropriate error.” Conforms.
Refuse a lone surrogate in a string or a member name. RFC 8785 section 3.2.2.2: “occurrences of such data MUST cause a compliant JCS implementation to terminate with an appropriate error.” Conforms.
Refuse a BigInt, a cycle, and a top-level value with no JSON form. RFC 8785 section 3.1: “JSON number data MUST be expressible as IEEE 754 [IEEE754] double-precision values.” Conforms. These values have no I-JSON form.
Set no depth limit. RFC 8785 and the specification set no depth limit. Conforms. The engine error passes through.
Genesis document with no JCS form: INVALID_DID_DOCUMENT. DID Resolution, Errors: “The DID document was malformed.” Conforms. The document gives no genesis bytes and no initial DID document.
Provided signed update: INVALID_SIGNAL_DATA. Process Beacon Signals: “Raise an [INVALID_SIGNAL_DATA] error if the two hashes are not equal.” Conforms. No hash is equal to update_hash.
Provided CAS Announcement: MISSING_UPDATE_DATA. Process CAS Beacon: “The announcement is not available from [CAS] if the hash of the retrieved content is not equal to map_update_hash”. Conforms. The announcement is not available, so the step raises MISSING_UPDATE_DATA.
Leave an unused sidecar item out of the maps. Resolve: “[Sidecar Data] that the resolver did not use has no effect on the result.” Conforms. RFC 8785 section 5 applies “before acting upon received data”, and an item that a signal needs still fails.
Write path: INVALID_DID_UPDATE. Errors: “An error was found when creating or applying a [BTCR2 Update].” Conforms.
transformDocument: PROOF_TRANSFORMATION_ERROR. VC Data Integrity, Processing Errors: “An error was encountered during the transformation process.” Conforms.
proofConfiguration: PROOF_GENERATION_ERROR. Proof Configuration (bip340-jcs-2025), step 3: “an error MUST be raised and SHOULD convey an error type of PROOF_GENERATION_ERROR.” Step 2 gives the same type. Conforms. Step 4 names no type, and the other steps of the algorithm use this type.
verifyProof gives an error, not verified: false. VC Data Integrity, section 3: “If an error is produced, the verification process failed to complete.” Conforms. The verification cannot complete with no hash.
The participant refuses its own update with no JCS form at submitUpdate. RFC 8785 section 3.2.2.2: “terminate with an appropriate error”. Conforms. The specification names no aggregation step for the refusal. The first JCS step of the member gives the error.
The cli keys an entry with no JCS form by its JSON text. Resolve: “[Sidecar Data] that the resolver did not use has no effect on the result.” Conforms. The resolver ignores the entry, and the cli keeps one copy of it.

Alternatives

Consequences

Superseded.

Unchanged.

Implementation

References