@0xpolygonid/js-sdk 1.10.4 → 1.11.1

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 (105) hide show
  1. package/README.md +11 -0
  2. package/dist/browser/esm/index.js +8360 -17398
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +8383 -17416
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/blockchain/index.js +17 -0
  7. package/dist/node/cjs/blockchain/transaction-service.js +55 -0
  8. package/dist/node/cjs/credentials/credential-wallet.js +1 -1
  9. package/dist/node/cjs/credentials/status/reverse-sparse-merkle-tree.js +5 -1
  10. package/dist/node/cjs/iden3comm/handlers/auth.js +62 -27
  11. package/dist/node/cjs/iden3comm/handlers/common.js +4 -4
  12. package/dist/node/cjs/iden3comm/handlers/contract-request.js +34 -15
  13. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +33 -14
  14. package/dist/node/cjs/iden3comm/handlers/fetch.js +65 -34
  15. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  16. package/dist/node/cjs/iden3comm/handlers/message-handler.js +96 -0
  17. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +58 -30
  18. package/dist/node/cjs/iden3comm/packageManager.js +16 -0
  19. package/dist/node/cjs/iden3comm/packers/jws.js +63 -49
  20. package/dist/node/cjs/iden3comm/packers/plain.js +13 -3
  21. package/dist/node/cjs/iden3comm/packers/zkp.js +9 -0
  22. package/dist/node/cjs/iden3comm/utils/did.js +11 -11
  23. package/dist/node/cjs/identity/identity-wallet.js +228 -43
  24. package/dist/node/cjs/index.js +1 -0
  25. package/dist/node/cjs/kms/key-providers/bjj-provider.js +9 -0
  26. package/dist/node/cjs/kms/key-providers/ed25519-provider.js +14 -3
  27. package/dist/node/cjs/kms/key-providers/index.js +1 -1
  28. package/dist/node/cjs/kms/key-providers/{sec256k1-provider.js → secp256k1-provider.js} +37 -26
  29. package/dist/node/cjs/kms/kms.js +15 -0
  30. package/dist/node/cjs/proof/proof-service.js +3 -33
  31. package/dist/node/cjs/proof/provers/inputs-generator.js +2 -7
  32. package/dist/node/cjs/storage/blockchain/onchain-revocation.js +4 -12
  33. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +3 -10
  34. package/dist/node/cjs/storage/blockchain/state.js +39 -10
  35. package/dist/node/cjs/utils/did-helper.js +36 -2
  36. package/dist/node/cjs/verifiable/constants.js +2 -1
  37. package/dist/node/esm/blockchain/index.js +1 -0
  38. package/dist/node/esm/blockchain/transaction-service.js +51 -0
  39. package/dist/node/esm/credentials/credential-wallet.js +1 -1
  40. package/dist/node/esm/credentials/status/reverse-sparse-merkle-tree.js +6 -2
  41. package/dist/node/esm/iden3comm/handlers/auth.js +62 -27
  42. package/dist/node/esm/iden3comm/handlers/common.js +4 -4
  43. package/dist/node/esm/iden3comm/handlers/contract-request.js +34 -15
  44. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +33 -14
  45. package/dist/node/esm/iden3comm/handlers/fetch.js +65 -34
  46. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  47. package/dist/node/esm/iden3comm/handlers/message-handler.js +91 -0
  48. package/dist/node/esm/iden3comm/handlers/revocation-status.js +58 -30
  49. package/dist/node/esm/iden3comm/packageManager.js +16 -0
  50. package/dist/node/esm/iden3comm/packers/jws.js +63 -49
  51. package/dist/node/esm/iden3comm/packers/plain.js +13 -3
  52. package/dist/node/esm/iden3comm/packers/zkp.js +9 -0
  53. package/dist/node/esm/iden3comm/utils/did.js +11 -8
  54. package/dist/node/esm/identity/identity-wallet.js +230 -45
  55. package/dist/node/esm/index.js +1 -0
  56. package/dist/node/esm/kms/key-providers/bjj-provider.js +10 -1
  57. package/dist/node/esm/kms/key-providers/ed25519-provider.js +14 -3
  58. package/dist/node/esm/kms/key-providers/index.js +1 -1
  59. package/dist/node/esm/kms/key-providers/secp256k1-provider.js +85 -0
  60. package/dist/node/esm/kms/kms.js +15 -0
  61. package/dist/node/esm/proof/proof-service.js +4 -34
  62. package/dist/node/esm/proof/provers/inputs-generator.js +3 -8
  63. package/dist/node/esm/storage/blockchain/onchain-revocation.js +4 -12
  64. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +3 -10
  65. package/dist/node/esm/storage/blockchain/state.js +39 -10
  66. package/dist/node/esm/utils/did-helper.js +33 -1
  67. package/dist/node/esm/verifiable/constants.js +2 -1
  68. package/dist/types/blockchain/index.d.ts +1 -0
  69. package/dist/types/blockchain/transaction-service.d.ts +80 -0
  70. package/dist/types/iden3comm/handlers/auth.d.ts +17 -2
  71. package/dist/types/iden3comm/handlers/common.d.ts +2 -2
  72. package/dist/types/iden3comm/handlers/contract-request.d.ts +10 -2
  73. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +5 -2
  74. package/dist/types/iden3comm/handlers/fetch.d.ts +15 -6
  75. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  76. package/dist/types/iden3comm/handlers/message-handler.d.ts +83 -0
  77. package/dist/types/iden3comm/handlers/revocation-status.d.ts +18 -2
  78. package/dist/types/iden3comm/packageManager.d.ts +10 -0
  79. package/dist/types/iden3comm/packers/jws.d.ts +9 -0
  80. package/dist/types/iden3comm/packers/plain.d.ts +10 -2
  81. package/dist/types/iden3comm/packers/zkp.d.ts +7 -0
  82. package/dist/types/iden3comm/types/packageManager.d.ts +10 -0
  83. package/dist/types/iden3comm/types/packer.d.ts +24 -2
  84. package/dist/types/iden3comm/types/protocol/auth.d.ts +5 -15
  85. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +2 -6
  86. package/dist/types/iden3comm/types/protocol/credentials.d.ts +7 -44
  87. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -9
  88. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -16
  89. package/dist/types/iden3comm/types/protocol/revocation.d.ts +3 -16
  90. package/dist/types/identity/identity-wallet.d.ts +80 -7
  91. package/dist/types/index.d.ts +1 -0
  92. package/dist/types/kms/key-providers/bjj-provider.d.ts +1 -0
  93. package/dist/types/kms/key-providers/ed25519-provider.d.ts +10 -2
  94. package/dist/types/kms/key-providers/index.d.ts +1 -1
  95. package/dist/types/kms/key-providers/{sec256k1-provider.d.ts → secp256k1-provider.d.ts} +15 -9
  96. package/dist/types/kms/kms.d.ts +18 -0
  97. package/dist/types/proof/proof-service.d.ts +2 -2
  98. package/dist/types/storage/blockchain/onchain-revocation.d.ts +1 -0
  99. package/dist/types/storage/blockchain/state.d.ts +7 -2
  100. package/dist/types/storage/interfaces/state.d.ts +26 -2
  101. package/dist/types/utils/did-helper.d.ts +9 -1
  102. package/dist/types/verifiable/constants.d.ts +1 -0
  103. package/package.json +10 -12
  104. package/LICENSE +0 -691
  105. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +0 -71
@@ -34,8 +34,11 @@ const schema_processor_1 = require("../schema-processor");
34
34
  const storage_1 = require("../storage");
35
35
  const verifiable_1 = require("../verifiable");
36
36
  const credentials_1 = require("../credentials");
37
+ const circuits_1 = require("../circuits");
37
38
  const utils_1 = require("../utils");
38
39
  const credential_status_publisher_1 = require("../credentials/status/credential-status-publisher");
40
+ const proof_1 = require("../proof");
41
+ const blockchain_1 = require("../blockchain");
39
42
  /**
40
43
  * @public
41
44
  * Wallet instance to manage the digital identity based on iden3 protocol
@@ -62,6 +65,8 @@ class IdentityWallet {
62
65
  this._credentialWallet = _credentialWallet;
63
66
  this._opts = _opts;
64
67
  this._credentialStatusPublisherRegistry = this.getCredentialStatusPublisherRegistry(_opts);
68
+ this._inputsGenerator = new proof_1.InputGenerator(this, _credentialWallet, _storage.states);
69
+ this._transactionService = new blockchain_1.TransactionService(_storage.states.getRpcProvider());
65
70
  }
66
71
  getCredentialStatusPublisherRegistry(_opts) {
67
72
  if (!_opts?.credentialStatusPublisherRegistry) {
@@ -76,35 +81,16 @@ class IdentityWallet {
76
81
  return this._opts?.credentialStatusPublisherRegistry;
77
82
  }
78
83
  }
79
- /**
80
- * {@inheritDoc IIdentityWallet.createIdentity}
81
- */
82
- async createIdentity(opts) {
83
- const tmpIdentifier = opts.seed ? uuid.v5(js_crypto_1.Hex.encode((0, js_crypto_1.sha256)(opts.seed)), uuid.NIL) : uuid.v4();
84
- opts.method = opts.method ?? js_iden3_core_1.DidMethod.Iden3;
85
- opts.blockchain = opts.blockchain ?? js_iden3_core_1.Blockchain.Polygon;
86
- opts.networkId = opts.networkId ?? js_iden3_core_1.NetworkId.Amoy;
87
- await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
88
- opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
89
- const keyId = await this._kms.createKeyFromSeed(kms_1.KmsKeyType.BabyJubJub, opts.seed);
84
+ async createAuthCoreClaim(revNonce, seed) {
85
+ const keyId = await this._kms.createKeyFromSeed(kms_1.KmsKeyType.BabyJubJub, seed);
90
86
  const pubKeyHex = await this._kms.publicKey(keyId);
91
87
  const pubKey = js_crypto_1.PublicKey.newFromHex(pubKeyHex);
92
88
  const schemaHash = js_iden3_core_1.SchemaHash.authSchemaHash;
93
89
  const authClaim = js_iden3_core_1.Claim.newClaim(schemaHash, js_iden3_core_1.ClaimOptions.withIndexDataInts(pubKey.p[0], pubKey.p[1]), js_iden3_core_1.ClaimOptions.withRevocationNonce(BigInt(0)));
94
- const revNonce = opts.revocationOpts.nonce ?? 0;
95
90
  authClaim.setRevocationNonce(BigInt(revNonce));
96
- await this._storage.mt.addToMerkleTree(tmpIdentifier, storage_1.MerkleTreeType.Claims, authClaim.hiHv().hi, authClaim.hiHv().hv);
97
- const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(tmpIdentifier, storage_1.MerkleTreeType.Claims);
98
- const currentState = (0, js_merkletree_1.hashElems)([
99
- (await claimsTree.root()).bigInt(),
100
- js_merkletree_1.ZERO_HASH.bigInt(),
101
- js_merkletree_1.ZERO_HASH.bigInt()
102
- ]);
103
- const didType = (0, js_iden3_core_1.buildDIDType)(opts.method, opts.blockchain, opts.networkId);
104
- const identifier = js_iden3_core_1.Id.idGenesisFromIdenState(didType, currentState.bigInt());
105
- const did = js_iden3_core_1.DID.parseFromId(identifier);
106
- await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
107
- const schema = JSON.parse(verifiable_1.VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
91
+ return { authClaim, pubKey };
92
+ }
93
+ async createAuthBJJCredential(did, pubKey, authClaim, currentState, revocationOpts) {
108
94
  const authData = authClaim.getExpirationDate();
109
95
  const expiration = authData ? (0, js_iden3_core_1.getUnixTimestamp)(authData) : 0;
110
96
  const request = {
@@ -118,29 +104,91 @@ class IdentityWallet {
118
104
  version: 0,
119
105
  expiration,
120
106
  revocationOpts: {
121
- nonce: revNonce,
122
- id: opts.revocationOpts.id.replace(/\/$/, ''),
123
- type: opts.revocationOpts.type,
107
+ nonce: Number(authClaim.getRevocationNonce()),
108
+ id: revocationOpts.id.replace(/\/$/, ''),
109
+ type: revocationOpts.type,
124
110
  issuerState: currentState.hex()
125
111
  }
126
112
  };
113
+ // Check if has already an auth credential
114
+ const authCredentials = await this._credentialWallet.getAllAuthBJJCredentials(did);
127
115
  let credential = new verifiable_1.W3CCredential();
128
- try {
129
- credential = this._credentialWallet.createCredential(did, request, schema);
116
+ if (authCredentials.length === 0) {
117
+ const schema = JSON.parse(verifiable_1.VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
118
+ try {
119
+ credential = this._credentialWallet.createCredential(did, request, schema);
120
+ }
121
+ catch (e) {
122
+ throw new Error(`Error create w3c credential ${e.message}`);
123
+ }
130
124
  }
131
- catch (e) {
132
- throw new Error(`Error create w3c credential ${e.message}`);
125
+ else {
126
+ // credential with sigProof signed with previous auth bjj credential
127
+ credential = await this.issueCredential(did, request);
133
128
  }
134
- const index = authClaim.hIndex();
129
+ return credential;
130
+ }
131
+ /**
132
+ * {@inheritDoc IIdentityWallet.createIdentity}
133
+ */
134
+ async createIdentity(opts) {
135
+ const tmpIdentifier = opts.seed ? uuid.v5(js_crypto_1.Hex.encode((0, js_crypto_1.sha256)(opts.seed)), uuid.NIL) : uuid.v4();
136
+ opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
137
+ await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
138
+ const revNonce = opts.revocationOpts.nonce ?? 0;
139
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(revNonce, opts.seed);
140
+ const { hi, hv } = authClaim.hiHv();
141
+ await this._storage.mt.addToMerkleTree(tmpIdentifier, storage_1.MerkleTreeType.Claims, hi, hv);
142
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(tmpIdentifier, storage_1.MerkleTreeType.Claims);
135
143
  const ctr = await claimsTree.root();
144
+ const currentState = (0, js_merkletree_1.hashElems)([ctr.bigInt(), js_merkletree_1.ZERO_HASH.bigInt(), js_merkletree_1.ZERO_HASH.bigInt()]);
145
+ const didType = (0, js_iden3_core_1.buildDIDType)(opts.method || js_iden3_core_1.DidMethod.Iden3, opts.blockchain || js_iden3_core_1.Blockchain.Polygon, opts.networkId || js_iden3_core_1.NetworkId.Amoy);
146
+ const identifier = js_iden3_core_1.Id.idGenesisFromIdenState(didType, currentState.bigInt());
147
+ const did = js_iden3_core_1.DID.parseFromId(identifier);
148
+ await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
149
+ const oldTreeState = {
150
+ revocationRoot: js_merkletree_1.ZERO_HASH,
151
+ claimsRoot: ctr,
152
+ state: currentState,
153
+ rootOfRoots: js_merkletree_1.ZERO_HASH
154
+ };
155
+ const identity = await this._storage.identity.getIdentity(did.string());
156
+ if (!identity) {
157
+ await this._storage.identity.saveIdentity({
158
+ did: did.string(),
159
+ state: currentState,
160
+ isStatePublished: false,
161
+ isStateGenesis: true
162
+ });
163
+ }
164
+ // check whether we have auth credential, if not - create a new one
165
+ const credentials = await this._credentialWallet.findByQuery({
166
+ credentialSubject: {
167
+ x: {
168
+ $eq: pubKey.p[0].toString()
169
+ },
170
+ y: {
171
+ $eq: pubKey.p[1].toString()
172
+ }
173
+ },
174
+ allowedIssuers: [did.string()]
175
+ });
176
+ if (credentials.length) {
177
+ return {
178
+ did,
179
+ credential: credentials[0]
180
+ };
181
+ }
182
+ const credential = await this.createAuthBJJCredential(did, pubKey, authClaim, currentState, opts.revocationOpts);
183
+ const index = authClaim.hIndex();
136
184
  const { proof } = await claimsTree.generateProof(index, ctr);
137
185
  const mtpProof = new verifiable_1.Iden3SparseMerkleTreeProof({
138
186
  mtp: proof,
139
187
  issuerData: {
140
188
  id: did,
141
189
  state: {
142
- rootOfRoots: js_merkletree_1.ZERO_HASH,
143
- revocationTreeRoot: js_merkletree_1.ZERO_HASH,
190
+ rootOfRoots: oldTreeState.rootOfRoots,
191
+ revocationTreeRoot: oldTreeState.revocationRoot,
144
192
  claimsTreeRoot: ctr,
145
193
  value: currentState
146
194
  }
@@ -152,13 +200,45 @@ class IdentityWallet {
152
200
  rhsUrl: opts.revocationOpts.id,
153
201
  onChain: opts.revocationOpts.onChain
154
202
  });
203
+ await this._credentialWallet.save(credential);
204
+ return {
205
+ did,
206
+ credential
207
+ };
208
+ }
209
+ /**
210
+ * {@inheritDoc IIdentityWallet.createEthereumBasedIdentity}
211
+ */
212
+ async createEthereumBasedIdentity(opts) {
213
+ opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
214
+ opts.createBjjCredential = opts.createBjjCredential ?? true;
215
+ let credential;
216
+ const ethSigner = opts.ethSigner;
217
+ if (!ethSigner) {
218
+ throw new Error('Ethereum signer is required to create Ethereum identities in order to transit state');
219
+ }
220
+ const currentState = js_merkletree_1.ZERO_HASH; // In Ethereum identities we don't have an initial state with the auth credential
221
+ const didType = (0, js_iden3_core_1.buildDIDType)(opts.method || js_iden3_core_1.DidMethod.Iden3, opts.blockchain || js_iden3_core_1.Blockchain.Polygon, opts.networkId || js_iden3_core_1.NetworkId.Amoy);
222
+ const keyIdEth = await this._kms.createKeyFromSeed(kms_1.KmsKeyType.Secp256k1, opts.seed);
223
+ const pubKeyHexEth = (await this._kms.publicKey(keyIdEth)).slice(2); // 04 + x + y (uncompressed key)
224
+ const did = (0, utils_1.buildDIDFromEthPubKey)(didType, pubKeyHexEth);
225
+ await this._storage.mt.createIdentityMerkleTrees(did.string());
155
226
  await this._storage.identity.saveIdentity({
156
227
  did: did.string(),
157
228
  state: currentState,
158
229
  isStatePublished: false,
159
230
  isStateGenesis: true
160
231
  });
161
- await this._credentialWallet.save(credential);
232
+ if (opts.createBjjCredential) {
233
+ // Old tree state genesis state
234
+ const oldTreeState = {
235
+ revocationRoot: js_merkletree_1.ZERO_HASH,
236
+ claimsRoot: js_merkletree_1.ZERO_HASH,
237
+ state: currentState,
238
+ rootOfRoots: js_merkletree_1.ZERO_HASH
239
+ };
240
+ credential = await this.addBJJAuthCredential(did, oldTreeState, true, ethSigner, opts);
241
+ }
162
242
  return {
163
243
  did,
164
244
  credential
@@ -232,7 +312,10 @@ class IdentityWallet {
232
312
  /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
233
313
  async generateCredentialMtp(did, credential, treeState) {
234
314
  const coreClaim = await this.getCoreClaimFromCredential(credential);
235
- // todo: Parser.parseClaim
315
+ return this.generateCoreClaimMtp(did, coreClaim, treeState);
316
+ }
317
+ /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
318
+ async generateCoreClaimMtp(did, coreClaim, treeState) {
236
319
  const treesModel = await this.getDIDTreeModel(did);
237
320
  const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), storage_1.MerkleTreeType.Claims);
238
321
  const claimsRoot = await treesModel.claimsTree.root();
@@ -366,14 +449,14 @@ class IdentityWallet {
366
449
  };
367
450
  }
368
451
  }
369
- throw new Error('no auth credentials found');
452
+ throw new Error(verifiable_1.VerifiableConstants.ERRORS.NO_AUTH_CRED_FOUND);
370
453
  }
371
454
  /** {@inheritDoc IIdentityWallet.revokeCredential} */
372
455
  async revokeCredential(issuerDID, credential) {
373
456
  const issuerTree = await this.getDIDTreeModel(issuerDID);
374
- const coreClaim = credential.getCoreClaimFromProof(verifiable_1.ProofType.BJJSignature);
457
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
375
458
  if (!coreClaim) {
376
- throw new Error('credential must have coreClaim representation in the signature proof');
459
+ throw new Error('credential must have coreClaim representation in proofs');
377
460
  }
378
461
  const nonce = coreClaim.getRevocationNonce();
379
462
  await issuerTree.revocationTree.add(nonce, BigInt(0));
@@ -420,16 +503,17 @@ class IdentityWallet {
420
503
  }
421
504
  /** {@inheritDoc IIdentityWallet.generateIden3SparseMerkleTreeProof} */
422
505
  // treeState - optional, if it is not passed proof of claim inclusion will be generated on the latest state in the tree.
423
- async generateIden3SparseMerkleTreeProof(issuerDID, credentials, txId, blockNumber, blockTimestamp, treeState) {
506
+ async generateIden3SparseMerkleTreeProof(issuerDID, credentials, txId, blockNumber, blockTimestamp, treeState, opts) {
424
507
  for (let index = 0; index < credentials.length; index++) {
425
508
  const credential = credentials[index];
426
- const mtpWithProof = await this.generateCredentialMtp(issuerDID, credential, treeState);
427
509
  // TODO: return coreClaim from generateCredentialMtp and use it below
428
510
  // credential must have a bjj signature proof
429
- const coreClaim = credential.getCoreClaimFromProof(verifiable_1.ProofType.BJJSignature);
511
+ const coreClaim = credential.getCoreClaimFromProof(verifiable_1.ProofType.BJJSignature) ||
512
+ (await credential.toCoreClaim(opts));
430
513
  if (!coreClaim) {
431
514
  throw new Error('credential must have coreClaim representation in the signature proof');
432
515
  }
516
+ const mtpWithProof = await this.generateCoreClaimMtp(issuerDID, coreClaim, treeState);
433
517
  const mtpProof = new verifiable_1.Iden3SparseMerkleTreeProof({
434
518
  mtp: mtpWithProof.proof,
435
519
  issuerData: {
@@ -450,7 +534,9 @@ class IdentityWallet {
450
534
  credentials[index].proof.push(mtpProof);
451
535
  }
452
536
  else {
453
- credentials[index].proof = [credentials[index].proof, mtpProof];
537
+ credentials[index].proof = credentials[index].proof
538
+ ? [credentials[index].proof, mtpProof]
539
+ : [mtpProof];
454
540
  }
455
541
  }
456
542
  return credentials;
@@ -539,5 +625,104 @@ class IdentityWallet {
539
625
  isStateGenesis: false
540
626
  });
541
627
  }
628
+ /** {@inheritdoc IIdentityWallet.transitState} */
629
+ async transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover) {
630
+ const newTreeModel = await this.getDIDTreeModel(did);
631
+ const claimsRoot = await newTreeModel.claimsTree.root();
632
+ const rootOfRoots = await newTreeModel.rootsTree.root();
633
+ const revocationRoot = await newTreeModel.revocationTree.root();
634
+ const newTreeState = {
635
+ revocationRoot,
636
+ claimsRoot,
637
+ state: newTreeModel.state,
638
+ rootOfRoots
639
+ };
640
+ const userId = js_iden3_core_1.DID.idFromDID(did);
641
+ let proof;
642
+ const isEthIdentity = (0, utils_1.isEthereumIdentity)(did); // don't generate proof for ethereum identities
643
+ let txId;
644
+ if (!isEthIdentity) {
645
+ if (!prover) {
646
+ throw new Error('prover is required to generate proofs for non ethereum identities');
647
+ }
648
+ // generate the proof
649
+ const authInfo = await this._inputsGenerator.prepareAuthBJJCredential(did, oldTreeState);
650
+ const challenge = js_crypto_1.Poseidon.hash([oldTreeState.state.bigInt(), newTreeState.state.bigInt()]);
651
+ const signature = await this.signChallenge(challenge, authInfo.credential);
652
+ const circuitInputs = new circuits_1.StateTransitionInputs();
653
+ circuitInputs.id = userId;
654
+ circuitInputs.signature = signature;
655
+ circuitInputs.isOldStateGenesis = isOldStateGenesis;
656
+ const authClaimIncProofNewState = await this.generateCredentialMtp(did, authInfo.credential, newTreeState);
657
+ circuitInputs.newTreeState = authClaimIncProofNewState.treeState;
658
+ circuitInputs.authClaimNewStateIncProof = authClaimIncProofNewState.proof;
659
+ circuitInputs.oldTreeState = oldTreeState;
660
+ circuitInputs.authClaim = {
661
+ claim: authInfo.coreClaim,
662
+ incProof: authInfo.incProof,
663
+ nonRevProof: authInfo.nonRevProof
664
+ };
665
+ const inputs = circuitInputs.inputsMarshal();
666
+ proof = await prover.generate(inputs, circuits_1.CircuitId.StateTransition);
667
+ txId = await this._storage.states.publishState(proof, ethSigner);
668
+ }
669
+ else {
670
+ const oldUserState = oldTreeState.state;
671
+ const newUserState = newTreeState.state;
672
+ const userStateTransitionInfo = {
673
+ userId,
674
+ oldUserState,
675
+ newUserState,
676
+ isOldStateGenesis,
677
+ methodId: BigInt(1),
678
+ methodParams: '0x'
679
+ };
680
+ txId = await this._storage.states.publishStateGeneric(ethSigner, userStateTransitionInfo);
681
+ }
682
+ await this.updateIdentityState(did, true, newTreeState);
683
+ return txId;
684
+ }
685
+ /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
686
+ async addBJJAuthCredential(did, oldTreeState, isOldStateGenesis, ethSigner, opts, prover // it will be needed in case of non ethereum identities
687
+ ) {
688
+ opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
689
+ opts.revocationOpts.nonce =
690
+ opts.revocationOpts.nonce ??
691
+ (isOldStateGenesis
692
+ ? 0
693
+ : opts.revocationOpts.nonce ?? new DataView((0, js_crypto_1.getRandomBytes)(12).buffer).getUint32(0));
694
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(opts.revocationOpts.nonce ?? 0, opts.seed);
695
+ const { hi, hv } = authClaim.hiHv();
696
+ await this._storage.mt.addToMerkleTree(did.string(), storage_1.MerkleTreeType.Claims, hi, hv);
697
+ // Calculate current state after adding credential to merkle tree
698
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(did.string(), storage_1.MerkleTreeType.Claims);
699
+ const currentState = (0, js_merkletree_1.hashElems)([
700
+ (await claimsTree.root()).bigInt(),
701
+ oldTreeState.revocationRoot.bigInt(),
702
+ oldTreeState.rootOfRoots.bigInt()
703
+ ]);
704
+ let credential = await this.createAuthBJJCredential(did, pubKey, authClaim, currentState, opts.revocationOpts);
705
+ const txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
706
+ const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
707
+ const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(did, [credential], txId, receipt?.blockNumber, block?.timestamp, undefined, {
708
+ revNonce: Number(authClaim.getRevocationNonce()),
709
+ subjectPosition: verifiable_1.SubjectPosition.None,
710
+ merklizedRootPosition: verifiable_1.MerklizedRootPosition.None,
711
+ updatable: false,
712
+ version: 0,
713
+ merklizeOpts: { documentLoader: (0, schema_processor_1.cacheLoader)() }
714
+ });
715
+ await this._credentialWallet.saveAll(credsWithIden3MTPProof);
716
+ const credRefreshed = await this._credentialWallet.findById(credential.id);
717
+ if (!credRefreshed) {
718
+ throw new Error('Credential not found in credential wallet');
719
+ }
720
+ credential = credRefreshed;
721
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
722
+ rhsUrl: opts.revocationOpts.id,
723
+ onChain: opts.revocationOpts.onChain
724
+ });
725
+ return credential;
726
+ }
542
727
  }
543
728
  exports.IdentityWallet = IdentityWallet;
@@ -38,6 +38,7 @@ __exportStar(require("./iden3comm"), exports);
38
38
  __exportStar(require("./circuits"), exports);
39
39
  __exportStar(require("./iden3comm"), exports);
40
40
  __exportStar(require("./utils"), exports);
41
+ __exportStar(require("./blockchain"), exports);
41
42
  const core = __importStar(require("@iden3/js-iden3-core"));
42
43
  exports.core = core;
43
44
  const jsonLDMerklizer = __importStar(require("@iden3/js-jsonld-merklization"));
@@ -26,7 +26,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.BjjProvider = void 0;
27
27
  const js_crypto_1 = require("@iden3/js-crypto");
28
28
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
29
+ const store_1 = require("../store");
29
30
  const providerHelpers = __importStar(require("../provider-helpers"));
31
+ const utils_1 = require("../../utils");
30
32
  /**
31
33
  * Provider for Baby Jub Jub keys
32
34
  * @public
@@ -40,6 +42,9 @@ class BjjProvider {
40
42
  * @param {AbstractPrivateKeyStore} keyStore - key store for kms
41
43
  */
42
44
  constructor(keyType, keyStore) {
45
+ if (keyType !== store_1.KmsKeyType.BabyJubJub) {
46
+ throw new Error('Key type must be BabyJubJub');
47
+ }
43
48
  this.keyType = keyType;
44
49
  this.keyStore = keyStore;
45
50
  }
@@ -94,5 +99,9 @@ class BjjProvider {
94
99
  const privateKeyHex = await this.keyStore.get({ alias: keyId.id });
95
100
  return new js_crypto_1.PrivateKey(js_crypto_1.Hex.decodeString(privateKeyHex));
96
101
  }
102
+ async verify(message, signatureHex, keyId) {
103
+ const publicKey = await this.publicKey(keyId);
104
+ return js_crypto_1.PublicKey.newFromCompressed((0, utils_1.hexToBytes)(publicKey)).verifyPoseidon(js_iden3_core_1.BytesHelper.bytesToInt(message), js_crypto_1.Signature.newFromCompressed((0, utils_1.hexToBytes)(signatureHex)));
105
+ }
97
106
  }
98
107
  exports.BjjProvider = BjjProvider;
@@ -77,12 +77,23 @@ class Ed25519Provider {
77
77
  * signs prepared payload of size,
78
78
  * with a key id
79
79
  * @param {KmsKeyId} keyId - key identifier
80
- * @param {Uint8Array} data - data to sign (32 bytes)
80
+ * @param {Uint8Array} digest - data to sign (32 bytes)
81
81
  * @returns {Promise<Uint8Array>} signature
82
82
  */
83
- async sign(keyId, data) {
83
+ async sign(keyId, digest) {
84
84
  const privateKeyHex = await this.privateKey(keyId);
85
- return ed25519_1.ed25519.sign(data, privateKeyHex);
85
+ return ed25519_1.ed25519.sign(digest, privateKeyHex);
86
+ }
87
+ /**
88
+ * Verifies a signature for the given message and key identifier.
89
+ * @param digest - The message to verify the signature against.
90
+ * @param signatureHex - The signature to verify, as a hexadecimal string.
91
+ * @param keyId - The key identifier to use for verification.
92
+ * @returns A Promise that resolves to a boolean indicating whether the signature is valid.
93
+ */
94
+ async verify(digest, signatureHex, keyId) {
95
+ const publicKeyHex = await this.publicKey(keyId);
96
+ return ed25519_1.ed25519.verify(signatureHex, digest, publicKeyHex);
86
97
  }
87
98
  /**
88
99
  * Retrieves the private key for a given keyId from the key store.
@@ -16,4 +16,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./bjj-provider"), exports);
18
18
  __exportStar(require("./ed25519-provider"), exports);
19
- __exportStar(require("./sec256k1-provider"), exports);
19
+ __exportStar(require("./secp256k1-provider"), exports);
@@ -22,19 +22,18 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
25
  Object.defineProperty(exports, "__esModule", { value: true });
29
26
  exports.Sec256k1Provider = void 0;
30
- const elliptic_1 = __importDefault(require("elliptic"));
27
+ const store_1 = require("../store");
31
28
  const providerHelpers = __importStar(require("../provider-helpers"));
32
- const did_jwt_1 = require("did-jwt");
33
29
  const utils_1 = require("../../utils");
30
+ const secp256k1_1 = require("@noble/curves/secp256k1");
31
+ const js_crypto_1 = require("@iden3/js-crypto");
32
+ const did_jwt_1 = require("did-jwt");
34
33
  /**
35
- * Provider for Sec256p1 keys256p1
34
+ * Provider for Secp256k1
36
35
  * @public
37
- * @class Sec256p1Provider
36
+ * @class Secp256k1Provider
38
37
  * @implements implements IKeyProvider interface
39
38
  */
40
39
  class Sec256k1Provider {
@@ -44,9 +43,11 @@ class Sec256k1Provider {
44
43
  * @param {AbstractPrivateKeyStore} keyStore - key store for kms
45
44
  */
46
45
  constructor(keyType, keyStore) {
46
+ if (keyType !== store_1.KmsKeyType.Secp256k1) {
47
+ throw new Error('Key type must be Secp256k1');
48
+ }
47
49
  this.keyType = keyType;
48
50
  this._keyStore = keyStore;
49
- this._ec = new elliptic_1.default.ec('secp256k1');
50
51
  }
51
52
  /**
52
53
  * generates a baby jub jub key from a seed phrase
@@ -57,12 +58,15 @@ class Sec256k1Provider {
57
58
  if (seed.length !== 32) {
58
59
  throw new Error('Seed should be 32 bytes');
59
60
  }
60
- const keyPair = this._ec.keyFromPrivate(seed);
61
+ const publicKey = secp256k1_1.secp256k1.getPublicKey(seed);
61
62
  const kmsId = {
62
63
  type: this.keyType,
63
- id: providerHelpers.keyPath(this.keyType, keyPair.getPublic().encode('hex', false))
64
+ id: providerHelpers.keyPath(this.keyType, (0, utils_1.bytesToHex)(publicKey))
64
65
  };
65
- await this._keyStore.importKey({ alias: kmsId.id, key: keyPair.getPrivate().toString('hex') });
66
+ await this._keyStore.importKey({
67
+ alias: kmsId.id,
68
+ key: (0, utils_1.bytesToHex)(seed).padStart(64, '0')
69
+ });
66
70
  return kmsId;
67
71
  }
68
72
  /**
@@ -72,27 +76,34 @@ class Sec256k1Provider {
72
76
  */
73
77
  async publicKey(keyId) {
74
78
  const privateKeyHex = await this.privateKey(keyId);
75
- return this._ec.keyFromPrivate(privateKeyHex, 'hex').getPublic().encode('hex', false);
79
+ const publicKey = secp256k1_1.secp256k1.getPublicKey(privateKeyHex, false); // 04 + x + y (uncompressed key)
80
+ return (0, utils_1.bytesToHex)(publicKey);
76
81
  }
77
82
  /**
78
- * signs prepared payload of size,
79
- * with a key id
80
- *
81
- * @param {KmsKeyId} keyId - key identifier
82
- * @param {Uint8Array} data - data to sign (32 bytes)
83
- * @returns Uint8Array signature
83
+ * Signs the given data using the private key associated with the specified key identifier.
84
+ * @param keyId - The key identifier to use for signing.
85
+ * @param data - The data to sign.
86
+ * @param opts - Signing options, such as the algorithm to use.
87
+ * @returns A Promise that resolves to the signature as a Uint8Array.
84
88
  */
85
89
  async sign(keyId, data, opts = { alg: 'ES256K' }) {
86
90
  const privateKeyHex = await this.privateKey(keyId);
87
- if (!privateKeyHex) {
88
- throw new Error('Private key not found for keyId: ' + keyId.id);
91
+ const signatureBase64 = await (0, did_jwt_1.ES256KSigner)((0, did_jwt_1.hexToBytes)(privateKeyHex), opts.alg === 'ES256K-R')(data);
92
+ if (typeof signatureBase64 !== 'string') {
93
+ throw new Error('signatureBase64 must be a string');
89
94
  }
90
- const signatureBase64 = await (0, did_jwt_1.ES256KSigner)((0, utils_1.hexToBytes)(privateKeyHex), opts.alg === 'ES256K-R')(data);
91
- const signatureHex = (0, utils_1.bytesToHex)((0, utils_1.base64UrlToBytes)(signatureBase64.toString()));
92
- if (typeof signatureHex !== 'string') {
93
- throw new Error('Signature is not a string');
94
- }
95
- return utils_1.byteEncoder.encode(signatureBase64.toString());
95
+ return (0, utils_1.base64UrlToBytes)(signatureBase64);
96
+ }
97
+ /**
98
+ * Verifies a signature for the given message and key identifier.
99
+ * @param message - The message to verify the signature against.
100
+ * @param signatureHex - The signature to verify, as a hexadecimal string.
101
+ * @param keyId - The key identifier to use for verification.
102
+ * @returns A Promise that resolves to a boolean indicating whether the signature is valid.
103
+ */
104
+ async verify(message, signatureHex, keyId) {
105
+ const publicKeyHex = await this.publicKey(keyId);
106
+ return secp256k1_1.secp256k1.verify(signatureHex, (0, js_crypto_1.sha256)(message), publicKeyHex);
96
107
  }
97
108
  async privateKey(keyId) {
98
109
  return this._keyStore.get({ alias: keyId.id });
@@ -65,5 +65,20 @@ class KMS {
65
65
  }
66
66
  return keyProvider.sign(keyId, data, opts);
67
67
  }
68
+ /**
69
+ * Verifies a signature against the provided data and key ID.
70
+ *
71
+ * @param data - The data to verify the signature against.
72
+ * @param signatureHex - The signature to verify, in hexadecimal format.
73
+ * @param keyId - The key ID to use for verification.
74
+ * @returns A promise that resolves to a boolean indicating whether the signature is valid.
75
+ */
76
+ verify(data, signatureHex, keyId) {
77
+ const keyProvider = this._registry.get(keyId.type);
78
+ if (!keyProvider) {
79
+ throw new Error(`keyProvider not found for: ${keyId.type}`);
80
+ }
81
+ return keyProvider.verify(data, signatureHex, keyId);
82
+ }
68
83
  }
69
84
  exports.KMS = KMS;
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ProofService = void 0;
4
- const js_crypto_1 = require("@iden3/js-crypto");
5
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
6
5
  const js_merkletree_1 = require("@iden3/js-merkletree");
7
6
  const circuits_1 = require("../circuits");
@@ -133,38 +132,9 @@ class ProofService {
133
132
  };
134
133
  }
135
134
  /** {@inheritdoc IProofService.transitState} */
136
- async transitState(did, oldTreeState, isOldStateGenesis, stateStorage, ethSigner) {
137
- const authInfo = await this._inputsGenerator.prepareAuthBJJCredential(did, oldTreeState);
138
- const newTreeModel = await this._identityWallet.getDIDTreeModel(did);
139
- const claimsRoot = await newTreeModel.claimsTree.root();
140
- const rootOfRoots = await newTreeModel.rootsTree.root();
141
- const revocationRoot = await newTreeModel.revocationTree.root();
142
- const newTreeState = {
143
- revocationRoot,
144
- claimsRoot,
145
- state: newTreeModel.state,
146
- rootOfRoots
147
- };
148
- const challenge = js_crypto_1.Poseidon.hash([oldTreeState.state.bigInt(), newTreeState.state.bigInt()]);
149
- const signature = await this._identityWallet.signChallenge(challenge, authInfo.credential);
150
- const circuitInputs = new circuits_1.StateTransitionInputs();
151
- circuitInputs.id = js_iden3_core_1.DID.idFromDID(did);
152
- circuitInputs.signature = signature;
153
- circuitInputs.isOldStateGenesis = isOldStateGenesis;
154
- const authClaimIncProofNewState = await this._identityWallet.generateCredentialMtp(did, authInfo.credential, newTreeState);
155
- circuitInputs.newTreeState = authClaimIncProofNewState.treeState;
156
- circuitInputs.authClaimNewStateIncProof = authClaimIncProofNewState.proof;
157
- circuitInputs.oldTreeState = oldTreeState;
158
- circuitInputs.authClaim = {
159
- claim: authInfo.coreClaim,
160
- incProof: authInfo.incProof,
161
- nonRevProof: authInfo.nonRevProof
162
- };
163
- const inputs = circuitInputs.inputsMarshal();
164
- const proof = await this._prover.generate(inputs, circuits_1.CircuitId.StateTransition);
165
- const txId = await stateStorage.publishState(proof, ethSigner);
166
- await this._identityWallet.updateIdentityState(did, true, newTreeState);
167
- return txId;
135
+ async transitState(did, oldTreeState, isOldStateGenesis, stateStorage, // for compatibility with previous versions we leave this parameter
136
+ ethSigner) {
137
+ return this._identityWallet.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, this._prover);
168
138
  }
169
139
  async generateInputs(preparedCredential, identifier, proofReq, params, circuitQueries) {
170
140
  return this._inputsGenerator.generateInputs({
@@ -6,6 +6,7 @@ const verifiable_1 = require("../../verifiable");
6
6
  const circuits_1 = require("../../circuits");
7
7
  const common_1 = require("../common");
8
8
  const credentials_1 = require("../../credentials");
9
+ const utils_1 = require("../../utils");
9
10
  const allOperations = Object.values(circuits_1.QueryOperators);
10
11
  const v2Operations = [
11
12
  circuits_1.Operators.NOOP,
@@ -269,13 +270,7 @@ class InputGenerator {
269
270
  circuitInputs.nullifierSessionID = proofReq.params?.nullifierSessionId
270
271
  ? BigInt(proofReq.params?.nullifierSessionId?.toString())
271
272
  : BigInt(0);
272
- let isEthIdentity = true;
273
- try {
274
- js_iden3_core_1.Id.ethAddressFromId(circuitInputs.id);
275
- }
276
- catch {
277
- isEthIdentity = false;
278
- }
273
+ const isEthIdentity = (0, utils_1.isEthereumIdentity)(identifier);
279
274
  circuitInputs.isBJJAuthEnabled = isEthIdentity ? 0 : 1;
280
275
  circuitInputs.challenge = BigInt(params.challenge ?? 0);
281
276
  const { nonce: authProfileNonce, genesisDID } = await this._identityWallet.getGenesisDIDMetadata(identifier);