@veridid/kanon 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +156 -2
  3. package/build/KanonApi.d.ts +52 -0
  4. package/build/KanonApi.d.ts.map +1 -0
  5. package/build/KanonApi.js +92 -0
  6. package/build/KanonApi.js.map +1 -0
  7. package/build/KanonModule.d.ts +15 -0
  8. package/build/KanonModule.d.ts.map +1 -0
  9. package/build/KanonModule.js +53 -0
  10. package/build/KanonModule.js.map +1 -0
  11. package/build/KanonModuleConfig.d.ts +123 -0
  12. package/build/KanonModuleConfig.d.ts.map +1 -0
  13. package/build/KanonModuleConfig.js +84 -0
  14. package/build/KanonModuleConfig.js.map +1 -0
  15. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.js +10 -0
  16. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateMetadata.js +7 -0
  17. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateParam.js +9 -0
  18. package/build/anoncreds/helpers/buildKanonCredentialAttributes.d.ts +33 -0
  19. package/build/anoncreds/helpers/buildKanonCredentialAttributes.d.ts.map +1 -0
  20. package/build/anoncreds/helpers/buildKanonCredentialAttributes.js +43 -0
  21. package/build/anoncreds/helpers/buildKanonCredentialAttributes.js.map +1 -0
  22. package/build/anoncreds/helpers/buildKanonProofRequest.d.ts +45 -0
  23. package/build/anoncreds/helpers/buildKanonProofRequest.d.ts.map +1 -0
  24. package/build/anoncreds/helpers/buildKanonProofRequest.js +45 -0
  25. package/build/anoncreds/helpers/buildKanonProofRequest.js.map +1 -0
  26. package/build/anoncreds/helpers/buildKanonSchema.d.ts +23 -0
  27. package/build/anoncreds/helpers/buildKanonSchema.d.ts.map +1 -0
  28. package/build/anoncreds/helpers/buildKanonSchema.js +27 -0
  29. package/build/anoncreds/helpers/buildKanonSchema.js.map +1 -0
  30. package/build/anoncreds/helpers/index.js +3 -0
  31. package/build/anoncreds/index.d.ts +8 -0
  32. package/build/anoncreds/index.js +9 -0
  33. package/build/anoncreds/services/KanonAnonCredsRegistry.d.ts +36 -0
  34. package/build/anoncreds/services/KanonAnonCredsRegistry.d.ts.map +1 -0
  35. package/build/anoncreds/services/KanonAnonCredsRegistry.js +298 -0
  36. package/build/anoncreds/services/KanonAnonCredsRegistry.js.map +1 -0
  37. package/build/anoncreds/services/KanonIssuanceTracker.d.ts +39 -0
  38. package/build/anoncreds/services/KanonIssuanceTracker.d.ts.map +1 -0
  39. package/build/anoncreds/services/KanonIssuanceTracker.js +141 -0
  40. package/build/anoncreds/services/KanonIssuanceTracker.js.map +1 -0
  41. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.d.ts +82 -0
  42. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.d.ts.map +1 -0
  43. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.js +316 -0
  44. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.js.map +1 -0
  45. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.d.ts +67 -0
  46. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.d.ts.map +1 -0
  47. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.js +330 -0
  48. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.js.map +1 -0
  49. package/build/anoncreds/utils/credIdHash.d.ts +2 -0
  50. package/build/anoncreds/utils/credIdHash.js +3 -0
  51. package/build/dids/KanonDidRegistrar.d.ts +47 -0
  52. package/build/dids/KanonDidRegistrar.d.ts.map +1 -0
  53. package/build/dids/KanonDidRegistrar.js +140 -0
  54. package/build/dids/KanonDidRegistrar.js.map +1 -0
  55. package/build/dids/KanonDidResolver.d.ts +18 -0
  56. package/build/dids/KanonDidResolver.d.ts.map +1 -0
  57. package/build/dids/KanonDidResolver.js +88 -0
  58. package/build/dids/KanonDidResolver.js.map +1 -0
  59. package/build/dids/didEtherUtils.d.ts +18 -0
  60. package/build/dids/didEtherUtils.d.ts.map +1 -0
  61. package/build/dids/didEtherUtils.js +47 -0
  62. package/build/dids/didEtherUtils.js.map +1 -0
  63. package/build/dids/index.js +3 -0
  64. package/build/index.d.ts +24 -0
  65. package/build/index.js +25 -0
  66. package/build/ledger/KanonClientService.d.ts +45 -0
  67. package/build/ledger/KanonClientService.d.ts.map +1 -0
  68. package/build/ledger/KanonClientService.js +111 -0
  69. package/build/ledger/KanonClientService.js.map +1 -0
  70. package/build/ledger/index.d.ts +1 -0
  71. package/build/ledger/index.js +1 -0
  72. package/build/utils/identifiers.d.ts +24 -0
  73. package/build/utils/identifiers.d.ts.map +1 -0
  74. package/build/utils/identifiers.js +39 -0
  75. package/build/utils/identifiers.js.map +1 -0
  76. package/build/zk/KanonZkApi.d.ts +186 -0
  77. package/build/zk/KanonZkApi.d.ts.map +1 -0
  78. package/build/zk/KanonZkApi.js +226 -0
  79. package/build/zk/KanonZkApi.js.map +1 -0
  80. package/build/zk/KanonZkIssuerKeyService.d.ts +107 -0
  81. package/build/zk/KanonZkIssuerKeyService.d.ts.map +1 -0
  82. package/build/zk/KanonZkIssuerKeyService.js +137 -0
  83. package/build/zk/KanonZkIssuerKeyService.js.map +1 -0
  84. package/build/zk/KanonZkPathService.d.ts +66 -0
  85. package/build/zk/KanonZkPathService.d.ts.map +1 -0
  86. package/build/zk/KanonZkPathService.js +163 -0
  87. package/build/zk/KanonZkPathService.js.map +1 -0
  88. package/build/zk/KanonZkService.d.ts +91 -0
  89. package/build/zk/KanonZkService.d.ts.map +1 -0
  90. package/build/zk/KanonZkService.js +165 -0
  91. package/build/zk/KanonZkService.js.map +1 -0
  92. package/build/zk/index.d.ts +4 -0
  93. package/build/zk/index.js +4 -0
  94. package/build/zk/modeBLeaves.js +48 -0
  95. package/build/zk/modeBLeaves.js.map +1 -0
  96. package/package.json +66 -3
@@ -0,0 +1,186 @@
1
+ import { KanonClientService } from "../ledger/KanonClientService.js";
2
+ import "../ledger/index.js";
3
+ import { KanonZkIssuerKeyService } from "./KanonZkIssuerKeyService.js";
4
+ import { KanonZkService } from "./KanonZkService.js";
5
+ import { AgentContext } from "@credo-ts/core";
6
+
7
+ //#region src/zk/KanonZkApi.d.ts
8
+ /**
9
+ * Result of `provisionCredDef`. Hand `(ax, ay)` straight to
10
+ * `registerCredentialDefinition` in the same flow — the contract requires the
11
+ * BabyJubjub key inline at registration time.
12
+ */
13
+ interface KanonZkProvisionResult {
14
+ ax: bigint;
15
+ ay: bigint;
16
+ }
17
+ /**
18
+ * Result of `prepareModeBCredential`. The caller MUST set every entry of
19
+ * `attributes` as a credential attribute (so the AnonCreds CL signature covers
20
+ * everything, including the kanon-reserved ones) before kicking off
21
+ * issuance. `kanonCredId` is also returned separately so revocation paths can
22
+ * key off it directly.
23
+ */
24
+ interface KanonZkCredentialPrep {
25
+ /** The full attribute set the issuer should send in the credential. */
26
+ attributes: Record<string, string>;
27
+ /** Convenience — the kanonCredId value, already present in `attributes`. */
28
+ kanonCredId: string;
29
+ /** Convenience — the kanonZkSig value, already present in `attributes`. */
30
+ kanonZkSig: string;
31
+ }
32
+ /**
33
+ * Result of `prepareModeBPresentation`. `selfAttestedAttributes` is what the
34
+ * caller merges into the AnonCreds presentation response so Mode B rides on
35
+ * standard AnonCreds.
36
+ */
37
+ interface KanonZkPresentationPrep {
38
+ selfAttestedAttributes: Record<string, string>;
39
+ }
40
+ /**
41
+ * Mode B application-facing surface. Wired on `agent.modules.kanon.api.zk`.
42
+ *
43
+ * The methods here intentionally do NOT monkey-patch credo's AnonCreds
44
+ * pipeline. Instead they expose the discrete steps a Mode B credDef needs at
45
+ * three points in its lifecycle:
46
+ *
47
+ * - **provisionCredDef** — before registering a Mode B credDef. Generates
48
+ * and persists the issuer BabyJubjub key, returns `(ax, ay)` for the
49
+ * caller to pass to `registerCredentialDefinition`.
50
+ * - **prepareModeBCredential** — at issuance time. Generates a fresh
51
+ * `kanonCredId`, computes the tagged leaf, signs it with the issuer key,
52
+ * and returns the attribute set the caller plugs into the AnonCreds offer.
53
+ * - **prepareModeBPresentation** — at holder presentation time. Builds the
54
+ * Groth16 proof from the credential's persisted sig + the current Merkle
55
+ * state, returns the `selfAttestedAttributes` blob the holder hands to
56
+ * credo's presentation flow.
57
+ * - **verifyModeBPresentation** — at verifier side. Pulls the proof out of
58
+ * the incoming `selfAttestedAttributes`, submits to the on-chain
59
+ * `MerkleStateRegistry.verifyZKMembership`.
60
+ *
61
+ * The introspection helpers (`getActiveLeaves`, `supportsZk`, `resync`) stay
62
+ * unchanged.
63
+ */
64
+ declare class KanonZkApi {
65
+ private readonly zkService;
66
+ private readonly issuerKeyService;
67
+ private readonly clientService;
68
+ private readonly agentContext;
69
+ constructor(zkService: KanonZkService, issuerKeyService: KanonZkIssuerKeyService, clientService: KanonClientService, agentContext: AgentContext);
70
+ /**
71
+ * Read-only snapshot of the active leaf set for a credDef. Useful for
72
+ * dashboards / debug. Triggers a lazy reconstruct on first call after
73
+ * restart (one chain scan per credDef per process).
74
+ */
75
+ getActiveLeaves(credDefId: string): Promise<{
76
+ keccak: string[];
77
+ poseidon: string[];
78
+ }>;
79
+ /** True iff the credDef opted in to `TIER_ZK_SNARK` at registration. */
80
+ supportsZk(credDefId: string): Promise<boolean>;
81
+ /**
82
+ * Force-refresh the local state by dropping the in-process cache and
83
+ * re-running `reconstructFromChain`. Use after an out-of-band write
84
+ * (e.g. another agent published a `batchUpdate`) when you need this
85
+ * agent's view to catch up before the next event tick.
86
+ */
87
+ resync(credDefId: string): Promise<void>;
88
+ /**
89
+ * Provision a Tier-2 BabyJubjub keypair for `credDefId`. Idempotent: if a
90
+ * key has already been persisted for this credDef the existing one is
91
+ * returned without re-publishing.
92
+ *
93
+ * Call this BEFORE `registerCredentialDefinition` and pass the returned
94
+ * `(ax, ay)` straight through — the contract requires the key inline.
95
+ */
96
+ provisionCredDef(credDefId: string): Promise<KanonZkProvisionResult>;
97
+ /**
98
+ * Build the credential attribute set for a Mode B issuance.
99
+ *
100
+ * Inputs:
101
+ * - `credDefId` — on-chain credDef bytes32
102
+ * - `domainAttributes` — `name → value` map of the schema's domain attrs
103
+ * (everything EXCEPT `kanonCredId` and `kanonZkSig`,
104
+ * which are reserved and injected here).
105
+ *
106
+ * Returns the full attribute set the caller plugs into the AnonCreds offer
107
+ * — every value is a string, ordered by AnonCreds' insertion semantics
108
+ * (domain attrs first, then `kanonCredId`, then `kanonZkSig`).
109
+ *
110
+ * The BabyJubjub signature is computed over the SAME tagged leaf the
111
+ * `non_revocation.circom` circuit and the `KanonZkService.addIssued` publish
112
+ * step recompute. The CL signature then covers `kanonZkSig` as a regular
113
+ * attribute, giving the "AnonCreds signs over everything" property.
114
+ */
115
+ prepareModeBCredential(params: {
116
+ credDefId: string;
117
+ domainAttributes: Record<string, string>;
118
+ }): Promise<KanonZkCredentialPrep>;
119
+ /**
120
+ * Build a Mode B SNARK proof and package it as a self-attested attribute the
121
+ * holder hands to credo's standard presentation flow.
122
+ *
123
+ * The holder must supply:
124
+ * - `credDefId` the on-chain credDef bytes32
125
+ * - `kanonCredId` the value of the `kanonCredId` attribute
126
+ * on the credential being presented
127
+ * - `kanonZkSig` the value of the `kanonZkSig` attribute
128
+ * on the credential — the BJJ signature
129
+ * the issuer produced at issuance time
130
+ * - `domainAttributeValues` the credential's domain attributes,
131
+ * IN THE SAME ORDER as at issuance, so the
132
+ * Merkle inclusion proof verifies
133
+ * - `disclosedDomainIndex` which domain attr to selectively disclose
134
+ * - `merklePath` `{ pathElements, pathIndices }` from the
135
+ * current published Mode B Poseidon tree
136
+ * — the caller is responsible for getting
137
+ * this from an indexer or by replaying the
138
+ * on-chain events
139
+ * - `root` the published Poseidon root the path
140
+ * recovers to (must be within the recent
141
+ * window or the verifier rejects)
142
+ * - `challenge` the verifier-supplied nonce (typically
143
+ * the AnonCreds presentation-request nonce)
144
+ * - `wasmPath` / `zkeyPath` paths to the snarkjs artifacts (defaults
145
+ * resolve from the SDK build)
146
+ *
147
+ * Returns `{ selfAttestedAttributes: { kanonZkProof: <base64> } }` — merge
148
+ * into the holder's presentation response.
149
+ */
150
+ prepareModeBPresentation(params: {
151
+ credDefId: string;
152
+ kanonCredId: string;
153
+ kanonZkSig: string;
154
+ domainAttributeValues: string[];
155
+ disclosedDomainIndex: number;
156
+ merklePath: {
157
+ pathElements: bigint[];
158
+ pathIndices: number[];
159
+ };
160
+ root: bigint;
161
+ challenge: bigint;
162
+ wasmPath?: string;
163
+ zkeyPath?: string;
164
+ }): Promise<KanonZkPresentationPrep>;
165
+ /**
166
+ * Validate a Mode B SNARK proof from an incoming presentation.
167
+ *
168
+ * `selfAttestedAttributes` is the map the verifier already has from the
169
+ * AnonCreds presentation. The function:
170
+ * 1. Looks for `kanonZkProof`.
171
+ * 2. Decodes it back into `(proofBytes, publicSignals)`.
172
+ * 3. Submits to the on-chain `MerkleStateRegistry.verifyZKMembership` —
173
+ * which checks recent root, credDefId binding, issuer-key binding,
174
+ * AND runs the Groth16 verifier all in one call.
175
+ *
176
+ * Returns `true` iff the on-chain check passes. The caller decides what to
177
+ * do on `false` — typically reject the presentation as a whole.
178
+ */
179
+ verifyModeBPresentation(params: {
180
+ credDefId: string;
181
+ selfAttestedAttributes: Record<string, string>;
182
+ }): Promise<boolean>;
183
+ }
184
+ //#endregion
185
+ export { KanonZkApi, KanonZkCredentialPrep, KanonZkPresentationPrep, KanonZkProvisionResult };
186
+ //# sourceMappingURL=KanonZkApi.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonZkApi.d.ts","names":[],"sources":["../../src/zk/KanonZkApi.ts"],"mappings":";;;;;;;;;;AA+BA;;UAAiB,sBAAA;EACf,EAAA;EACA,EAAA;AAAA;;;;;;;;UAUe,qBAAA;EAML;EAJV,UAAA,EAAY,MAAA;EAY0B;EAVtC,WAAA;EAWA;EATA,UAAA;AAAA;;;;;;UAQe,uBAAA;EACf,sBAAA,EAAwB,MAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;cA4Bb,UAAA;EAAA,iBAEQ,SAAA;EAAA,iBACA,gBAAA;EAAA,iBACA,aAAA;EAAA,iBACA,YAAA;cAHA,SAAA,EAAW,cAAA,EACX,gBAAA,EAAkB,uBAAA,EAClB,aAAA,EAAe,kBAAA,EACf,YAAA,EAAc,YAAA;EAkBpB;;;;;EANA,eAAA,CAAgB,SAAA,WAAoB,OAAA;IAAU,MAAA;IAAkB,QAAA;EAAA;EAiCnB;EA3B7C,UAAA,CAAW,SAAA,WAAoB,OAAA;EAmD1C;;;;;;EAzCW,MAAA,CAAO,SAAA,WAAoB,OAAA;EA+HtC;;;;;;;;EA9GW,gBAAA,CAAiB,SAAA,WAAoB,OAAA,CAAQ,sBAAA;EAqHxD;;;;;;;;;;;;;;;;;;EA9FW,sBAAA,CAAuB,MAAA;IAClC,SAAA;IACA,gBAAA,EAAkB,MAAA;EAAA,IAChB,OAAA,CAAQ,qBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmFC,wBAAA,CAAyB,MAAA;IACpC,SAAA;IACA,WAAA;IACA,UAAA;IACA,qBAAA;IACA,oBAAA;IACA,UAAA;MAAc,YAAA;MAAwB,WAAA;IAAA;IACtC,IAAA;IACA,SAAA;IACA,QAAA;IACA,QAAA;EAAA,IACE,OAAA,CAAQ,uBAAA;;;;;;;;;;;;;;;EAqHC,uBAAA,CAAwB,MAAA;IACnC,SAAA;IACA,sBAAA,EAAwB,MAAA;EAAA,IACtB,OAAA;AAAA"}
@@ -0,0 +1,226 @@
1
+ import { __decorate } from "../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.js";
2
+ import { KanonZkIssuerKeyService } from "./KanonZkIssuerKeyService.js";
3
+ import { __decorateMetadata } from "../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateMetadata.js";
4
+ import { KanonClientService } from "../ledger/KanonClientService.js";
5
+ import "../ledger/index.js";
6
+ import { KanonZkService, padAttrsToCircuit } from "./KanonZkService.js";
7
+ import { BN254_SCALAR_FIELD, KANON_CRED_ID_ATTRIBUTE, KANON_ZK_PROOF_ATTRIBUTE, KANON_ZK_SIG_ATTRIBUTE, attrValueToFelt, computeZkLeaf, decodeKanonZkProofAttr, encodeAttributesCanonical, encodeKanonZkProofAttr, encodeZkSignature, kanonCredIdHash, signZkLeaf } from "@ajna-inc/kanon-sdk";
8
+ import { injectable } from "@credo-ts/core";
9
+ import { resourceIdToBytes32 } from "@ajna-inc/kanon-sdk/anoncreds";
10
+ import { ethers, hexlify, randomBytes } from "ethers";
11
+
12
+ //#region src/zk/KanonZkApi.ts
13
+ var _ref, _ref2, _ref3;
14
+ let KanonZkApi = class KanonZkApi {
15
+ constructor(zkService, issuerKeyService, clientService, agentContext) {
16
+ this.zkService = zkService;
17
+ this.issuerKeyService = issuerKeyService;
18
+ this.clientService = clientService;
19
+ this.agentContext = agentContext;
20
+ }
21
+ /**
22
+ * Read-only snapshot of the active leaf set for a credDef. Useful for
23
+ * dashboards / debug. Triggers a lazy reconstruct on first call after
24
+ * restart (one chain scan per credDef per process).
25
+ */
26
+ async getActiveLeaves(credDefId) {
27
+ return (await this.zkService.getCheckpoint(this.agentContext, credDefId)).active;
28
+ }
29
+ /** True iff the credDef opted in to `TIER_ZK_SNARK` at registration. */
30
+ async supportsZk(credDefId) {
31
+ return this.clientService.client.credDefSupportsZk(resourceIdToBytes32(credDefId));
32
+ }
33
+ /**
34
+ * Force-refresh the local state by dropping the in-process cache and
35
+ * re-running `reconstructFromChain`. Use after an out-of-band write
36
+ * (e.g. another agent published a `batchUpdate`) when you need this
37
+ * agent's view to catch up before the next event tick.
38
+ */
39
+ async resync(credDefId) {
40
+ this.zkService.invalidate(credDefId);
41
+ await this.zkService.getOrInit(this.agentContext, credDefId);
42
+ }
43
+ /**
44
+ * Provision a Tier-2 BabyJubjub keypair for `credDefId`. Idempotent: if a
45
+ * key has already been persisted for this credDef the existing one is
46
+ * returned without re-publishing.
47
+ *
48
+ * Call this BEFORE `registerCredentialDefinition` and pass the returned
49
+ * `(ax, ay)` straight through — the contract requires the key inline.
50
+ */
51
+ async provisionCredDef(credDefId) {
52
+ const key = await this.issuerKeyService.provision(this.agentContext, credDefId);
53
+ return {
54
+ ax: key.publicKey.Ax,
55
+ ay: key.publicKey.Ay
56
+ };
57
+ }
58
+ /**
59
+ * Build the credential attribute set for a Mode B issuance.
60
+ *
61
+ * Inputs:
62
+ * - `credDefId` — on-chain credDef bytes32
63
+ * - `domainAttributes` — `name → value` map of the schema's domain attrs
64
+ * (everything EXCEPT `kanonCredId` and `kanonZkSig`,
65
+ * which are reserved and injected here).
66
+ *
67
+ * Returns the full attribute set the caller plugs into the AnonCreds offer
68
+ * — every value is a string, ordered by AnonCreds' insertion semantics
69
+ * (domain attrs first, then `kanonCredId`, then `kanonZkSig`).
70
+ *
71
+ * The BabyJubjub signature is computed over the SAME tagged leaf the
72
+ * `non_revocation.circom` circuit and the `KanonZkService.addIssued` publish
73
+ * step recompute. The CL signature then covers `kanonZkSig` as a regular
74
+ * attribute, giving the "AnonCreds signs over everything" property.
75
+ */
76
+ async prepareModeBCredential(params) {
77
+ const { credDefId, domainAttributes } = params;
78
+ if (KANON_CRED_ID_ATTRIBUTE in domainAttributes || KANON_ZK_SIG_ATTRIBUTE in domainAttributes) throw new Error(`kanon-zk: domain attrs must not include the reserved attribute names ${KANON_CRED_ID_ATTRIBUTE} / ${KANON_ZK_SIG_ATTRIBUTE}; the SDK injects them.`);
79
+ const kanonCredId = hexlify(randomBytes(32));
80
+ const leaf = await computeZkLeaf(BigInt(resourceIdToBytes32(credDefId)) % BN254_SCALAR_FIELD, BigInt(kanonCredIdHash(kanonCredId)) % BN254_SCALAR_FIELD, padAttrsToCircuit(encodeAttributesCanonical(domainAttributes)));
81
+ const kanonZkSig = encodeZkSignature(await this.issuerKeyService.withPrivateKey(this.agentContext, credDefId, async (issuerKey) => signZkLeaf(issuerKey.privateKeyHex, leaf)));
82
+ const attributes = { ...domainAttributes };
83
+ attributes[KANON_CRED_ID_ATTRIBUTE] = kanonCredId;
84
+ attributes[KANON_ZK_SIG_ATTRIBUTE] = kanonZkSig;
85
+ return {
86
+ attributes,
87
+ kanonCredId,
88
+ kanonZkSig
89
+ };
90
+ }
91
+ /**
92
+ * Build a Mode B SNARK proof and package it as a self-attested attribute the
93
+ * holder hands to credo's standard presentation flow.
94
+ *
95
+ * The holder must supply:
96
+ * - `credDefId` the on-chain credDef bytes32
97
+ * - `kanonCredId` the value of the `kanonCredId` attribute
98
+ * on the credential being presented
99
+ * - `kanonZkSig` the value of the `kanonZkSig` attribute
100
+ * on the credential — the BJJ signature
101
+ * the issuer produced at issuance time
102
+ * - `domainAttributeValues` the credential's domain attributes,
103
+ * IN THE SAME ORDER as at issuance, so the
104
+ * Merkle inclusion proof verifies
105
+ * - `disclosedDomainIndex` which domain attr to selectively disclose
106
+ * - `merklePath` `{ pathElements, pathIndices }` from the
107
+ * current published Mode B Poseidon tree
108
+ * — the caller is responsible for getting
109
+ * this from an indexer or by replaying the
110
+ * on-chain events
111
+ * - `root` the published Poseidon root the path
112
+ * recovers to (must be within the recent
113
+ * window or the verifier rejects)
114
+ * - `challenge` the verifier-supplied nonce (typically
115
+ * the AnonCreds presentation-request nonce)
116
+ * - `wasmPath` / `zkeyPath` paths to the snarkjs artifacts (defaults
117
+ * resolve from the SDK build)
118
+ *
119
+ * Returns `{ selfAttestedAttributes: { kanonZkProof: <base64> } }` — merge
120
+ * into the holder's presentation response.
121
+ */
122
+ async prepareModeBPresentation(params) {
123
+ const sdk = await import("@ajna-inc/kanon-sdk");
124
+ const { credDefId, kanonCredId, kanonZkSig, domainAttributeValues, disclosedDomainIndex, merklePath, root, challenge } = params;
125
+ const credDefFelt = BigInt(resourceIdToBytes32(credDefId)) % BN254_SCALAR_FIELD;
126
+ const credIdFelt = BigInt(kanonCredIdHash(kanonCredId)) % BN254_SCALAR_FIELD;
127
+ const paddedAttrs = padAttrsToCircuit(domainAttributeValues.map((v) => attrValueToFelt(v)));
128
+ const onChainKey = await this.clientService.contracts.credDefRegistry.getIssuerZkPubKey(resourceIdToBytes32(credDefId));
129
+ if (!onChainKey.set) throw new Error(`kanon-zk: credDef ${credDefId} has no Tier 2 key published; Mode B presentation is not supported for this credDef`);
130
+ const sig = sdk.decodeZkSignature(kanonZkSig);
131
+ await sdk.zk.initPoseidon();
132
+ const input = {
133
+ root: root.toString(),
134
+ credDefId: credDefFelt.toString(),
135
+ challenge: challenge.toString(),
136
+ issuerAx: BigInt(onChainKey.ax).toString(),
137
+ issuerAy: BigInt(onChainKey.ay).toString(),
138
+ disclosedIndex: [disclosedDomainIndex.toString()],
139
+ disclosedValue: [paddedAttrs[disclosedDomainIndex].toString()],
140
+ credId: credIdFelt.toString(),
141
+ attributes: paddedAttrs.map((a) => a.toString()),
142
+ pathElements: merklePath.pathElements.map((p) => p.toString()),
143
+ pathIndices: merklePath.pathIndices.map((p) => p.toString()),
144
+ sigS: sig.S.toString(),
145
+ sigR8x: sig.R8x.toString(),
146
+ sigR8y: sig.R8y.toString()
147
+ };
148
+ const snarkjs = await import("snarkjs");
149
+ const wasmPath = params.wasmPath ?? defaultWasmPath();
150
+ const zkeyPath = params.zkeyPath ?? defaultZkeyPath();
151
+ const { proof, publicSignals } = await snarkjs.groth16.fullProve(input, wasmPath, zkeyPath);
152
+ const calldata = await snarkjs.groth16.exportSolidityCallData(proof, publicSignals);
153
+ const [a, b, c] = JSON.parse("[" + calldata + "]");
154
+ const proofBytes = ethers.AbiCoder.defaultAbiCoder().encode([
155
+ "uint256[2]",
156
+ "uint256[2][2]",
157
+ "uint256[2]"
158
+ ], [
159
+ a,
160
+ b,
161
+ c
162
+ ]);
163
+ const toBytes32 = (v) => "0x" + BigInt(v).toString(16).padStart(64, "0");
164
+ const encoded = encodeKanonZkProofAttr({
165
+ proofBytes,
166
+ publicSignals: publicSignals.map(toBytes32)
167
+ });
168
+ return { selfAttestedAttributes: { [KANON_ZK_PROOF_ATTRIBUTE]: encoded } };
169
+ }
170
+ /**
171
+ * Validate a Mode B SNARK proof from an incoming presentation.
172
+ *
173
+ * `selfAttestedAttributes` is the map the verifier already has from the
174
+ * AnonCreds presentation. The function:
175
+ * 1. Looks for `kanonZkProof`.
176
+ * 2. Decodes it back into `(proofBytes, publicSignals)`.
177
+ * 3. Submits to the on-chain `MerkleStateRegistry.verifyZKMembership` —
178
+ * which checks recent root, credDefId binding, issuer-key binding,
179
+ * AND runs the Groth16 verifier all in one call.
180
+ *
181
+ * Returns `true` iff the on-chain check passes. The caller decides what to
182
+ * do on `false` — typically reject the presentation as a whole.
183
+ */
184
+ async verifyModeBPresentation(params) {
185
+ const { credDefId, selfAttestedAttributes } = params;
186
+ const encoded = selfAttestedAttributes[KANON_ZK_PROOF_ATTRIBUTE];
187
+ if (typeof encoded !== "string" || encoded.length === 0) return false;
188
+ let wire;
189
+ try {
190
+ wire = decodeKanonZkProofAttr(encoded);
191
+ } catch {
192
+ return false;
193
+ }
194
+ const merkleStateRegistry = this.clientService.contracts.merkleStateRegistry;
195
+ try {
196
+ return await merkleStateRegistry.verifyZKMembership(resourceIdToBytes32(credDefId), wire.proofBytes, wire.publicSignals);
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ };
202
+ KanonZkApi = __decorate([injectable(), __decorateMetadata("design:paramtypes", [
203
+ KanonZkService,
204
+ KanonZkIssuerKeyService,
205
+ KanonClientService,
206
+ Object
207
+ ])], KanonZkApi);
208
+ /**
209
+ * Default snarkjs artifact paths. The credo-ts plugin is shipped without
210
+ * embedding the 12MB zkey, so by default we resolve relative to the kanon
211
+ * SDK's checked-in `circom/build/` (works for the monorepo development
212
+ * setup). Production deployments override via the call-site `wasmPath` /
213
+ * `zkeyPath` params or set `KANON_ZK_WASM` / `KANON_ZK_ZKEY` env vars.
214
+ */
215
+ function defaultWasmPath() {
216
+ if (process.env.KANON_ZK_WASM) return process.env.KANON_ZK_WASM;
217
+ throw new Error("kanon-zk: snarkjs wasm path not configured. Set KANON_ZK_WASM or pass wasmPath/zkeyPath to prepareModeBPresentation.");
218
+ }
219
+ function defaultZkeyPath() {
220
+ if (process.env.KANON_ZK_ZKEY) return process.env.KANON_ZK_ZKEY;
221
+ throw new Error("kanon-zk: snarkjs zkey path not configured. Set KANON_ZK_ZKEY or pass wasmPath/zkeyPath to prepareModeBPresentation.");
222
+ }
223
+
224
+ //#endregion
225
+ export { KanonZkApi };
226
+ //# sourceMappingURL=KanonZkApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonZkApi.js","names":[],"sources":["../../src/zk/KanonZkApi.ts"],"sourcesContent":["import type { AgentContext } from '@credo-ts/core'\nimport type { KanonZkProofWire } from '@ajna-inc/kanon-sdk'\n\nimport {\n attrValueToFelt,\n BN254_SCALAR_FIELD,\n decodeKanonZkProofAttr,\n encodeAttributesCanonical,\n encodeKanonZkProofAttr,\n encodeZkSignature,\n KANON_CRED_ID_ATTRIBUTE,\n KANON_ZK_PROOF_ATTRIBUTE,\n KANON_ZK_SIG_ATTRIBUTE,\n kanonCredIdHash,\n computeZkLeaf,\n signZkLeaf,\n} from '@ajna-inc/kanon-sdk'\nimport { resourceIdToBytes32 } from '@ajna-inc/kanon-sdk/anoncreds'\nimport { injectable } from '@credo-ts/core'\nimport { ethers, randomBytes, hexlify } from 'ethers'\n\nimport { KanonClientService } from '../ledger'\n\nimport { KanonZkService, padAttrsToCircuit } from './KanonZkService'\nimport { KanonZkIssuerKeyService } from './KanonZkIssuerKeyService'\n\n/**\n * Result of `provisionCredDef`. Hand `(ax, ay)` straight to\n * `registerCredentialDefinition` in the same flow — the contract requires the\n * BabyJubjub key inline at registration time.\n */\nexport interface KanonZkProvisionResult {\n ax: bigint\n ay: bigint\n}\n\n/**\n * Result of `prepareModeBCredential`. The caller MUST set every entry of\n * `attributes` as a credential attribute (so the AnonCreds CL signature covers\n * everything, including the kanon-reserved ones) before kicking off\n * issuance. `kanonCredId` is also returned separately so revocation paths can\n * key off it directly.\n */\nexport interface KanonZkCredentialPrep {\n /** The full attribute set the issuer should send in the credential. */\n attributes: Record<string, string>\n /** Convenience — the kanonCredId value, already present in `attributes`. */\n kanonCredId: string\n /** Convenience — the kanonZkSig value, already present in `attributes`. */\n kanonZkSig: string\n}\n\n/**\n * Result of `prepareModeBPresentation`. `selfAttestedAttributes` is what the\n * caller merges into the AnonCreds presentation response so Mode B rides on\n * standard AnonCreds.\n */\nexport interface KanonZkPresentationPrep {\n selfAttestedAttributes: Record<string, string>\n}\n\n/**\n * Mode B application-facing surface. Wired on `agent.modules.kanon.api.zk`.\n *\n * The methods here intentionally do NOT monkey-patch credo's AnonCreds\n * pipeline. Instead they expose the discrete steps a Mode B credDef needs at\n * three points in its lifecycle:\n *\n * - **provisionCredDef** — before registering a Mode B credDef. Generates\n * and persists the issuer BabyJubjub key, returns `(ax, ay)` for the\n * caller to pass to `registerCredentialDefinition`.\n * - **prepareModeBCredential** — at issuance time. Generates a fresh\n * `kanonCredId`, computes the tagged leaf, signs it with the issuer key,\n * and returns the attribute set the caller plugs into the AnonCreds offer.\n * - **prepareModeBPresentation** — at holder presentation time. Builds the\n * Groth16 proof from the credential's persisted sig + the current Merkle\n * state, returns the `selfAttestedAttributes` blob the holder hands to\n * credo's presentation flow.\n * - **verifyModeBPresentation** — at verifier side. Pulls the proof out of\n * the incoming `selfAttestedAttributes`, submits to the on-chain\n * `MerkleStateRegistry.verifyZKMembership`.\n *\n * The introspection helpers (`getActiveLeaves`, `supportsZk`, `resync`) stay\n * unchanged.\n */\n@injectable()\nexport class KanonZkApi {\n public constructor(\n private readonly zkService: KanonZkService,\n private readonly issuerKeyService: KanonZkIssuerKeyService,\n private readonly clientService: KanonClientService,\n private readonly agentContext: AgentContext\n ) {}\n\n // ─────────────────────────────────────────────────────────────────────\n // Introspection\n // ─────────────────────────────────────────────────────────────────────\n\n /**\n * Read-only snapshot of the active leaf set for a credDef. Useful for\n * dashboards / debug. Triggers a lazy reconstruct on first call after\n * restart (one chain scan per credDef per process).\n */\n public async getActiveLeaves(credDefId: string): Promise<{ keccak: string[]; poseidon: string[] }> {\n const cp = await this.zkService.getCheckpoint(this.agentContext, credDefId)\n return cp.active\n }\n\n /** True iff the credDef opted in to `TIER_ZK_SNARK` at registration. */\n public async supportsZk(credDefId: string): Promise<boolean> {\n return this.clientService.client.credDefSupportsZk(resourceIdToBytes32(credDefId))\n }\n\n /**\n * Force-refresh the local state by dropping the in-process cache and\n * re-running `reconstructFromChain`. Use after an out-of-band write\n * (e.g. another agent published a `batchUpdate`) when you need this\n * agent's view to catch up before the next event tick.\n */\n public async resync(credDefId: string): Promise<void> {\n this.zkService.invalidate(credDefId)\n await this.zkService.getOrInit(this.agentContext, credDefId)\n }\n\n // ─────────────────────────────────────────────────────────────────────\n // Lifecycle hooks\n // ─────────────────────────────────────────────────────────────────────\n\n /**\n * Provision a Tier-2 BabyJubjub keypair for `credDefId`. Idempotent: if a\n * key has already been persisted for this credDef the existing one is\n * returned without re-publishing.\n *\n * Call this BEFORE `registerCredentialDefinition` and pass the returned\n * `(ax, ay)` straight through — the contract requires the key inline.\n */\n public async provisionCredDef(credDefId: string): Promise<KanonZkProvisionResult> {\n const key = await this.issuerKeyService.provision(this.agentContext, credDefId)\n return { ax: key.publicKey.Ax, ay: key.publicKey.Ay }\n }\n\n /**\n * Build the credential attribute set for a Mode B issuance.\n *\n * Inputs:\n * - `credDefId` — on-chain credDef bytes32\n * - `domainAttributes` — `name → value` map of the schema's domain attrs\n * (everything EXCEPT `kanonCredId` and `kanonZkSig`,\n * which are reserved and injected here).\n *\n * Returns the full attribute set the caller plugs into the AnonCreds offer\n * — every value is a string, ordered by AnonCreds' insertion semantics\n * (domain attrs first, then `kanonCredId`, then `kanonZkSig`).\n *\n * The BabyJubjub signature is computed over the SAME tagged leaf the\n * `non_revocation.circom` circuit and the `KanonZkService.addIssued` publish\n * step recompute. The CL signature then covers `kanonZkSig` as a regular\n * attribute, giving the \"AnonCreds signs over everything\" property.\n */\n public async prepareModeBCredential(params: {\n credDefId: string\n domainAttributes: Record<string, string>\n }): Promise<KanonZkCredentialPrep> {\n const { credDefId, domainAttributes } = params\n if (\n KANON_CRED_ID_ATTRIBUTE in domainAttributes ||\n KANON_ZK_SIG_ATTRIBUTE in domainAttributes\n ) {\n throw new Error(\n `kanon-zk: domain attrs must not include the reserved attribute names ${KANON_CRED_ID_ATTRIBUTE} / ${KANON_ZK_SIG_ATTRIBUTE}; the SDK injects them.`\n )\n }\n // 32-byte UUID-ish credId. utf-8 hex string; matches the Mode A convention\n // (`kanonCredIdHash(credId)` runs keccak over the utf-8). Hex avoids\n // ambiguity for any downstream string-shaped storage.\n const credIdBytes = randomBytes(32)\n const kanonCredId = hexlify(credIdBytes) // 0x + 64 hex chars\n\n // Felt encode the inputs the same way the circuit and the on-chain\n // registry will (mod p over the canonical bytes32 hash).\n const credDefFelt = BigInt(resourceIdToBytes32(credDefId)) % BN254_SCALAR_FIELD\n const credIdFelt = BigInt(kanonCredIdHash(kanonCredId)) % BN254_SCALAR_FIELD\n\n // Domain attributes — felt-encoded in CANONICAL alphabetical order so\n // the issuance tracker and the holder-side wrapper, neither of which\n // can rely on `domainAttributes`' insertion order surviving\n // serialization, reproduce the same leaf from the same value map.\n // SDK-reserved names (`kanonCredId`, `kanonZkSig`, …) are excluded\n // automatically — see `encodeAttributesCanonical`.\n const domainAttrFelts = encodeAttributesCanonical(domainAttributes)\n const paddedAttrs = padAttrsToCircuit(domainAttrFelts)\n\n // Tagged leaf + BabyJubjub signature. We use `withPrivateKey` so the\n // hex form of the BJJ privkey is in scope ONLY for the signZkLeaf call\n // — `KanonZkIssuerKeyService` re-loads from the wallet, runs the\n // callback, and best-effort drops the reference on return.\n const leaf = await computeZkLeaf(credDefFelt, credIdFelt, paddedAttrs)\n const sig = await this.issuerKeyService.withPrivateKey(\n this.agentContext,\n credDefId,\n async (issuerKey) => signZkLeaf(issuerKey.privateKeyHex, leaf)\n )\n const kanonZkSig = encodeZkSignature(sig)\n\n // Final attribute set. Order: domain attrs in insertion order, then the\n // two reserved kanon ones. The schema MUST list attrNames in this exact\n // order — Mode B credDefs are documented to do so.\n const attributes: Record<string, string> = { ...domainAttributes }\n attributes[KANON_CRED_ID_ATTRIBUTE] = kanonCredId\n attributes[KANON_ZK_SIG_ATTRIBUTE] = kanonZkSig\n\n return { attributes, kanonCredId, kanonZkSig }\n }\n\n /**\n * Build a Mode B SNARK proof and package it as a self-attested attribute the\n * holder hands to credo's standard presentation flow.\n *\n * The holder must supply:\n * - `credDefId` the on-chain credDef bytes32\n * - `kanonCredId` the value of the `kanonCredId` attribute\n * on the credential being presented\n * - `kanonZkSig` the value of the `kanonZkSig` attribute\n * on the credential — the BJJ signature\n * the issuer produced at issuance time\n * - `domainAttributeValues` the credential's domain attributes,\n * IN THE SAME ORDER as at issuance, so the\n * Merkle inclusion proof verifies\n * - `disclosedDomainIndex` which domain attr to selectively disclose\n * - `merklePath` `{ pathElements, pathIndices }` from the\n * current published Mode B Poseidon tree\n * — the caller is responsible for getting\n * this from an indexer or by replaying the\n * on-chain events\n * - `root` the published Poseidon root the path\n * recovers to (must be within the recent\n * window or the verifier rejects)\n * - `challenge` the verifier-supplied nonce (typically\n * the AnonCreds presentation-request nonce)\n * - `wasmPath` / `zkeyPath` paths to the snarkjs artifacts (defaults\n * resolve from the SDK build)\n *\n * Returns `{ selfAttestedAttributes: { kanonZkProof: <base64> } }` — merge\n * into the holder's presentation response.\n */\n public async prepareModeBPresentation(params: {\n credDefId: string\n kanonCredId: string\n kanonZkSig: string\n domainAttributeValues: string[]\n disclosedDomainIndex: number\n merklePath: { pathElements: bigint[]; pathIndices: number[] }\n root: bigint\n challenge: bigint\n wasmPath?: string\n zkeyPath?: string\n }): Promise<KanonZkPresentationPrep> {\n const sdk = await import('@ajna-inc/kanon-sdk')\n const {\n credDefId,\n kanonCredId,\n kanonZkSig,\n domainAttributeValues,\n disclosedDomainIndex,\n merklePath,\n root,\n challenge,\n } = params\n\n // Felt-encode the same inputs the issuer used.\n const credDefFelt = BigInt(resourceIdToBytes32(credDefId)) % BN254_SCALAR_FIELD\n const credIdFelt = BigInt(kanonCredIdHash(kanonCredId)) % BN254_SCALAR_FIELD\n const domainFelts = domainAttributeValues.map((v) => attrValueToFelt(v))\n const paddedAttrs = padAttrsToCircuit(domainFelts)\n\n // Lookup the issuer's pubkey from on-chain so we hand the circuit the\n // SAME Ax/Ay the verifier will compare against `getIssuerZkPubKey`.\n // Cast through unknown — the typechain ABI in the SDK might not yet\n // include the new view depending on regenerate-on-publish cadence.\n const credDefRegistry = this.clientService.contracts.credDefRegistry as unknown as {\n getIssuerZkPubKey: (credDefId: string) => Promise<{ ax: bigint; ay: bigint; set: boolean }>\n }\n const onChainKey = await credDefRegistry.getIssuerZkPubKey(resourceIdToBytes32(credDefId))\n if (!onChainKey.set) {\n throw new Error(\n `kanon-zk: credDef ${credDefId} has no Tier 2 key published; Mode B presentation is not supported for this credDef`\n )\n }\n\n // The decoded signature is what the prover would otherwise have to\n // reconstruct from the issuer's signing — we reuse the one already on the\n // credential.\n const sig = sdk.decodeZkSignature(kanonZkSig)\n\n await sdk.zk.initPoseidon()\n\n // Wire the snarkjs witness inputs in the layout the compiled circuit expects.\n const input = {\n root: root.toString(),\n credDefId: credDefFelt.toString(),\n challenge: challenge.toString(),\n issuerAx: BigInt(onChainKey.ax).toString(),\n issuerAy: BigInt(onChainKey.ay).toString(),\n disclosedIndex: [disclosedDomainIndex.toString()],\n disclosedValue: [paddedAttrs[disclosedDomainIndex].toString()],\n credId: credIdFelt.toString(),\n attributes: paddedAttrs.map((a: bigint) => a.toString()),\n pathElements: merklePath.pathElements.map((p: bigint) => p.toString()),\n pathIndices: merklePath.pathIndices.map((p: number) => p.toString()),\n sigS: sig.S.toString(),\n sigR8x: sig.R8x.toString(),\n sigR8y: sig.R8y.toString(),\n }\n\n // snarkjs is an optional dep — dynamic require so the credo package\n // doesn't pay the cost on Mode A-only deployments. The package ships\n // no type declarations, so we describe only the surface we use and\n // route the import through a string variable to avoid TS module\n // resolution at compile time.\n type SnarkjsModule = {\n groth16: {\n fullProve: (\n input: unknown,\n wasmPath: string,\n zkeyPath: string\n ) => Promise<{ proof: unknown; publicSignals: string[] }>\n exportSolidityCallData: (proof: unknown, publicSignals: string[]) => Promise<string>\n }\n }\n const snarkjsModuleName = 'snarkjs'\n const snarkjs = (await import(snarkjsModuleName)) as unknown as SnarkjsModule\n\n const wasmPath = params.wasmPath ?? defaultWasmPath()\n const zkeyPath = params.zkeyPath ?? defaultZkeyPath()\n const { proof, publicSignals } = await snarkjs.groth16.fullProve(input, wasmPath, zkeyPath)\n\n const calldata = await snarkjs.groth16.exportSolidityCallData(proof, publicSignals)\n const [a, b, c] = JSON.parse('[' + calldata + ']') as [\n [string, string],\n [[string, string], [string, string]],\n [string, string],\n string[],\n ]\n const proofBytes = ethers.AbiCoder.defaultAbiCoder().encode(\n ['uint256[2]', 'uint256[2][2]', 'uint256[2]'],\n [a, b, c]\n )\n const toBytes32 = (v: string) => '0x' + BigInt(v).toString(16).padStart(64, '0')\n const wire: KanonZkProofWire = {\n proofBytes,\n publicSignals: publicSignals.map(toBytes32),\n }\n const encoded = encodeKanonZkProofAttr(wire)\n\n return {\n selfAttestedAttributes: { [KANON_ZK_PROOF_ATTRIBUTE]: encoded },\n }\n }\n\n /**\n * Validate a Mode B SNARK proof from an incoming presentation.\n *\n * `selfAttestedAttributes` is the map the verifier already has from the\n * AnonCreds presentation. The function:\n * 1. Looks for `kanonZkProof`.\n * 2. Decodes it back into `(proofBytes, publicSignals)`.\n * 3. Submits to the on-chain `MerkleStateRegistry.verifyZKMembership` —\n * which checks recent root, credDefId binding, issuer-key binding,\n * AND runs the Groth16 verifier all in one call.\n *\n * Returns `true` iff the on-chain check passes. The caller decides what to\n * do on `false` — typically reject the presentation as a whole.\n */\n public async verifyModeBPresentation(params: {\n credDefId: string\n selfAttestedAttributes: Record<string, string>\n }): Promise<boolean> {\n const { credDefId, selfAttestedAttributes } = params\n const encoded = selfAttestedAttributes[KANON_ZK_PROOF_ATTRIBUTE]\n if (typeof encoded !== 'string' || encoded.length === 0) return false\n let wire: KanonZkProofWire\n try {\n wire = decodeKanonZkProofAttr(encoded)\n } catch {\n return false\n }\n\n const merkleStateRegistry = this.clientService.contracts.merkleStateRegistry as unknown as {\n verifyZKMembership: (\n credDefId: string,\n proof: string,\n publicSignals: string[]\n ) => Promise<boolean>\n }\n try {\n return await merkleStateRegistry.verifyZKMembership(\n resourceIdToBytes32(credDefId),\n wire.proofBytes,\n wire.publicSignals\n )\n } catch {\n // Custom errors / revert reasons surface as exceptions on the ethers\n // call — treat any failure as \"rejected\" rather than propagating, so\n // verifier code can simply branch on the boolean.\n return false\n }\n }\n}\n\n/**\n * Default snarkjs artifact paths. The credo-ts plugin is shipped without\n * embedding the 12MB zkey, so by default we resolve relative to the kanon\n * SDK's checked-in `circom/build/` (works for the monorepo development\n * setup). Production deployments override via the call-site `wasmPath` /\n * `zkeyPath` params or set `KANON_ZK_WASM` / `KANON_ZK_ZKEY` env vars.\n */\nfunction defaultWasmPath(): string {\n if (process.env.KANON_ZK_WASM) return process.env.KANON_ZK_WASM\n throw new Error(\n 'kanon-zk: snarkjs wasm path not configured. Set KANON_ZK_WASM or pass wasmPath/zkeyPath to prepareModeBPresentation.'\n )\n}\n\nfunction defaultZkeyPath(): string {\n if (process.env.KANON_ZK_ZKEY) return process.env.KANON_ZK_ZKEY\n throw new Error(\n 'kanon-zk: snarkjs zkey path not configured. Set KANON_ZK_ZKEY or pass wasmPath/zkeyPath to prepareModeBPresentation.'\n )\n}\n"],"mappings":"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"}
@@ -0,0 +1,107 @@
1
+ import { KanonZkIssuerKey } from "@ajna-inc/kanon-sdk";
2
+ import { AgentContext } from "@credo-ts/core";
3
+
4
+ //#region src/zk/KanonZkIssuerKeyService.d.ts
5
+ /**
6
+ * Tier-2 BabyJubjub issuer key lifecycle (off-chain only).
7
+ *
8
+ * Mode B requires the issuer's BabyJubjub public key to be published on chain
9
+ * via `CredentialDefinitionRegistry.registerCredentialDefinition(..., ax, ay)`
10
+ * — registration and key publication happen atomically in one transaction. So
11
+ * this service does NOT touch chain: it just generates + persists the keypair
12
+ * so the registration caller can read `(ax, ay)` to pass through and so the
13
+ * issuance side can later read the private key to sign credential leaves.
14
+ *
15
+ * Persistence: `GenericRecordsApi`, one record per credDef, keyed by
16
+ * `kanon-zk-issuer-key:<lowercased credDefId>`. The wallet encrypts records at
17
+ * rest, so the on-disk form is safe; the in-memory exposure surface is the
18
+ * hex string between load + use.
19
+ *
20
+ * Hardening choices in this implementation:
21
+ *
22
+ * - We cache ONLY the public key (`Ax`, `Ay`). Public coords are safe to
23
+ * keep — they're literally published on chain. The PRIVATE key is loaded
24
+ * from the wallet on every signing operation and discarded immediately
25
+ * after.
26
+ *
27
+ * - `withPrivateKey(fn)` lets callers compute with the privkey in a tight
28
+ * scope. The privkey buffer is best-effort overwritten before returning,
29
+ * mitigating heap-dump exposure (JS doesn't guarantee zeroing — GC may
30
+ * have copied it — but this still removes the strong reference).
31
+ *
32
+ * - `provision()` is serialized per credDef via a single-flight lock. Two
33
+ * concurrent calls for the same credDef can't both generate fresh keys
34
+ * and race on the GenericRecords write — the second caller blocks on the
35
+ * first and observes the persisted result.
36
+ *
37
+ * Idempotent: `provision` returns the existing key if already persisted.
38
+ * Rotating is unsupported — it would silently break every previously-issued
39
+ * Mode B proof.
40
+ */
41
+ declare class KanonZkIssuerKeyService {
42
+ /**
43
+ * In-process cache for the PUBLIC key only. The public coords are safe to
44
+ * cache — they're on chain anyway. We deliberately do NOT cache the
45
+ * private key; it's loaded from the wallet on every use and the hex
46
+ * string is dropped as soon as the closure that uses it returns.
47
+ */
48
+ private readonly publicKeyCache;
49
+ /**
50
+ * Per-credDef single-flight queue so two concurrent `provision()` calls
51
+ * for the same credDef can't both generate fresh keys and race on the
52
+ * GenericRecords write. Same pattern as `KanonZkPathService.withLock`.
53
+ */
54
+ private readonly provisionQueues;
55
+ /**
56
+ * Generate a fresh BJJ keypair for `credDefId` if one isn't persisted yet,
57
+ * and return it. Pass `(key.publicKey.Ax, key.publicKey.Ay)` to
58
+ * `registerCredentialDefinition` in the same flow.
59
+ *
60
+ * Concurrent calls for the same credDef serialize — only ONE generates a
61
+ * fresh key; the rest observe the persisted record.
62
+ */
63
+ provision(agentContext: AgentContext, credDefId: string): Promise<KanonZkIssuerKey>;
64
+ /**
65
+ * Public-key-only accessor. Hits the in-process cache when warm; otherwise
66
+ * reads from the wallet but discards the privkey hex on return. Used by
67
+ * Mode B presentation flow (which needs `(Ax, Ay)` as a public input).
68
+ */
69
+ loadPublicKey(agentContext: AgentContext, credDefId: string): Promise<{
70
+ Ax: bigint;
71
+ Ay: bigint;
72
+ }>;
73
+ /**
74
+ * Run `fn` with the issuer's BabyJubjub private key for `credDefId`.
75
+ *
76
+ * The privkey is loaded from the wallet, passed to `fn`, and the local
77
+ * reference dropped on return. Callers MUST do their signing inside `fn`
78
+ * and not stash the hex string elsewhere — the entire point is to keep
79
+ * the strong reference scoped tightly.
80
+ *
81
+ * We make a best-effort attempt to overwrite the hex string buffer before
82
+ * returning. JavaScript doesn't guarantee deletion (the GC may have copied
83
+ * the string elsewhere) but removing the obvious reference reduces the
84
+ * window for a heap-dump attacker.
85
+ */
86
+ withPrivateKey<T>(agentContext: AgentContext, credDefId: string, fn: (key: KanonZkIssuerKey) => Promise<T>): Promise<T>;
87
+ /**
88
+ * Legacy method retained for transition. Now equivalent to
89
+ * `loadPublicKey` for the public coords + best-effort drop of the privkey
90
+ * reference immediately. Prefer `loadPublicKey` (read-only fast path) or
91
+ * `withPrivateKey(fn)` (scoped signing) directly.
92
+ *
93
+ * @deprecated use `loadPublicKey` or `withPrivateKey` instead.
94
+ */
95
+ load(agentContext: AgentContext, credDefId: string): Promise<KanonZkIssuerKey>;
96
+ private restore;
97
+ /**
98
+ * Per-credDef single-flight queue. Each `provision` call chains onto the
99
+ * previous one for the same credDef. Failure in one doesn't poison the
100
+ * queue for the next caller — `.catch(() => undefined)` keeps it moving.
101
+ */
102
+ private withProvisionLock;
103
+ private recordId;
104
+ }
105
+ //#endregion
106
+ export { KanonZkIssuerKeyService };
107
+ //# sourceMappingURL=KanonZkIssuerKeyService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonZkIssuerKeyService.d.ts","names":[],"sources":["../../src/zk/KanonZkIssuerKeyService.ts"],"mappings":";;;;;;AA6CA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cACa,uBAAA;EAsGiB;;;;;;EAAA,iBA/FX,cAAA;EAkGwB;;;;;EAAA,iBA3FxB,eAAA;EAkIf;;;;;;;;EAxHW,SAAA,CACX,YAAA,EAAc,YAAA,EACd,SAAA,WACC,OAAA,CAAQ,gBAAA;;;;;;EA8BE,aAAA,CACX,YAAA,EAAc,YAAA,EACd,SAAA,WACC,OAAA;IAAU,EAAA;IAAY,EAAA;EAAA;;;;;;;;;;;;;;EA0CZ,cAAA,GAAA,CACX,YAAA,EAAc,YAAA,EACd,SAAA,UACA,EAAA,GAAK,GAAA,EAAK,gBAAA,KAAqB,OAAA,CAAQ,CAAA,IACtC,OAAA,CAAQ,CAAA;;;;;;;;;EAqCE,IAAA,CACX,YAAA,EAAc,YAAA,EACd,SAAA,WACC,OAAA,CAAQ,gBAAA;EAAA,QAeG,OAAA;;;;;;UAcN,iBAAA;EAAA,QAQA,QAAA;AAAA"}