@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,165 @@
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 { IssuerService, issuer } from "@ajna-inc/kanon-sdk";
7
+ import { GenericRecordsApi, injectable } from "@credo-ts/core";
8
+ import { resourceIdToBytes32 } from "@ajna-inc/kanon-sdk/anoncreds";
9
+
10
+ //#region src/zk/KanonZkService.ts
11
+ var _ref, _ref2;
12
+ /**
13
+ * Internal record type for the per-credDef sync checkpoint. The plugin stores
14
+ * one record per credDef; the record id encodes the credDef so lookups are
15
+ * deterministic without a separate index.
16
+ */
17
+ const CHECKPOINT_RECORD_TYPE = "kanon-zk-sync";
18
+ const checkpointRecordId = (credDefId) => `kanon-zk-sync:${credDefId.toLowerCase()}`;
19
+ /** Circuit-fixed attribute count. Mirrors `nAttr` in `non_revocation.circom`. */
20
+ const KANON_ZK_CIRCUIT_ATTRS = 16;
21
+ /**
22
+ * Pad / truncate a felt array to the circuit's 16-felt attribute width.
23
+ * Throws when the caller has more attributes than the circuit supports — that
24
+ * is a schema-design problem the caller has to fix, not a silent truncation.
25
+ */
26
+ function padAttrsToCircuit(attrs) {
27
+ if (attrs.length > KANON_ZK_CIRCUIT_ATTRS) throw new Error(`kanon-zk: schema has ${attrs.length} attributes but the circuit only supports ${KANON_ZK_CIRCUIT_ATTRS}. Reduce the schema or recompile with a higher nAttr.`);
28
+ const out = attrs.slice();
29
+ while (out.length < KANON_ZK_CIRCUIT_ATTRS) out.push(0n);
30
+ return out;
31
+ }
32
+ let KanonZkService = class KanonZkService {
33
+ constructor(clientService, issuerKeyService) {
34
+ this.clientService = clientService;
35
+ this.issuerKeyService = issuerKeyService;
36
+ this.cache = /* @__PURE__ */ new Map();
37
+ }
38
+ /**
39
+ * Get the issuer service for `credDefId`. Idempotent — subsequent calls
40
+ * return the cached instance. The caller must ensure `clientService.init()`
41
+ * has completed before invoking this.
42
+ */
43
+ async getOrInit(agentContext, credDefId) {
44
+ const key = credDefId.toLowerCase();
45
+ const cached = this.cache.get(key);
46
+ if (cached) return cached;
47
+ const records = agentContext.dependencyManager.resolve(GenericRecordsApi);
48
+ const dummyKeys = issuer.generateIssuerKeyPair();
49
+ const service = new IssuerService(this.clientService.contracts, this.clientService.getSigner(), credDefId, dummyKeys);
50
+ const existing = await records.findById(checkpointRecordId(credDefId)).catch(() => null);
51
+ let lastSynced = 0;
52
+ if (existing) try {
53
+ const cp = existing.content;
54
+ service.loadCheckpoint(cp);
55
+ lastSynced = cp.lastSyncedBlock;
56
+ } catch {
57
+ lastSynced = 0;
58
+ }
59
+ await service.reconstructFromChain(lastSynced);
60
+ await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint());
61
+ this.cache.set(key, service);
62
+ return service;
63
+ }
64
+ /**
65
+ * Revoke `credIds` for `credDefId`. Lazy-initialises the issuer service if
66
+ * needed, derives keccak leaves via the SDK, publishes `batchUpdate` to
67
+ * MerkleStateRegistry, and re-persists the checkpoint so the local state
68
+ * survives the next restart.
69
+ */
70
+ async revoke(agentContext, credDefId, credIds) {
71
+ if (credIds.length === 0) return;
72
+ const service = await this.getOrInit(agentContext, credDefId);
73
+ await service.revokeByCredId(credIds);
74
+ await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint());
75
+ }
76
+ /**
77
+ * Add issued credentials to the on-chain Merkle roots.
78
+ *
79
+ * For each `{credId, attributes}` we compute:
80
+ *
81
+ * - Mode A leaf: `deriveLeaf(keccak256(utf8(credId)))` — the OZ-keccak
82
+ * tree leaf used by the nullifier path. Always computed
83
+ * so revocation works even on Mode B-only credDefs (the
84
+ * contract just won't accept Mode A consume on them).
85
+ * - Mode B leaf: `Poseidon(LEAF_TAG, credDefId, credId, Poseidon(attrs))`
86
+ * — the tagged leaf the `non_revocation.circom` circuit
87
+ * recomputes from its inputs. Same value the issuer's
88
+ * BabyJubjub signature was computed over inside
89
+ * `KanonZkApi.prepareModeBCredential`.
90
+ *
91
+ * The credDefId and credId felts are `uint256(bytes32) mod p`, matching
92
+ * the on-chain registry's `publicSignals[1]` binding. `attributes` MUST be
93
+ * the same felt array (in the same order) the prep step used — see the
94
+ * docstring on `prepareModeBCredential` for the canonical encoding.
95
+ */
96
+ async addIssued(agentContext, credDefId, credentials) {
97
+ if (credentials.length === 0) return;
98
+ const service = await this.getOrInit(agentContext, credDefId);
99
+ const sdk = await import("@ajna-inc/kanon-sdk");
100
+ await this.issuerKeyService.loadPublicKey(agentContext, credDefId);
101
+ const credDefFelt = BigInt(resourceIdToBytes32(credDefId)) % sdk.BN254_SCALAR_FIELD;
102
+ await sdk.zk.initPoseidon();
103
+ const addedKeccak = [];
104
+ const addedPoseidon = [];
105
+ const addedPoseidonBig = [];
106
+ for (const { credId, attributes } of credentials) {
107
+ const credIdHash = sdk.kanonCredIdHash(credId);
108
+ const keccakLeaf = sdk.deriveLeaf(credIdHash);
109
+ const credIdFelt = BigInt(credIdHash) % sdk.BN254_SCALAR_FIELD;
110
+ const padded = padAttrsToCircuit(attributes);
111
+ const poseidonLeaf = await sdk.computeZkLeaf(credDefFelt, credIdFelt, padded);
112
+ const poseidonLeafHex = "0x" + poseidonLeaf.toString(16).padStart(64, "0");
113
+ addedKeccak.push(keccakLeaf);
114
+ addedPoseidon.push(poseidonLeafHex);
115
+ addedPoseidonBig.push(poseidonLeaf);
116
+ }
117
+ const cp = service.getCheckpoint();
118
+ cp.active.keccak.push(...addedKeccak);
119
+ cp.active.poseidon.push(...addedPoseidon);
120
+ service.loadCheckpoint(cp);
121
+ const allKeccak = cp.active.keccak;
122
+ const newKeccakRoot = new sdk.core.StandardMerkleTree(allKeccak.length > 0 ? allKeccak : ["0x" + "00".repeat(32)]).root;
123
+ const allPoseidonBig = cp.active.poseidon.map((h) => BigInt(h));
124
+ const newPoseidonRoot = "0x" + new sdk.zk.PoseidonTree(26, allPoseidonBig).root.toString(16).padStart(64, "0");
125
+ await this.clientService.contracts.merkleStateRegistry.connect(this.clientService.getSigner()).batchUpdate(credDefId, addedKeccak, addedPoseidon, [], [], newKeccakRoot, newPoseidonRoot);
126
+ await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint());
127
+ }
128
+ /** Snapshot the current active-leaf set for a credDef (mostly for tests). */
129
+ async getCheckpoint(agentContext, credDefId) {
130
+ return (await this.getOrInit(agentContext, credDefId)).getCheckpoint();
131
+ }
132
+ /** Drop the in-process cache for a credDef. Forces re-init on next call. */
133
+ invalidate(credDefId) {
134
+ this.cache.delete(credDefId.toLowerCase());
135
+ }
136
+ /**
137
+ * Pad / truncate a `bigint[]` to the circuit-fixed 16-felt input width.
138
+ *
139
+ * The compiled `non_revocation.circom` consumes EXACTLY 16 attribute felts.
140
+ * Real schemas have fewer, so we right-pad with `0n`. Schemas with more than
141
+ * 16 attrs do NOT fit in this circuit and are caught at the boundary —
142
+ * surfacing the constraint to the caller rather than silently truncating.
143
+ */
144
+ async persistCheckpoint(agentContext, credDefId, checkpoint) {
145
+ const records = agentContext.dependencyManager.resolve(GenericRecordsApi);
146
+ const id = checkpointRecordId(credDefId);
147
+ const existing = await records.findById(id).catch(() => null);
148
+ if (existing) {
149
+ existing.content = checkpoint;
150
+ await records.update(existing);
151
+ } else await records.save({
152
+ id,
153
+ content: checkpoint,
154
+ tags: {
155
+ type: CHECKPOINT_RECORD_TYPE,
156
+ credDefId: credDefId.toLowerCase()
157
+ }
158
+ });
159
+ }
160
+ };
161
+ KanonZkService = __decorate([injectable(), __decorateMetadata("design:paramtypes", [KanonClientService, KanonZkIssuerKeyService])], KanonZkService);
162
+
163
+ //#endregion
164
+ export { KANON_ZK_CIRCUIT_ATTRS, KanonZkService, padAttrsToCircuit };
165
+ //# sourceMappingURL=KanonZkService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonZkService.js","names":["sdkIssuer"],"sources":["../../src/zk/KanonZkService.ts"],"sourcesContent":["import type { AgentContext } from '@credo-ts/core'\nimport type { IssuerSyncCheckpoint } from '@ajna-inc/kanon-sdk'\n\nimport { IssuerService, issuer as sdkIssuer } from '@ajna-inc/kanon-sdk'\nimport { resourceIdToBytes32 } from '@ajna-inc/kanon-sdk/anoncreds'\nimport { GenericRecordsApi, injectable } from '@credo-ts/core'\n\nimport { KanonClientService } from '../ledger'\nimport { KanonZkIssuerKeyService } from './KanonZkIssuerKeyService'\n\n/**\n * Internal record type for the per-credDef sync checkpoint. The plugin stores\n * one record per credDef; the record id encodes the credDef so lookups are\n * deterministic without a separate index.\n */\nconst CHECKPOINT_RECORD_TYPE = 'kanon-zk-sync'\nconst checkpointRecordId = (credDefId: string): string => `kanon-zk-sync:${credDefId.toLowerCase()}`\n\n/** Circuit-fixed attribute count. Mirrors `nAttr` in `non_revocation.circom`. */\nexport const KANON_ZK_CIRCUIT_ATTRS = 16\n\n/**\n * Pad / truncate a felt array to the circuit's 16-felt attribute width.\n * Throws when the caller has more attributes than the circuit supports — that\n * is a schema-design problem the caller has to fix, not a silent truncation.\n */\nexport function padAttrsToCircuit(attrs: bigint[]): bigint[] {\n if (attrs.length > KANON_ZK_CIRCUIT_ATTRS) {\n throw new Error(\n `kanon-zk: schema has ${attrs.length} attributes but the circuit only supports ${KANON_ZK_CIRCUIT_ATTRS}. Reduce the schema or recompile with a higher nAttr.`\n )\n }\n const out = attrs.slice()\n while (out.length < KANON_ZK_CIRCUIT_ATTRS) out.push(0n)\n return out\n}\n\n/**\n * Restart-survivable Mode B (Groth16 non-revocation) facade for the credo\n * plugin. Maintains a lazy-initialised `IssuerService` per credDef.\n *\n * Cold start:\n *\n * 1. Caller asks for `getOrInit(credDefId)`.\n * 2. The service looks up a persisted checkpoint in `GenericRecordsApi`.\n * 3. If present, `loadCheckpoint` rehydrates the local active leaf set + the\n * keccak↔poseidon companion map without touching chain.\n * 4. `reconstructFromChain(lastSyncedBlock)` then folds in any events that\n * arrived since the snapshot.\n * 5. The updated checkpoint is persisted.\n *\n * Subsequent calls reuse the cached `IssuerService` in-process. Plugin reload\n * (agent shutdown) is survived by the persisted checkpoint.\n */\n@injectable()\nexport class KanonZkService {\n private readonly cache = new Map<string, IssuerService>()\n\n public constructor(\n private readonly clientService: KanonClientService,\n private readonly issuerKeyService: KanonZkIssuerKeyService\n ) {}\n\n /**\n * Get the issuer service for `credDefId`. Idempotent — subsequent calls\n * return the cached instance. The caller must ensure `clientService.init()`\n * has completed before invoking this.\n */\n public async getOrInit(agentContext: AgentContext, credDefId: string): Promise<IssuerService> {\n const key = credDefId.toLowerCase()\n const cached = this.cache.get(key)\n if (cached) return cached\n\n const records = agentContext.dependencyManager.resolve(GenericRecordsApi)\n\n // IssuerService requires an IssuerKeyPair but the revoke path does not use\n // it (keys only matter for SDK-side issuance which the credo plugin does\n // not perform — issuance goes through Credo's AnonCreds flow). A fresh\n // throwaway keypair keeps the constructor happy without cost.\n const dummyKeys = sdkIssuer.generateIssuerKeyPair()\n const service = new IssuerService(\n this.clientService.contracts,\n this.clientService.getSigner(),\n credDefId,\n dummyKeys\n )\n\n // 1. Hydrate from a persisted checkpoint if present.\n const existing = await records.findById(checkpointRecordId(credDefId)).catch(() => null)\n let lastSynced = 0\n if (existing) {\n try {\n const cp = existing.content as unknown as IssuerSyncCheckpoint\n service.loadCheckpoint(cp)\n lastSynced = cp.lastSyncedBlock\n } catch {\n // Stale / corrupt checkpoint — fall through and rescan from genesis.\n lastSynced = 0\n }\n }\n\n // 2. Incremental scan from the checkpoint forward.\n await service.reconstructFromChain(lastSynced)\n\n // 3. Persist the refreshed checkpoint.\n await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint())\n\n this.cache.set(key, service)\n return service\n }\n\n /**\n * Revoke `credIds` for `credDefId`. Lazy-initialises the issuer service if\n * needed, derives keccak leaves via the SDK, publishes `batchUpdate` to\n * MerkleStateRegistry, and re-persists the checkpoint so the local state\n * survives the next restart.\n */\n public async revoke(\n agentContext: AgentContext,\n credDefId: string,\n credIds: string[]\n ): Promise<void> {\n if (credIds.length === 0) return\n const service = await this.getOrInit(agentContext, credDefId)\n await service.revokeByCredId(credIds)\n await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint())\n }\n\n /**\n * Add issued credentials to the on-chain Merkle roots.\n *\n * For each `{credId, attributes}` we compute:\n *\n * - Mode A leaf: `deriveLeaf(keccak256(utf8(credId)))` — the OZ-keccak\n * tree leaf used by the nullifier path. Always computed\n * so revocation works even on Mode B-only credDefs (the\n * contract just won't accept Mode A consume on them).\n * - Mode B leaf: `Poseidon(LEAF_TAG, credDefId, credId, Poseidon(attrs))`\n * — the tagged leaf the `non_revocation.circom` circuit\n * recomputes from its inputs. Same value the issuer's\n * BabyJubjub signature was computed over inside\n * `KanonZkApi.prepareModeBCredential`.\n *\n * The credDefId and credId felts are `uint256(bytes32) mod p`, matching\n * the on-chain registry's `publicSignals[1]` binding. `attributes` MUST be\n * the same felt array (in the same order) the prep step used — see the\n * docstring on `prepareModeBCredential` for the canonical encoding.\n */\n public async addIssued(\n agentContext: AgentContext,\n credDefId: string,\n credentials: Array<{ credId: string; attributes: bigint[] }>\n ): Promise<void> {\n if (credentials.length === 0) return\n const service = await this.getOrInit(agentContext, credDefId)\n const sdk = await import('@ajna-inc/kanon-sdk')\n\n // The BJJ key is required to exist locally — Mode B credDefs are provisioned\n // through `KanonZkIssuerKeyService.provision` before registration, so this\n // is guaranteed unless someone bypassed the credDef registration helper.\n // We don't sign here (sig went into the kanonZkSig attribute at issuance\n // time), so check existence via the PUBLIC-key path — that surfaces a\n // missing-key misconfiguration without touching the privkey.\n await this.issuerKeyService.loadPublicKey(agentContext, credDefId)\n\n // Reduce credDefId to the BN254 felt the on-chain registry binds against.\n // credDefId is a DID-URL, so hash it to bytes32 (keccak256(utf8(id)), with a\n // 0x<64hex> passthrough) before the felt reduction — matching every on-chain\n // boundary. A raw `BigInt(credDefId)` on the DID-URL string throws.\n const credDefFelt = BigInt(resourceIdToBytes32(credDefId)) % sdk.BN254_SCALAR_FIELD\n\n await sdk.zk.initPoseidon()\n\n const addedKeccak: string[] = []\n const addedPoseidon: string[] = []\n const addedPoseidonBig: bigint[] = []\n for (const { credId, attributes } of credentials) {\n // Mode A leaf: keccak path. `kanonCredIdHash` matches the SDK + Python\n // convention, then `deriveLeaf` does the OZ-standard double-keccak.\n const credIdHash = sdk.kanonCredIdHash(credId)\n const keccakLeaf = sdk.deriveLeaf(credIdHash)\n\n // Mode B leaf: tagged Poseidon. The credId felt mirrors the verifier\n // side — same hash-then-reduce as the prep step.\n const credIdFelt = BigInt(credIdHash) % sdk.BN254_SCALAR_FIELD\n const padded = padAttrsToCircuit(attributes)\n const poseidonLeaf = await sdk.computeZkLeaf(credDefFelt, credIdFelt, padded)\n const poseidonLeafHex = '0x' + poseidonLeaf.toString(16).padStart(64, '0')\n\n addedKeccak.push(keccakLeaf)\n addedPoseidon.push(poseidonLeafHex)\n addedPoseidonBig.push(poseidonLeaf)\n }\n\n // Fold the new leaves into local state.\n const cp = service.getCheckpoint()\n cp.active.keccak.push(...addedKeccak)\n cp.active.poseidon.push(...addedPoseidon)\n service.loadCheckpoint(cp)\n\n // Recompute both roots over the WHOLE active set. The OZ-keccak side\n // mirrors `MerkleStateRegistry.deriveLeaf`'s ordering; the tagged\n // Poseidon side mirrors the in-circuit `MerkleInclusion` template.\n const allKeccak = cp.active.keccak\n const keccakTree = new sdk.core.StandardMerkleTree(\n allKeccak.length > 0 ? allKeccak : ['0x' + '00'.repeat(32)]\n )\n const newKeccakRoot = keccakTree.root\n\n const allPoseidonBig = cp.active.poseidon.map((h) => BigInt(h))\n const poseidonTree = new sdk.zk.PoseidonTree(26, allPoseidonBig)\n const newPoseidonRoot =\n '0x' + poseidonTree.root.toString(16).padStart(64, '0')\n\n await this.clientService.contracts.merkleStateRegistry\n .connect(this.clientService.getSigner())\n .batchUpdate(\n credDefId,\n addedKeccak,\n addedPoseidon,\n [],\n [],\n newKeccakRoot,\n newPoseidonRoot\n )\n\n await this.persistCheckpoint(agentContext, credDefId, service.getCheckpoint())\n }\n\n /** Snapshot the current active-leaf set for a credDef (mostly for tests). */\n public async getCheckpoint(\n agentContext: AgentContext,\n credDefId: string\n ): Promise<IssuerSyncCheckpoint> {\n const service = await this.getOrInit(agentContext, credDefId)\n return service.getCheckpoint()\n }\n\n /** Drop the in-process cache for a credDef. Forces re-init on next call. */\n public invalidate(credDefId: string): void {\n this.cache.delete(credDefId.toLowerCase())\n }\n\n /**\n * Pad / truncate a `bigint[]` to the circuit-fixed 16-felt input width.\n *\n * The compiled `non_revocation.circom` consumes EXACTLY 16 attribute felts.\n * Real schemas have fewer, so we right-pad with `0n`. Schemas with more than\n * 16 attrs do NOT fit in this circuit and are caught at the boundary —\n * surfacing the constraint to the caller rather than silently truncating.\n */\n\n private async persistCheckpoint(\n agentContext: AgentContext,\n credDefId: string,\n checkpoint: IssuerSyncCheckpoint\n ): Promise<void> {\n const records = agentContext.dependencyManager.resolve(GenericRecordsApi)\n const id = checkpointRecordId(credDefId)\n const existing = await records.findById(id).catch(() => null)\n if (existing) {\n existing.content = checkpoint as unknown as Record<string, unknown>\n await records.update(existing)\n } else {\n await records.save({\n id,\n content: checkpoint as unknown as Record<string, unknown>,\n tags: { type: CHECKPOINT_RECORD_TYPE, credDefId: credDefId.toLowerCase() },\n })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAM,yBAAyB;AAC/B,MAAM,sBAAsB,cAA8B,iBAAiB,UAAU,aAAa;;AAGlG,MAAa,yBAAyB;;;;;;AAOtC,SAAgB,kBAAkB,OAA2B;AAC3D,KAAI,MAAM,SAAS,uBACjB,OAAM,IAAI,MACR,wBAAwB,MAAM,OAAO,4CAA4C,uBAAuB,uDACzG;CAEH,MAAM,MAAM,MAAM,OAAO;AACzB,QAAO,IAAI,SAAS,uBAAwB,KAAI,KAAK,GAAG;AACxD,QAAO;;AAqBF,2BAAM,eAAe;CAG1B,AAAO,YACL,AAAiB,eACjB,AAAiB,kBACjB;EAFiB;EACA;OAJ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,OAAK,MAAM,OAAO,UAAU,aAAa,CAAC;;;;;;;;;;CAY5C,MAAc,kBACZ,cACA,WACA,YACe;EACf,MAAM,UAAU,aAAa,kBAAkB,QAAQ,kBAAkB;EACzE,MAAM,KAAK,mBAAmB,UAAU;EACxC,MAAM,WAAW,MAAM,QAAQ,SAAS,GAAG,CAAC,YAAY,KAAK;AAC7D,MAAI,UAAU;AACZ,YAAS,UAAU;AACnB,SAAM,QAAQ,OAAO,SAAS;QAE9B,OAAM,QAAQ,KAAK;GACjB;GACA,SAAS;GACT,MAAM;IAAE,MAAM;IAAwB,WAAW,UAAU,aAAa;IAAE;GAC3E,CAAC;;;6BAtNP,YAAY"}
@@ -0,0 +1,4 @@
1
+ import { KanonZkPathService } from "./KanonZkPathService.js";
2
+ import { KanonZkIssuerKeyService } from "./KanonZkIssuerKeyService.js";
3
+ import { KANON_ZK_CIRCUIT_ATTRS, KanonZkService, padAttrsToCircuit } from "./KanonZkService.js";
4
+ import { KanonZkApi, KanonZkCredentialPrep, KanonZkPresentationPrep, KanonZkProvisionResult } from "./KanonZkApi.js";
@@ -0,0 +1,4 @@
1
+ import { KanonZkIssuerKeyService } from "./KanonZkIssuerKeyService.js";
2
+ import { KANON_ZK_CIRCUIT_ATTRS, KanonZkService, padAttrsToCircuit } from "./KanonZkService.js";
3
+ import { KanonZkPathService } from "./KanonZkPathService.js";
4
+ import { KanonZkApi } from "./KanonZkApi.js";
@@ -0,0 +1,48 @@
1
+ //#region src/zk/modeBLeaves.ts
2
+ /** How long to wait for the CrMS leaf-set endpoint before falling back to the chain scan. */
3
+ const MODE_B_LEAVES_TIMEOUT_MS = 2e4;
4
+ /**
5
+ * Base URL of the CrMS serving the Mode B leaf set for `credDefId`, or
6
+ * `undefined` when none is configured. Resolution order:
7
+ * 1. the app-provided `resolver` (see `KanonModuleConfigOptions.resolveLeavesBaseUrl`);
8
+ * 2. `KANON_ORG_BASE_URLS` — JSON `{"<orgHash>":"<crmsBase>"}`, keyed by the org in the credDefId;
9
+ * 3. `KANON_MODEB_LEAVES_BASE_URL`.
10
+ * Env vars are read through `globalThis.process` so this also runs where `process` is missing.
11
+ */
12
+ async function resolveModeBLeavesBaseUrl(credDefId, resolver) {
13
+ const fromResolver = await resolver?.(credDefId);
14
+ if (fromResolver) return fromResolver;
15
+ const env = globalThis.process?.env ?? {};
16
+ const org = /^did:kanon:org:([^/]+)\//i.exec(credDefId)?.[1]?.toLowerCase();
17
+ if (org && env.KANON_ORG_BASE_URLS) try {
18
+ const map = JSON.parse(env.KANON_ORG_BASE_URLS);
19
+ if (map[org]) return map[org];
20
+ } catch {}
21
+ return env.KANON_MODEB_LEAVES_BASE_URL || void 0;
22
+ }
23
+ /**
24
+ * Fetch the Mode B leaf set from `GET {base}/api/kanon/mode-b/leaves?cred_def_id=…`.
25
+ * Returns the leaves as bigints, or `{ status }` when the response is not usable.
26
+ * Throws on network errors and on timeout.
27
+ *
28
+ * Uses `AbortController` + `setTimeout` instead of `AbortSignal.timeout`, which
29
+ * is not available on every React Native runtime.
30
+ */
31
+ async function fetchModeBLeaves(base, credDefId, timeoutMs = MODE_B_LEAVES_TIMEOUT_MS) {
32
+ const url = `${base.replace(/\/+$/, "")}/api/kanon/mode-b/leaves?cred_def_id=${encodeURIComponent(credDefId)}`;
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
35
+ try {
36
+ const res = await fetch(url, { signal: controller.signal });
37
+ if (!res.ok) return { status: res.status };
38
+ const json = await res.json();
39
+ if (!Array.isArray(json?.leaves)) return { status: res.status };
40
+ return { leaves: json.leaves.map((h) => BigInt(typeof h === "string" && !h.startsWith("0x") ? `0x${h}` : h)) };
41
+ } finally {
42
+ clearTimeout(timer);
43
+ }
44
+ }
45
+
46
+ //#endregion
47
+ export { fetchModeBLeaves, resolveModeBLeavesBaseUrl };
48
+ //# sourceMappingURL=modeBLeaves.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modeBLeaves.js","names":[],"sources":["../../src/zk/modeBLeaves.ts"],"sourcesContent":["import type { KanonLeavesBaseUrlResolver } from '../KanonModuleConfig'\n\n/** How long to wait for the CrMS leaf-set endpoint before falling back to the chain scan. */\nexport const MODE_B_LEAVES_TIMEOUT_MS = 20_000\n\n/**\n * Base URL of the CrMS serving the Mode B leaf set for `credDefId`, or\n * `undefined` when none is configured. Resolution order:\n * 1. the app-provided `resolver` (see `KanonModuleConfigOptions.resolveLeavesBaseUrl`);\n * 2. `KANON_ORG_BASE_URLS` — JSON `{\"<orgHash>\":\"<crmsBase>\"}`, keyed by the org in the credDefId;\n * 3. `KANON_MODEB_LEAVES_BASE_URL`.\n * Env vars are read through `globalThis.process` so this also runs where `process` is missing.\n */\nexport async function resolveModeBLeavesBaseUrl(\n credDefId: string,\n resolver?: KanonLeavesBaseUrlResolver\n): Promise<string | undefined> {\n const fromResolver = await resolver?.(credDefId)\n if (fromResolver) return fromResolver\n\n const env = globalThis.process?.env ?? {}\n const org = /^did:kanon:org:([^/]+)\\//i.exec(credDefId)?.[1]?.toLowerCase()\n if (org && env.KANON_ORG_BASE_URLS) {\n try {\n const map = JSON.parse(env.KANON_ORG_BASE_URLS) as Record<string, string>\n if (map[org]) return map[org]\n } catch {\n // ignore malformed KANON_ORG_BASE_URLS\n }\n }\n return env.KANON_MODEB_LEAVES_BASE_URL || undefined\n}\n\n/**\n * Fetch the Mode B leaf set from `GET {base}/api/kanon/mode-b/leaves?cred_def_id=…`.\n * Returns the leaves as bigints, or `{ status }` when the response is not usable.\n * Throws on network errors and on timeout.\n *\n * Uses `AbortController` + `setTimeout` instead of `AbortSignal.timeout`, which\n * is not available on every React Native runtime.\n */\nexport async function fetchModeBLeaves(\n base: string,\n credDefId: string,\n timeoutMs = MODE_B_LEAVES_TIMEOUT_MS\n): Promise<{ leaves?: bigint[]; status?: number }> {\n const url = `${base.replace(/\\/+$/, '')}/api/kanon/mode-b/leaves?cred_def_id=${encodeURIComponent(credDefId)}`\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await fetch(url, {\n // Same cast as @credo-ts/core's fetch util: DOM and Node AbortSignal typings conflict\n signal: controller.signal as NonNullable<RequestInit['signal']>,\n })\n if (!res.ok) return { status: res.status }\n const json = (await res.json()) as { leaves?: unknown }\n if (!Array.isArray(json?.leaves)) return { status: res.status }\n return {\n leaves: json.leaves.map((h) => BigInt(typeof h === 'string' && !h.startsWith('0x') ? `0x${h}` : (h as string))),\n }\n } finally {\n clearTimeout(timer)\n }\n}\n"],"mappings":";;AAGA,MAAa,2BAA2B;;;;;;;;;AAUxC,eAAsB,0BACpB,WACA,UAC6B;CAC7B,MAAM,eAAe,MAAM,WAAW,UAAU;AAChD,KAAI,aAAc,QAAO;CAEzB,MAAM,MAAM,WAAW,SAAS,OAAO,EAAE;CACzC,MAAM,MAAM,4BAA4B,KAAK,UAAU,GAAG,IAAI,aAAa;AAC3E,KAAI,OAAO,IAAI,oBACb,KAAI;EACF,MAAM,MAAM,KAAK,MAAM,IAAI,oBAAoB;AAC/C,MAAI,IAAI,KAAM,QAAO,IAAI;SACnB;AAIV,QAAO,IAAI,+BAA+B;;;;;;;;;;AAW5C,eAAsB,iBACpB,MACA,WACA,YAAY,0BACqC;CACjD,MAAM,MAAM,GAAG,KAAK,QAAQ,QAAQ,GAAG,CAAC,uCAAuC,mBAAmB,UAAU;CAC5G,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,QAAQ,iBAAiB,WAAW,OAAO,EAAE,UAAU;AAC7D,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,KAAK,EAE3B,QAAQ,WAAW,QACpB,CAAC;AACF,MAAI,CAAC,IAAI,GAAI,QAAO,EAAE,QAAQ,IAAI,QAAQ;EAC1C,MAAM,OAAQ,MAAM,IAAI,MAAM;AAC9B,MAAI,CAAC,MAAM,QAAQ,MAAM,OAAO,CAAE,QAAO,EAAE,QAAQ,IAAI,QAAQ;AAC/D,SAAO,EACL,QAAQ,KAAK,OAAO,KAAK,MAAM,OAAO,OAAO,MAAM,YAAY,CAAC,EAAE,WAAW,KAAK,GAAG,KAAK,MAAO,EAAa,CAAC,EAChH;WACO;AACR,eAAa,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@veridid/kanon",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Credo (Aries TS) plugin that uses the Kanon AnonCreds VDR — drop-in for any EVM chain. Works with @credo-ts/anoncreds and @hyperledger/anoncreds-shared unmodified.",
5
+ "type": "module",
6
+ "main": "./build/index.js",
7
+ "types": "./build/index.d.ts",
8
+ "module": "./build/index.js",
9
+ "license": "Apache-2.0",
10
+ "author": "Ajna Inc",
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./build/index.d.ts",
17
+ "import": "./build/index.js",
18
+ "default": "./build/index.js"
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "files": [
23
+ "build",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "keywords": [
28
+ "credo",
29
+ "credo-ts",
30
+ "aries",
31
+ "anoncreds",
32
+ "kanon",
33
+ "ssi",
34
+ "did",
35
+ "vc",
36
+ "evm",
37
+ "vdr"
38
+ ],
39
+ "homepage": "https://github.com/VeriDID/credo-ts-internal/tree/release/packages/kanon",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/VeriDID/credo-ts-internal",
43
+ "directory": "packages/kanon"
44
+ },
45
+ "dependencies": {
46
+ "@ajna-inc/kanon-sdk": "0.1.10",
47
+ "class-transformer": "0.5.1",
48
+ "class-validator": "^0.14.1",
49
+ "rxjs": "^7.8.2",
50
+ "tsyringe": "^4.10.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@credo-ts/anoncreds": ">=0.7.0 <0.8",
54
+ "@credo-ts/core": ">=0.7.0 <0.8",
55
+ "@credo-ts/didcomm": ">=0.7.0 <0.8",
56
+ "ethers": "^6.13.0"
57
+ },
58
+ "devDependencies": {
59
+ "ethers": "^6.13.0",
60
+ "typescript": "~5.9.3",
61
+ "@credo-ts/anoncreds": "0.7.0",
62
+ "@credo-ts/didcomm": "0.7.0",
63
+ "@credo-ts/core": "0.7.0"
64
+ },
65
+ "scripts": {
66
+ "build": "tsdown --config-loader unconfig",
67
+ "clean": "rimraf ./build"
68
+ }
6
69
  }