@0xpolygonid/js-sdk 1.16.1 → 1.17.2

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 (40) hide show
  1. package/dist/browser/esm/index.js +1384 -365
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +1381 -362
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +2 -1
  6. package/dist/node/cjs/iden3comm/handlers/message-handler.js +3 -3
  7. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +3 -3
  8. package/dist/node/cjs/identity/identity-wallet.js +64 -32
  9. package/dist/node/cjs/kms/key-providers/bjj-provider.js +8 -0
  10. package/dist/node/cjs/kms/key-providers/ed25519-provider.js +8 -0
  11. package/dist/node/cjs/kms/key-providers/secp256k1-provider.js +8 -0
  12. package/dist/node/cjs/kms/kms.js +13 -0
  13. package/dist/node/cjs/kms/store/indexed-db-key-store.js +10 -0
  14. package/dist/node/cjs/kms/store/local-storage-key-store.js +14 -0
  15. package/dist/node/cjs/kms/store/memory-key-store.js +3 -0
  16. package/dist/node/cjs/storage/blockchain/state.js +1 -1
  17. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +2 -1
  18. package/dist/node/esm/iden3comm/handlers/message-handler.js +3 -3
  19. package/dist/node/esm/iden3comm/handlers/revocation-status.js +3 -3
  20. package/dist/node/esm/identity/identity-wallet.js +64 -32
  21. package/dist/node/esm/kms/key-providers/bjj-provider.js +8 -0
  22. package/dist/node/esm/kms/key-providers/ed25519-provider.js +8 -0
  23. package/dist/node/esm/kms/key-providers/secp256k1-provider.js +8 -0
  24. package/dist/node/esm/kms/kms.js +13 -0
  25. package/dist/node/esm/kms/store/indexed-db-key-store.js +11 -1
  26. package/dist/node/esm/kms/store/local-storage-key-store.js +14 -0
  27. package/dist/node/esm/kms/store/memory-key-store.js +3 -0
  28. package/dist/node/esm/storage/blockchain/state.js +1 -1
  29. package/dist/types/iden3comm/handlers/message-handler.d.ts +1 -1
  30. package/dist/types/iden3comm/handlers/revocation-status.d.ts +2 -2
  31. package/dist/types/identity/identity-wallet.d.ts +1 -0
  32. package/dist/types/kms/key-providers/bjj-provider.d.ts +8 -0
  33. package/dist/types/kms/key-providers/ed25519-provider.d.ts +8 -0
  34. package/dist/types/kms/key-providers/secp256k1-provider.d.ts +8 -0
  35. package/dist/types/kms/kms.d.ts +19 -0
  36. package/dist/types/kms/store/abstract-key-store.d.ts +10 -0
  37. package/dist/types/kms/store/indexed-db-key-store.d.ts +10 -0
  38. package/dist/types/kms/store/local-storage-key-store.d.ts +10 -0
  39. package/dist/types/kms/store/memory-key-store.d.ts +4 -0
  40. package/package.json +2 -2
@@ -142,7 +142,8 @@ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler
142
142
  }
143
143
  },
144
144
  type: cred.type,
145
- context: cred.context
145
+ context: cred.context,
146
+ allowedIssuers: [proposalRequest.to]
146
147
  });
147
148
  }
148
149
  catch (e) {
@@ -93,10 +93,10 @@ class MessageHandler {
93
93
  return null;
94
94
  }
95
95
  let packerParams = {};
96
- const senderDID = context?.senderDID;
97
- if (unpackedMediaType === constants_1.MediaType.ZKPMessage && senderDID) {
96
+ const senderDid = context?.senderDid;
97
+ if (unpackedMediaType === constants_1.MediaType.ZKPMessage && senderDid) {
98
98
  packerParams = {
99
- senderDID,
99
+ senderDID: senderDid,
100
100
  provingMethodAlg: js_jwz_1.proving.provingMethodGroth16AuthV2Instance.methodAlg
101
101
  };
102
102
  return this._params.packageManager.packMessage(unpackedMediaType, response, packerParams);
@@ -52,7 +52,7 @@ class RevocationStatusHandler extends message_handler_1.AbstractMessageHandler {
52
52
  this._identityWallet = _identityWallet;
53
53
  }
54
54
  handle(message, context) {
55
- if (!context.did) {
55
+ if (!context.senderDid) {
56
56
  throw new Error('DID is required');
57
57
  }
58
58
  if (!context.mediaType) {
@@ -94,7 +94,7 @@ class RevocationStatusHandler extends message_handler_1.AbstractMessageHandler {
94
94
  type: constants_1.PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,
95
95
  thid: rsRequest.thid ?? guid,
96
96
  body: revStatus,
97
- from: context.did.string(),
97
+ from: context.senderDid.string(),
98
98
  to: rsRequest.from
99
99
  };
100
100
  return response;
@@ -124,7 +124,7 @@ class RevocationStatusHandler extends message_handler_1.AbstractMessageHandler {
124
124
  }
125
125
  const rsRequest = await this.parseRevocationStatusRequest(request);
126
126
  const response = await this.handleRevocationStatusRequestMessage(rsRequest, {
127
- did,
127
+ senderDid: did,
128
128
  mediaType: opts.mediaType,
129
129
  packerOptions: opts.packerOptions,
130
130
  treeState: opts.treeState
@@ -217,7 +217,7 @@ class IdentityWallet {
217
217
  opts.createBjjCredential = opts.createBjjCredential ?? true;
218
218
  let credential;
219
219
  const ethSigner = opts.ethSigner;
220
- if (!ethSigner) {
220
+ if (opts.createBjjCredential && !ethSigner) {
221
221
  throw new Error('Ethereum signer is required to create Ethereum identities in order to transit state');
222
222
  }
223
223
  const currentState = js_merkletree_1.ZERO_HASH; // In Ethereum identities we don't have an initial state with the auth credential
@@ -232,7 +232,7 @@ class IdentityWallet {
232
232
  isStatePublished: false,
233
233
  isStateGenesis: true
234
234
  });
235
- if (opts.createBjjCredential) {
235
+ if (opts.createBjjCredential && ethSigner) {
236
236
  // Old tree state genesis state
237
237
  const oldTreeState = {
238
238
  revocationRoot: js_merkletree_1.ZERO_HASH,
@@ -685,16 +685,8 @@ class IdentityWallet {
685
685
  await this.updateIdentityState(did, true, newTreeState);
686
686
  return txId;
687
687
  }
688
- /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
689
- async addBJJAuthCredential(did, oldTreeState, isOldStateGenesis, ethSigner, opts, prover // it will be needed in case of non ethereum identities
690
- ) {
691
- opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
692
- opts.revocationOpts.nonce =
693
- opts.revocationOpts.nonce ??
694
- (isOldStateGenesis
695
- ? 0
696
- : opts.revocationOpts.nonce ?? new DataView((0, js_crypto_1.getRandomBytes)(12).buffer).getUint32(0));
697
- const { authClaim, pubKey } = await this.createAuthCoreClaim(opts.revocationOpts.nonce ?? 0, opts.seed);
688
+ async getAuthBJJCredential(did, oldTreeState, { nonce, seed, id, type }) {
689
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(nonce, seed);
698
690
  const { hi, hv } = authClaim.hiHv();
699
691
  await this._storage.mt.addToMerkleTree(did.string(), storage_1.MerkleTreeType.Claims, hi, hv);
700
692
  // Calculate current state after adding credential to merkle tree
@@ -704,28 +696,68 @@ class IdentityWallet {
704
696
  oldTreeState.revocationRoot.bigInt(),
705
697
  oldTreeState.rootOfRoots.bigInt()
706
698
  ]);
707
- let credential = await this.createAuthBJJCredential(did, pubKey, authClaim, currentState, opts.revocationOpts);
708
- const txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
709
- const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
710
- const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(did, [credential], txId, receipt?.blockNumber, block?.timestamp, undefined, {
711
- revNonce: Number(authClaim.getRevocationNonce()),
712
- subjectPosition: verifiable_1.SubjectPosition.None,
713
- merklizedRootPosition: verifiable_1.MerklizedRootPosition.None,
714
- updatable: false,
715
- version: 0,
716
- merklizeOpts: { documentLoader: (0, schema_processor_1.cacheLoader)() }
699
+ return this.createAuthBJJCredential(did, pubKey, authClaim, currentState, {
700
+ id,
701
+ type
717
702
  });
718
- await this._credentialWallet.saveAll(credsWithIden3MTPProof);
719
- const credRefreshed = await this._credentialWallet.findById(credential.id);
720
- if (!credRefreshed) {
721
- throw new Error('Credential not found in credential wallet');
722
- }
723
- credential = credRefreshed;
724
- await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
725
- rhsUrl: opts.revocationOpts.id,
726
- onChain: opts.revocationOpts.onChain
703
+ }
704
+ /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
705
+ async addBJJAuthCredential(did, oldTreeState, isOldStateGenesis, ethSigner, opts, prover // it will be needed in case of non ethereum identities
706
+ ) {
707
+ opts.seed = opts.seed ?? (0, js_crypto_1.getRandomBytes)(32);
708
+ opts.revocationOpts.nonce =
709
+ opts.revocationOpts.nonce ??
710
+ (isOldStateGenesis
711
+ ? 0
712
+ : opts.revocationOpts.nonce ?? new DataView((0, js_crypto_1.getRandomBytes)(12).buffer).getUint32(0));
713
+ const credential = await this.getAuthBJJCredential(did, oldTreeState, {
714
+ nonce: opts.revocationOpts.nonce,
715
+ seed: opts.seed,
716
+ id: opts.revocationOpts.id,
717
+ type: opts.revocationOpts.type
727
718
  });
728
- return credential;
719
+ const addMtpToCredAndPublishRevState = async () => {
720
+ const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
721
+ const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(did, [credential], txId, receipt?.blockNumber, block?.timestamp, undefined, {
722
+ revNonce: opts.revocationOpts.nonce ?? 0,
723
+ subjectPosition: verifiable_1.SubjectPosition.None,
724
+ merklizedRootPosition: verifiable_1.MerklizedRootPosition.None,
725
+ updatable: false,
726
+ version: 0,
727
+ merklizeOpts: { documentLoader: (0, schema_processor_1.cacheLoader)() }
728
+ });
729
+ await this._credentialWallet.saveAll(credsWithIden3MTPProof);
730
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
731
+ rhsUrl: opts.revocationOpts.id,
732
+ onChain: opts.revocationOpts.onChain
733
+ });
734
+ return credsWithIden3MTPProof[0];
735
+ };
736
+ let txId = '';
737
+ let attempt = 2;
738
+ do {
739
+ try {
740
+ txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
741
+ break;
742
+ }
743
+ catch (err) {
744
+ console.warn(`Error while transiting state, retrying state transition, attempt: ${attempt}`, err);
745
+ }
746
+ } while (--attempt);
747
+ if (!txId) {
748
+ const oldTransitStateInfoJson = JSON.stringify({
749
+ claimsRoot: oldTreeState.claimsRoot.hex(),
750
+ revocationRoot: oldTreeState.revocationRoot.hex(),
751
+ rootOfRoots: oldTreeState.rootOfRoots.hex(),
752
+ state: oldTreeState.state.hex(),
753
+ isOldStateGenesis,
754
+ credentialId: credential.id,
755
+ did: did.string()
756
+ }, null, 2);
757
+ await this._credentialWallet.save(credential);
758
+ throw new Error(`Error publishing state, info to publish: ${oldTransitStateInfoJson}`);
759
+ }
760
+ return addMtpToCredAndPublishRevState();
729
761
  }
730
762
  }
731
763
  exports.IdentityWallet = IdentityWallet;
@@ -48,6 +48,14 @@ class BjjProvider {
48
48
  this.keyType = keyType;
49
49
  this.keyStore = keyStore;
50
50
  }
51
+ /**
52
+ * get all keys
53
+ * @returns list of keys
54
+ */
55
+ async list() {
56
+ const allKeysFromKeyStore = await this.keyStore.list();
57
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
58
+ }
51
59
  /**
52
60
  * generates a baby jub jub key from a seed phrase
53
61
  * @param {Uint8Array} seed - byte array seed
@@ -43,6 +43,14 @@ class Ed25519Provider {
43
43
  this.keyType = keyType;
44
44
  this._keyStore = _keyStore;
45
45
  }
46
+ /**
47
+ * get all keys
48
+ * @returns list of keys
49
+ */
50
+ async list() {
51
+ const allKeysFromKeyStore = await this._keyStore.list();
52
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
53
+ }
46
54
  /**
47
55
  * generates a ed25519 key from a seed phrase
48
56
  * @param {Uint8Array} seed - byte array seed
@@ -49,6 +49,14 @@ class Sec256k1Provider {
49
49
  this.keyType = keyType;
50
50
  this._keyStore = keyStore;
51
51
  }
52
+ /**
53
+ * get all keys
54
+ * @returns list of keys
55
+ */
56
+ async list() {
57
+ const allKeysFromKeyStore = await this._keyStore.list();
58
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
59
+ }
52
60
  /**
53
61
  * generates a baby jub jub key from a seed phrase
54
62
  * @param {Uint8Array} seed - byte array seed
@@ -80,5 +80,18 @@ class KMS {
80
80
  }
81
81
  return keyProvider.verify(data, signatureHex, keyId);
82
82
  }
83
+ /**
84
+ * get all keys by key type
85
+ *
86
+ * @param keyType - Key type
87
+ * @returns list of keys
88
+ */
89
+ list(keyType) {
90
+ const keyProvider = this._registry.get(keyType);
91
+ if (!keyProvider) {
92
+ throw new Error(`keyProvider not found for: ${keyType}`);
93
+ }
94
+ return keyProvider.list();
95
+ }
83
96
  }
84
97
  exports.KMS = KMS;
@@ -14,6 +14,16 @@ class IndexedDBPrivateKeyStore {
14
14
  constructor() {
15
15
  this._store = (0, idb_keyval_1.createStore)(`${IndexedDBPrivateKeyStore.storageKey}-db`, IndexedDBPrivateKeyStore.storageKey);
16
16
  }
17
+ /**
18
+ * get all keys
19
+ *
20
+ * @abstract
21
+ * @returns `Promise<{ alias: string; key: string }[]>`
22
+ */
23
+ async list() {
24
+ const allEntries = await (0, idb_keyval_1.entries)(this._store);
25
+ return allEntries.map(([alias, key]) => ({ alias, key: key.value }));
26
+ }
17
27
  /**
18
28
  * Gets key from the indexed db storage
19
29
  *
@@ -10,6 +10,20 @@ exports.LocalStoragePrivateKeyStore = void 0;
10
10
  * @implements implements AbstractPrivateKeyStore interface
11
11
  */
12
12
  class LocalStoragePrivateKeyStore {
13
+ /**
14
+ * get all keys
15
+ *
16
+ * @abstract
17
+ * @returns `Promise<{ alias: string; key: string }[]>`
18
+ */
19
+ list() {
20
+ const dataStr = localStorage.getItem(LocalStoragePrivateKeyStore.storageKey);
21
+ if (!dataStr) {
22
+ throw new Error('no key under given alias');
23
+ }
24
+ const data = JSON.parse(dataStr);
25
+ return data.map((i) => ({ alias: i.id, key: i.value }));
26
+ }
13
27
  /**
14
28
  * Gets key from the local storage
15
29
  *
@@ -12,6 +12,9 @@ class InMemoryPrivateKeyStore {
12
12
  constructor() {
13
13
  this._data = new Map();
14
14
  }
15
+ list() {
16
+ return Promise.resolve(Array.from(this._data).map(([alias, key]) => ({ alias, key })));
17
+ }
15
18
  async get(args) {
16
19
  const privateKey = this._data.get(args.alias);
17
20
  if (!privateKey) {
@@ -185,7 +185,7 @@ class EthStateStorage {
185
185
  const chainId = (0, js_iden3_core_1.getChainId)(js_iden3_core_1.DID.blockchainFromId(idTyped), js_iden3_core_1.DID.networkIdFromId(idTyped));
186
186
  const config = this.networkByChainId(chainId);
187
187
  const provider = new ethers_1.JsonRpcProvider(config.url);
188
- const stateContract = new ethers_1.Contract(config.contractAddress, State_json_1.default, this.provider);
188
+ const stateContract = new ethers_1.Contract(config.contractAddress, State_json_1.default, provider);
189
189
  return { stateContract, provider };
190
190
  }
191
191
  networkByChainId(chainId) {
@@ -114,7 +114,8 @@ export class CredentialProposalHandler extends AbstractMessageHandler {
114
114
  }
115
115
  },
116
116
  type: cred.type,
117
- context: cred.context
117
+ context: cred.context,
118
+ allowedIssuers: [proposalRequest.to]
118
119
  });
119
120
  }
120
121
  catch (e) {
@@ -89,10 +89,10 @@ export class MessageHandler {
89
89
  return null;
90
90
  }
91
91
  let packerParams = {};
92
- const senderDID = context?.senderDID;
93
- if (unpackedMediaType === MediaType.ZKPMessage && senderDID) {
92
+ const senderDid = context?.senderDid;
93
+ if (unpackedMediaType === MediaType.ZKPMessage && senderDid) {
94
94
  packerParams = {
95
- senderDID,
95
+ senderDID: senderDid,
96
96
  provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
97
97
  };
98
98
  return this._params.packageManager.packMessage(unpackedMediaType, response, packerParams);
@@ -26,7 +26,7 @@ export class RevocationStatusHandler extends AbstractMessageHandler {
26
26
  this._identityWallet = _identityWallet;
27
27
  }
28
28
  handle(message, context) {
29
- if (!context.did) {
29
+ if (!context.senderDid) {
30
30
  throw new Error('DID is required');
31
31
  }
32
32
  if (!context.mediaType) {
@@ -68,7 +68,7 @@ export class RevocationStatusHandler extends AbstractMessageHandler {
68
68
  type: PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,
69
69
  thid: rsRequest.thid ?? guid,
70
70
  body: revStatus,
71
- from: context.did.string(),
71
+ from: context.senderDid.string(),
72
72
  to: rsRequest.from
73
73
  };
74
74
  return response;
@@ -98,7 +98,7 @@ export class RevocationStatusHandler extends AbstractMessageHandler {
98
98
  }
99
99
  const rsRequest = await this.parseRevocationStatusRequest(request);
100
100
  const response = await this.handleRevocationStatusRequestMessage(rsRequest, {
101
- did,
101
+ senderDid: did,
102
102
  mediaType: opts.mediaType,
103
103
  packerOptions: opts.packerOptions,
104
104
  treeState: opts.treeState
@@ -191,7 +191,7 @@ export class IdentityWallet {
191
191
  opts.createBjjCredential = opts.createBjjCredential ?? true;
192
192
  let credential;
193
193
  const ethSigner = opts.ethSigner;
194
- if (!ethSigner) {
194
+ if (opts.createBjjCredential && !ethSigner) {
195
195
  throw new Error('Ethereum signer is required to create Ethereum identities in order to transit state');
196
196
  }
197
197
  const currentState = ZERO_HASH; // In Ethereum identities we don't have an initial state with the auth credential
@@ -206,7 +206,7 @@ export class IdentityWallet {
206
206
  isStatePublished: false,
207
207
  isStateGenesis: true
208
208
  });
209
- if (opts.createBjjCredential) {
209
+ if (opts.createBjjCredential && ethSigner) {
210
210
  // Old tree state genesis state
211
211
  const oldTreeState = {
212
212
  revocationRoot: ZERO_HASH,
@@ -659,16 +659,8 @@ export class IdentityWallet {
659
659
  await this.updateIdentityState(did, true, newTreeState);
660
660
  return txId;
661
661
  }
662
- /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
663
- async addBJJAuthCredential(did, oldTreeState, isOldStateGenesis, ethSigner, opts, prover // it will be needed in case of non ethereum identities
664
- ) {
665
- opts.seed = opts.seed ?? getRandomBytes(32);
666
- opts.revocationOpts.nonce =
667
- opts.revocationOpts.nonce ??
668
- (isOldStateGenesis
669
- ? 0
670
- : opts.revocationOpts.nonce ?? new DataView(getRandomBytes(12).buffer).getUint32(0));
671
- const { authClaim, pubKey } = await this.createAuthCoreClaim(opts.revocationOpts.nonce ?? 0, opts.seed);
662
+ async getAuthBJJCredential(did, oldTreeState, { nonce, seed, id, type }) {
663
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(nonce, seed);
672
664
  const { hi, hv } = authClaim.hiHv();
673
665
  await this._storage.mt.addToMerkleTree(did.string(), MerkleTreeType.Claims, hi, hv);
674
666
  // Calculate current state after adding credential to merkle tree
@@ -678,27 +670,67 @@ export class IdentityWallet {
678
670
  oldTreeState.revocationRoot.bigInt(),
679
671
  oldTreeState.rootOfRoots.bigInt()
680
672
  ]);
681
- let credential = await this.createAuthBJJCredential(did, pubKey, authClaim, currentState, opts.revocationOpts);
682
- const txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
683
- const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
684
- const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(did, [credential], txId, receipt?.blockNumber, block?.timestamp, undefined, {
685
- revNonce: Number(authClaim.getRevocationNonce()),
686
- subjectPosition: SubjectPosition.None,
687
- merklizedRootPosition: MerklizedRootPosition.None,
688
- updatable: false,
689
- version: 0,
690
- merklizeOpts: { documentLoader: cacheLoader() }
673
+ return this.createAuthBJJCredential(did, pubKey, authClaim, currentState, {
674
+ id,
675
+ type
691
676
  });
692
- await this._credentialWallet.saveAll(credsWithIden3MTPProof);
693
- const credRefreshed = await this._credentialWallet.findById(credential.id);
694
- if (!credRefreshed) {
695
- throw new Error('Credential not found in credential wallet');
696
- }
697
- credential = credRefreshed;
698
- await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
699
- rhsUrl: opts.revocationOpts.id,
700
- onChain: opts.revocationOpts.onChain
677
+ }
678
+ /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
679
+ async addBJJAuthCredential(did, oldTreeState, isOldStateGenesis, ethSigner, opts, prover // it will be needed in case of non ethereum identities
680
+ ) {
681
+ opts.seed = opts.seed ?? getRandomBytes(32);
682
+ opts.revocationOpts.nonce =
683
+ opts.revocationOpts.nonce ??
684
+ (isOldStateGenesis
685
+ ? 0
686
+ : opts.revocationOpts.nonce ?? new DataView(getRandomBytes(12).buffer).getUint32(0));
687
+ const credential = await this.getAuthBJJCredential(did, oldTreeState, {
688
+ nonce: opts.revocationOpts.nonce,
689
+ seed: opts.seed,
690
+ id: opts.revocationOpts.id,
691
+ type: opts.revocationOpts.type
701
692
  });
702
- return credential;
693
+ const addMtpToCredAndPublishRevState = async () => {
694
+ const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
695
+ const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(did, [credential], txId, receipt?.blockNumber, block?.timestamp, undefined, {
696
+ revNonce: opts.revocationOpts.nonce ?? 0,
697
+ subjectPosition: SubjectPosition.None,
698
+ merklizedRootPosition: MerklizedRootPosition.None,
699
+ updatable: false,
700
+ version: 0,
701
+ merklizeOpts: { documentLoader: cacheLoader() }
702
+ });
703
+ await this._credentialWallet.saveAll(credsWithIden3MTPProof);
704
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
705
+ rhsUrl: opts.revocationOpts.id,
706
+ onChain: opts.revocationOpts.onChain
707
+ });
708
+ return credsWithIden3MTPProof[0];
709
+ };
710
+ let txId = '';
711
+ let attempt = 2;
712
+ do {
713
+ try {
714
+ txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
715
+ break;
716
+ }
717
+ catch (err) {
718
+ console.warn(`Error while transiting state, retrying state transition, attempt: ${attempt}`, err);
719
+ }
720
+ } while (--attempt);
721
+ if (!txId) {
722
+ const oldTransitStateInfoJson = JSON.stringify({
723
+ claimsRoot: oldTreeState.claimsRoot.hex(),
724
+ revocationRoot: oldTreeState.revocationRoot.hex(),
725
+ rootOfRoots: oldTreeState.rootOfRoots.hex(),
726
+ state: oldTreeState.state.hex(),
727
+ isOldStateGenesis,
728
+ credentialId: credential.id,
729
+ did: did.string()
730
+ }, null, 2);
731
+ await this._credentialWallet.save(credential);
732
+ throw new Error(`Error publishing state, info to publish: ${oldTransitStateInfoJson}`);
733
+ }
734
+ return addMtpToCredAndPublishRevState();
703
735
  }
704
736
  }
@@ -22,6 +22,14 @@ export class BjjProvider {
22
22
  this.keyType = keyType;
23
23
  this.keyStore = keyStore;
24
24
  }
25
+ /**
26
+ * get all keys
27
+ * @returns list of keys
28
+ */
29
+ async list() {
30
+ const allKeysFromKeyStore = await this.keyStore.list();
31
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
32
+ }
25
33
  /**
26
34
  * generates a baby jub jub key from a seed phrase
27
35
  * @param {Uint8Array} seed - byte array seed
@@ -17,6 +17,14 @@ export class Ed25519Provider {
17
17
  this.keyType = keyType;
18
18
  this._keyStore = _keyStore;
19
19
  }
20
+ /**
21
+ * get all keys
22
+ * @returns list of keys
23
+ */
24
+ async list() {
25
+ const allKeysFromKeyStore = await this._keyStore.list();
26
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
27
+ }
20
28
  /**
21
29
  * generates a ed25519 key from a seed phrase
22
30
  * @param {Uint8Array} seed - byte array seed
@@ -23,6 +23,14 @@ export class Sec256k1Provider {
23
23
  this.keyType = keyType;
24
24
  this._keyStore = keyStore;
25
25
  }
26
+ /**
27
+ * get all keys
28
+ * @returns list of keys
29
+ */
30
+ async list() {
31
+ const allKeysFromKeyStore = await this._keyStore.list();
32
+ return allKeysFromKeyStore.filter((key) => key.alias.startsWith(this.keyType));
33
+ }
26
34
  /**
27
35
  * generates a baby jub jub key from a seed phrase
28
36
  * @param {Uint8Array} seed - byte array seed
@@ -77,4 +77,17 @@ export class KMS {
77
77
  }
78
78
  return keyProvider.verify(data, signatureHex, keyId);
79
79
  }
80
+ /**
81
+ * get all keys by key type
82
+ *
83
+ * @param keyType - Key type
84
+ * @returns list of keys
85
+ */
86
+ list(keyType) {
87
+ const keyProvider = this._registry.get(keyType);
88
+ if (!keyProvider) {
89
+ throw new Error(`keyProvider not found for: ${keyType}`);
90
+ }
91
+ return keyProvider.list();
92
+ }
80
93
  }
@@ -1,4 +1,4 @@
1
- import { createStore, get, set } from 'idb-keyval';
1
+ import { createStore, get, set, entries } from 'idb-keyval';
2
2
  /**
3
3
  * Allows storing keys in the indexed db storage of the browser
4
4
  * (NOT ENCRYPTED: DO NOT USE IN THE PRODUCTION)
@@ -11,6 +11,16 @@ export class IndexedDBPrivateKeyStore {
11
11
  constructor() {
12
12
  this._store = createStore(`${IndexedDBPrivateKeyStore.storageKey}-db`, IndexedDBPrivateKeyStore.storageKey);
13
13
  }
14
+ /**
15
+ * get all keys
16
+ *
17
+ * @abstract
18
+ * @returns `Promise<{ alias: string; key: string }[]>`
19
+ */
20
+ async list() {
21
+ const allEntries = await entries(this._store);
22
+ return allEntries.map(([alias, key]) => ({ alias, key: key.value }));
23
+ }
14
24
  /**
15
25
  * Gets key from the indexed db storage
16
26
  *
@@ -7,6 +7,20 @@
7
7
  * @implements implements AbstractPrivateKeyStore interface
8
8
  */
9
9
  export class LocalStoragePrivateKeyStore {
10
+ /**
11
+ * get all keys
12
+ *
13
+ * @abstract
14
+ * @returns `Promise<{ alias: string; key: string }[]>`
15
+ */
16
+ list() {
17
+ const dataStr = localStorage.getItem(LocalStoragePrivateKeyStore.storageKey);
18
+ if (!dataStr) {
19
+ throw new Error('no key under given alias');
20
+ }
21
+ const data = JSON.parse(dataStr);
22
+ return data.map((i) => ({ alias: i.id, key: i.value }));
23
+ }
10
24
  /**
11
25
  * Gets key from the local storage
12
26
  *
@@ -9,6 +9,9 @@ export class InMemoryPrivateKeyStore {
9
9
  constructor() {
10
10
  this._data = new Map();
11
11
  }
12
+ list() {
13
+ return Promise.resolve(Array.from(this._data).map(([alias, key]) => ({ alias, key })));
14
+ }
12
15
  async get(args) {
13
16
  const privateKey = this._data.get(args.alias);
14
17
  if (!privateKey) {
@@ -179,7 +179,7 @@ export class EthStateStorage {
179
179
  const chainId = getChainId(DID.blockchainFromId(idTyped), DID.networkIdFromId(idTyped));
180
180
  const config = this.networkByChainId(chainId);
181
181
  const provider = new JsonRpcProvider(config.url);
182
- const stateContract = new Contract(config.contractAddress, abi, this.provider);
182
+ const stateContract = new Contract(config.contractAddress, abi, provider);
183
183
  return { stateContract, provider };
184
184
  }
185
185
  networkByChainId(chainId) {
@@ -80,7 +80,7 @@ export declare class MessageHandler {
80
80
  * @returns A Promise that resolves to a Uint8Array of the packed response, or null if no response was generated.
81
81
  */
82
82
  handleMessage(bytes: Uint8Array, context: AuthMessageHandlerOptions | ContractMessageHandlerOptions | RevocationStatusMessageHandlerOptions | PaymentRequestMessageHandlerOptions | PaymentHandlerOptions | {
83
- senderDID?: DID;
83
+ senderDid?: DID;
84
84
  [key: string]: unknown;
85
85
  }): Promise<Uint8Array | null>;
86
86
  }
@@ -6,13 +6,13 @@ import { IIdentityWallet } from '../../identity';
6
6
  import { AbstractMessageHandler, IProtocolMessageHandler } from './message-handler';
7
7
  /**
8
8
  * Defines the options for a RevocationStatusMessageHandler.
9
- * @property did - The DID (Decentralized Identifier) to be used.
9
+ * @property senderDid - The DID (Decentralized Identifier) to be used.
10
10
  * @property mediaType - The media type to be used.
11
11
  * @property packerOptions - Optional parameters for the JWS packer.
12
12
  * @property treeState - Optional tree state to be used.
13
13
  */
14
14
  export type RevocationStatusMessageHandlerOptions = {
15
- did: DID;
15
+ senderDid: DID;
16
16
  mediaType: MediaType;
17
17
  packerOptions?: JWSPackerParams;
18
18
  treeState?: TreeState;