Repository navigation
Feat/cesr pq codes - #413
Conversation
daidoji
left a comment
There was a problem hiding this comment.
PQ stuff looks good.
2AAA and 3AAA were used a long time ago for testing cesr codes but were moved away in keripy without fanfare. https://github.com/WebOfTrust/keripy/blame/6473d7efe811254763986555dc1d9873b9d8524d/src/keri/core/coring.py#L318
signify-ts has the primitive classes (Matter/Counter/Indexer) and EMITS framed
streams (eventing.messagize) but has no parser that CONSUMES a stream. Add
src/keri/core/parsing.ts: a deterministic v1 stream walker that frames messages
by version-string size + attachment counters (never by sniffing a leading '{',
so binary CBOR/MGPK bodies work too), delegating all primitive/counter/indexer
sizing to the existing classes. Every node carries byte-span provenance, and the
walk is resilient — on a code it cannot frame it stops and reports, keeping
everything parsed so far. Body decoders are pluggable (JSON built in). Exported
via src/exports.ts; 30 inline keripy-vector tests in test/core/parsing.test.ts.
Scope: CESR v1 only; the v2 count/genus/version-string machinery is a separate
follow-up.
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
…erable Nothing compared a DECLARED length against the bytes actually available, so a truncated stream parsed as a complete one. Reported by @daidoji on WebOfTrust#402: `{"v":"KERI10JSON100000_"}` — 25 bytes claiming 0x100000 — returned one message, no errors, and a `consumed` and `span.end` a megabyte past the end of the buffer, because subarray clamps silently and the clamped slice happened to be valid JSON. The same omission ran through the attachment framing (a truncated -V framed `state: 'known'` past the buffer; a truncated -A framed unframable-group, which condemns bytes that were merely absent), and produced a hang: a version string with size 0 and a serialization with no registered decoder never advanced the cursor, pushing a message per pass until the heap died — about 40s to 4 GB in node, from 25 bytes of input. - ParseError.permanent is a boolean; `incomplete` carries false, the one failure more bytes can cure. New `invalid-version-size` rejects a size too small to hold its own version string, which makes forward progress an invariant of the parse loop rather than a special case for 0. - Primitive and counter shortage is read from the Matter/Indexer/Counter size tables BEFORE construction — a throw could never tell short from malformed. - An incomplete message is not emitted and `consumed` stays at its first byte, so a caller appends bytes and re-parses with no double-emit. - A truncation sweep parses nine vectors cut at every byte offset, asserting termination and that no span or `consumed` ever exceeds the input: the class of bug, not the one example, is what went undetected. One corner is left: a version string cut in half still reports no-version-string, since deciding that needs a "could these bytes still become a legal message start" test rather than a length check. The sweep pins its exact bound rather than allowing any permanent error. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
The Matter/Indexer size tables store a variable-size code's `fs` as null while typing it `fs?: number`, so the preceding commit's `fs === undefined || fs < 0` let null through (null >= 0 is true) and handed back a null length. It only looked harmless because the empty slice made the constructor throw and the catch called it 'bad'. Tested by value with typeof now. Found by cesrview's 100% coverage gate on the same code, which flagged that the bounds checks split several one-line failure paths in two and left six new branches untested. Tests added for the distinctions the split created, each a real one: a primitive that is the right SIZE but the wrong bytes (sizing says yes, decoding says no); a counter whose bytes are all present but are not ASCII; a compound group whose NESTED group is malformed vs cut off; a primitive hard code cut off vs one in no size table vs one that is variable-size; a big counter's 3-character hard code cut off; and a -V whose inner group is wholly present but overflows the wrapper, which is not shortage — it belongs to no one — so the wrapper still stands as a resilience boundary. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
Stacks on the v1 stream parser (WebOfTrust#402): the parser now also handles CESR 2.0 / KERI 2.x streams, ground-truthed to keripy 2.0.0-dev6. - parseVersion parses the v2 version string (proto + protocol-version + embedded CESR-genus-version + kind + base64 size + '.') and returns the genus. - frameGroup dispatches by genus. Native v2 counter framing (from keripy's CtrDex_2_0) is added because signify-ts's Counter carries only the v1 table and silently misframes v2 codes (they collide with v1 strings but denote different groups). Every v2 group counts its body in quadlets, so it self-frames as count*4 bytes — decomposition is uniform and even unrecognized codes are unknown-but-framed, with the -V resilience-boundary rule generalized to all groups. Primitives still delegate to Matter/Indexer (genus-stable). - AttachmentGroup gains `genus`, since a code's meaning depends on it. Adds v2 parseVersion, framing, and resilience/corruption tests, plus a real keripy-generated v2 witness-OOBI vector. All four CI gates green locally. The v2 framing carries the same bounds-checking the preceding commit added for v1: parseV2Counter distinguishes a header cut off by the end of the stream from one whose soft count is not base64, and a v2 group whose count*4 quadlets run past the end is short rather than framed. Self-framing is exactly the property a truncated stream makes a lie of, so the truncation sweep runs over the v2 OOBI vector too. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
`CesrMessage.sn` was populated from the body's `s` field for every protocol. Under KERI that field is the sequence number, a hex-encoded integer; under ACDC the same field name holds the schema SAID, an unrelated value. So parsing an ACDC handed the caller a 44-character digest in a field documented as a sequence number, and any consumer that compared or ordered on `sn` would act on it. Gate the assignment on the protocol and say so in the field's doc comment. Nothing is lost for ACDC callers: the schema SAID is still on `sad.s`, where it belongs. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
The spec's SAD Path Examples section carries a bare genus-2 ACDC with no attachments — a shape the suite did not cover, since every other v2 vector is a KERI event and most carry attachment groups. @daidoji reported it failing to parse on PR WebOfTrust#403, which it did until the v2 version string was read; this pins the behaviour so it cannot regress. Covers parseVersion on an ACDC v2 string (base64 size AAIe = 542) and full framing: one message, no errors, consumed == length, the nested attribute block intact, and `sn` null because `s` here is the schema. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
4ed767b to
c5bc46a
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #413 +/- ##
=======================================
Coverage 97.46% 97.46%
=======================================
Files 1 1
Lines 79 79
Branches 28 28
=======================================
Hits 77 77
Misses 2 2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
My main criticism of this parser is that it is a batch parser in its current form and is not suitable as a streaming parser. This means that it expects complete CESR streams for the A problem with such a batch parser would be hooking it up to a network stream that arrives in chunks and then receiving a complete CESR message body and considering that the whole message prior to receiving the attachments. Then, the attachments might arrive late and never be considered part of the body. This is more a problem in CESR v1 streams since KERIpy in v1, where SignifyTS' CESR primitives and parsing mental model is inspired or copied from, does not frame the CESR message body and attachments like CESR v2 does. Group codes in CESR v2 wrap all KERIpy CESR streams which means that the type-length-value (TLV) CESR size values for the stream-bounding group code can be relied upon to instruct a parser when to wait on the network for more bytes. CESR v1 does not have such a convenience. The way KERIpy's CESR parser handled this scenario was to just always assume there were attachments with messages and to just wait for them. This current parser architecture does not support waiting for more bytes or an analog to a ShortageError from KERIpy. We could merge it as is and then just change it later because there's a lot of valuable work in this parser and I lean towards merging, though a fast follow PR should include proper streaming support. My keri-ts implementation has streaming support yet is a different parsing design and uses the feed/flush incremental streaming parser. I do like it, even better than KERIpy's parser architecture since it seems a better fit for Typescript, though it can be a matter of taste. While I do have other review comments on the PR I suggest we add proper incremental/streaming parser support first prior to merging this since that would be a reasonable performance and capability improvement and would align the signify-ts parser design closer with what KERIpy uses. I'm more than happy to submit my desired change as a PR to your branch, @dhh1128 , yet a proper incremental parser is a big enough change that it might make more sense to have it be a separate PR since I would change so much. |
|
Hmm, you know what, I'll just accept this parser implementation and then submit my comments as pull request changes. This is a good place to start. |
`genus` held only the genus major, so 2.0 and 2.1 material were
indistinguishable. It is now a `GenusVersion` ({major, minor}) on every
`AttachmentGroup`, and `CesrMessage` gains the same field. Counter-table
dispatch still keys on the major. A v1 stream is genus 1.0.
The types are new exports that have not shipped, so the shape changes now
rather than as a breaking change after a release. Raised by @kentbull on
WebOfTrust#413.
Claude-Session: https://claude.ai/code/session_01EDJMKwuf8DgsxNiEF4kUNq
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
c5bc46a to
b432abd
Compare
|
Thanks, Kent. I'm happy with that plan: land this, and take a feed/flush incremental parser as a follow-up from you, since you've already built one in keri-ts. One correction on the diagnosis, because it narrows what the follow-up has to fix. The parser does detect shortage, just not everywhere. A body whose declared size runs past the buffer, or attachments that end mid-element, come back as an The gap you describe is real, though, and it sits at element boundaries. If a v1 chunk ends exactly after a complete body, or exactly between two attachment groups, the parser has no way to know more groups are coming, so it emits the message as complete. When the rest arrives it starts with a counter rather than a version string, and that's a permanent |
The v1 version-string pattern took decimal digits, so a valid token like `KERI1aJSON00012b_` (protocol version 1.10) was rejected as no version string at all. keripy's VEREX1, and signify-ts's own VEREX in core.ts, read the major and minor as hex, like the size. Reported by @kentbull on WebOfTrust#413. Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
parseVersion searched a 128-byte window and tried the v2 layout first, so a
version-like string inside a field value could take over the outer
message's framing: on `{"v":"KERI10JSON000033_","x":"KERICAACAAJSONAAD_."}`
it framed a 255-byte v2 message from byte 30 and reported the whole 51-byte
message as recoverably incomplete, so a caller would wait forever.
It now does what keripy's smell does: one combined v2|v1 search for the
earliest token, rejected if it starts more than MAXVSOFFSET (8) bytes in.
The window is read one character per byte, so offsets are byte offsets
behind a CBOR or MGPK header. And when fewer than SMELLSIZE bytes remain and
no token is found, the result is `incomplete` rather than a permanent
`no-version-string` (keripy's ShortageError at the same point), since the
token may be cut off. Reported by @kentbull on WebOfTrust#413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
…sn, gvrsn
parseVersion is now smell, returning a Smellage of proto, pvrsn, kind,
size and gvrsn, the names keripy uses for the same function and tuple. The
old private name `Version` also collided with the `Version` class that
core.ts already exports.
Both versions are now that core `Version` ({ major, minor }, keripy's
Versionage): the protocol version was a '1.0'-style string, and the
parser-local GenusVersion type is gone. `genus` is `gvrsn` on every
AttachmentGroup and on CesrMessage, and `version` is `pvrsn`.
The `length` field is dropped. A version string is 17 bytes in v1 and 19 in
v2 (keripy's VER1FULLSPAN and VER2FULLSPAN), so the too-small-size check
uses those constants. Requested by @kentbull on WebOfTrust#413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
A CesrMessage is now { body, attachments }, the shape of keri-ts's
CesrMessage. The body (CesrBody) carries what the version string says
(proto, pvrsn, gvrsn, kind, size), the ilk and SAID, the field map, and
its bytes as both `raw` and `span`. Grouping them makes plain that the
top-level fields describe the body only: each attachment group already
carried its own gvrsn, which is what lets v2 groups nest and interleave
genera.
`raw` is a subarray view, not a copy, so it is free while the caller holds
the buffer; `span` stays for provenance. `sn` is removed: a sequence number
is a KERI field, not a framing one, and the need to special-case ACDC's
`s` was the sign it did not belong here. Callers read it from `sad`.
Requested by @kentbull on WebOfTrust#413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
Records which code stands for ShortageError, UnknownCodeError and ColdStartError, and that the cold-start analog covers only the message domain until the parser classifies a stream's first byte. Requested by @kentbull on WebOfTrust#413. Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
CESR 1.1 defines 33 post-quantum primitives — FN-DSA (Falcon), ML-DSA and SLH-DSA public keys, signatures and private-key seeds — across the four-character `1`, `2` and `3` fixed tables. The spec requires them there rather than in the one- and two-character tables because every post-quantum primitive is large: the smallest signature is 666 B and the largest 29,792 B, so a four-character code costs under half a percent of the encoding while the compact tables stay available for primitives that need them. Sizes only, deliberately. Framing needs sizes, and the parser gets post-quantum support for free once the table has them — no change to parsing.ts. Named MatterCodex constants are left out so signify-ts does not coin 33 names that then diverge from keripy's when it adds these codes; naming should follow the reference implementation, and adding names later is additive. TWO EXISTING ROWS CHANGE MEANING. `2AAA` and `3AAA` held Sizage(4, 0, 8, 1) and Sizage(4, 0, 8, 2) — vestigial test placeholders from a keripy that no longer exists. keripy has used `2___` and `3___` for that purpose at every version I can find, including 1.x, and nothing in this repository referenced either row: no MatterCodex constant, no use in src or test. CESR 1.1 assigns them the FN-DSA-1024 and ML-DSA-44 public keys. Flagging it explicitly rather than letting it ride in as a diff line, since it is a code-table change; a test pins the new meanings. The tests check the table against arithmetic the spec makes checkable — every full size a multiple of 4, every lead size following the selector, every raw plus lead aligning on 24 bits, and a round-trip through Matter at all 33 codes — and then against real cryptography: a CESR-1 stream where an Ed25519 inception is receipted by a witness signing with Falcon. That vector's FN-DSA-512 keypair and signature are real, generated with @noble/post-quantum over the receipted event's exact bytes, so the exhibit verifies; signify-ts ships no Falcon implementation and so cannot check that here, but framing it is the point. CESR 1.1 defines no INDEXED post-quantum signature code, so a post-quantum signature can never be a controller or witness indexed signature. That negative requirement gets a positive oracle rather than a comment: one test asserts no Indexer-class primitive appears in the exhibit, and another that a post-quantum code in a -A group does not resolve however well it would resolve as Matter. Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
b432abd to
e7aaa09
Compare
CesrMessage's body fields moved under `body` in acf1794, below this commit's base, so the PQ exhibit test reads `m.body.ilk`. Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
|
Okay, I know I have a bunch more review comments, yet I will submit my comments as a future PR. I like this as a first draft and am approving and merging it now. |
kentbull
left a comment
There was a problem hiding this comment.
Conditionally approved. A fast follow on PR or set of PRs should address the following points, in priority order:
- Incremental streaming: Preserve parsing progress across network chunks, keeping messages open until their attachments are complete. Test chunk boundaries to prevent lost attachments or duplicate messages.
- Recursion limits: Limit attachment-group nesting and return a parsing error instead of an uncaught stack overflow.
- Attachment completeness: Reject malformed contents inside known attachment wrappers instead of silently returning a partial decomposition as successful. Preserve intentionally opaque payloads explicitly as bytes.
- Pathed attachments: Decode -L paths and associate embedded attachments with their corresponding events for multisig and IPEX processing.
- V1 interoperability: Add focused coverage for current KERIA credential CESR stream exports, witness receipts/replay, mailbox payloads, and controller exchanges. Separately fix inherited Ed448 sizing and messagize() witness/receipt serialization defects.
- V2 version handling: Apply leading and nested genus-version selectors to subsequent parsing, respecting enclosure boundaries. Reject unsupported versions instead of falling through to v1 handling.
`genus` held only the genus major, so 2.0 and 2.1 material were
indistinguishable. It is now a `GenusVersion` ({major, minor}) on every
`AttachmentGroup`, and `CesrMessage` gains the same field. Counter-table
dispatch still keys on the major. A v1 stream is genus 1.0.
The types are new exports that have not shipped, so the shape changes now
rather than as a breaking change after a release. Raised by @kentbull on
#413.
Claude-Session: https://claude.ai/code/session_01EDJMKwuf8DgsxNiEF4kUNq
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
The v1 version-string pattern took decimal digits, so a valid token like `KERI1aJSON00012b_` (protocol version 1.10) was rejected as no version string at all. keripy's VEREX1, and signify-ts's own VEREX in core.ts, read the major and minor as hex, like the size. Reported by @kentbull on #413. Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
parseVersion searched a 128-byte window and tried the v2 layout first, so a
version-like string inside a field value could take over the outer
message's framing: on `{"v":"KERI10JSON000033_","x":"KERICAACAAJSONAAD_."}`
it framed a 255-byte v2 message from byte 30 and reported the whole 51-byte
message as recoverably incomplete, so a caller would wait forever.
It now does what keripy's smell does: one combined v2|v1 search for the
earliest token, rejected if it starts more than MAXVSOFFSET (8) bytes in.
The window is read one character per byte, so offsets are byte offsets
behind a CBOR or MGPK header. And when fewer than SMELLSIZE bytes remain and
no token is found, the result is `incomplete` rather than a permanent
`no-version-string` (keripy's ShortageError at the same point), since the
token may be cut off. Reported by @kentbull on #413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
…sn, gvrsn
parseVersion is now smell, returning a Smellage of proto, pvrsn, kind,
size and gvrsn, the names keripy uses for the same function and tuple. The
old private name `Version` also collided with the `Version` class that
core.ts already exports.
Both versions are now that core `Version` ({ major, minor }, keripy's
Versionage): the protocol version was a '1.0'-style string, and the
parser-local GenusVersion type is gone. `genus` is `gvrsn` on every
AttachmentGroup and on CesrMessage, and `version` is `pvrsn`.
The `length` field is dropped. A version string is 17 bytes in v1 and 19 in
v2 (keripy's VER1FULLSPAN and VER2FULLSPAN), so the too-small-size check
uses those constants. Requested by @kentbull on #413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
A CesrMessage is now { body, attachments }, the shape of keri-ts's
CesrMessage. The body (CesrBody) carries what the version string says
(proto, pvrsn, gvrsn, kind, size), the ilk and SAID, the field map, and
its bytes as both `raw` and `span`. Grouping them makes plain that the
top-level fields describe the body only: each attachment group already
carried its own gvrsn, which is what lets v2 groups nest and interleave
genera.
`raw` is a subarray view, not a copy, so it is free while the caller holds
the buffer; `span` stays for provenance. `sn` is removed: a sequence number
is a KERI field, not a framing one, and the need to special-case ACDC's
`s` was the sign it did not belong here. Callers read it from `sad`.
Requested by @kentbull on #413.
Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez
Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
Records which code stands for ShortageError, UnknownCodeError and ColdStartError, and that the cold-start analog covers only the message domain until the parser classifies a stream's first byte. Requested by @kentbull on #413. Claude-Session: https://claude.ai/code/session_01WRfCuQNE3iHSDxqvPGMUez Signed-off-by: Daniel Hardman <daniel.hardman@gmail.com>
|
@kentbull The parser work was probably fine but I don't know if we should have merged this with codes that signify-ts doesn't support (because we don't implement the PQ algorithms) and that aren't approved into the main CESR spec yet (there was a PR from Daniel that was inadvertently merged that was discussed on this weeks call which may have led to the confusion). |
This adds the 33 post-quantum primitive codes from CESR 1.1 to
Matter.Sizes: FN-DSA (Falcon), ML-DSA, and SLH-DSA public keys, signatures, and private-key seeds. It's stacked on #403, so it shows those commits too until they merge. The last one is the commit to look at.The part I'd most like feedback on is that two existing rows change meaning. In the pre-PR code,
2AAAand3AAAcurrently holdSizage(4, 0, 8, 1)andSizage(4, 0, 8, 2). They look like leftover test placeholders from an older keripy: there's noMatterCodexconstant for either, nothing in src or test refers to them, and keripy uses2___and3___for that purpose in every version I looked at, including 1.x. CESR 1.1 gives those two codes to the FN-DSA-1024 and ML-DSA-44 public keys. I think the change is safe, but I could have missed a caller, so please let me know if either row is doing work somewhere.I stopped at sizes and didn't add
MatterCodexconstants. keripy hasn't named these codes yet, and if signify-ts names 33 of them first, I'd expect the two to drift apart. Adding names later doesn't break anything. If you'd rather have them now, I'll put them in.There's no change to
parsing.ts. The parser picks these up as soon as the table has them.The tests use two oracles, because a transcription slip in 33 rows of large numbers is otherwise invisible. One is arithmetic the spec makes checkable: each full size divides by 4, each lead size follows the selector, each raw-plus-lead falls on a 24-bit boundary, and a raw value of the implied length round-trips through
Matterto the declared length. That last check exercises thels > 0path for the 19 codes in the2and3tables.The other oracle is real cryptography. The vector is an Ed25519 inception receipted by a witness signing with Falcon. Its FN-DSA-512 keypair and signature are genuine, made with
@noble/post-quantumover the receipted event's exact bytes, so the signature verifies against the key sitting next to it. signify-ts has no Falcon implementation and can't check that here, but it can frame it. The generator is scripts/make-falcon-sample.mjs in bakobo/cesrview if you want to regenerate or check the vector yourself.CESR 1.1 has no indexed post-quantum signature code, so a Falcon signature can't be a controller or witness indexed signature, and a
-Creceipt couple is the only v1 carrier for it. That's what the vector uses. There's also a test asserting that no Indexer primitive shows up in it, since a negative requirement with no failing test tends to get quietly dropped.A couple of things I ran into look more like spec questions than PR questions.
1AAR's 666 bytes is the padded Falcon variant; plain falcon512 gave me 652 bytes in one run, which the code can't encode. And there's no non-transferable-prefix code for any post-quantum algorithm, only the plain verification key, so the vector puts a Falcon key where a prefix would normally go. Between that and the missing indexed code, I don't think there's a fully specified way right now to attach a post-quantum signature to a KERI event. I can raise both with the KSWG; neither affects this PR.