@mocanetwork/privado-js-sdk 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 (517) hide show
  1. package/README.md +75 -0
  2. package/dist/browser/esm/index.js +14901 -0
  3. package/dist/browser/esm/index.js.map +1 -0
  4. package/dist/browser/umd/index.global.js +678 -0
  5. package/dist/browser/umd/index.global.js.map +1 -0
  6. package/dist/node/cjs/index.cjs +15418 -0
  7. package/dist/node/cjs/index.cjs.map +1 -0
  8. package/dist/node/esm/index.js +14901 -0
  9. package/dist/node/esm/index.js.map +1 -0
  10. package/dist/types/blockchain/index.d.ts +2 -0
  11. package/dist/types/blockchain/index.d.ts.map +1 -0
  12. package/dist/types/blockchain/transaction-service.d.ts +81 -0
  13. package/dist/types/blockchain/transaction-service.d.ts.map +1 -0
  14. package/dist/types/circuits/atomic-query-mtp-v2-on-chain.d.ts +70 -0
  15. package/dist/types/circuits/atomic-query-mtp-v2-on-chain.d.ts.map +1 -0
  16. package/dist/types/circuits/atomic-query-mtp-v2.d.ts +63 -0
  17. package/dist/types/circuits/atomic-query-mtp-v2.d.ts.map +1 -0
  18. package/dist/types/circuits/atomic-query-sig-v2-on-chain.d.ts +137 -0
  19. package/dist/types/circuits/atomic-query-sig-v2-on-chain.d.ts.map +1 -0
  20. package/dist/types/circuits/atomic-query-sig-v2.d.ts +64 -0
  21. package/dist/types/circuits/atomic-query-sig-v2.d.ts.map +1 -0
  22. package/dist/types/circuits/atomic-query-v3-on-chain.d.ts +141 -0
  23. package/dist/types/circuits/atomic-query-v3-on-chain.d.ts.map +1 -0
  24. package/dist/types/circuits/atomic-query-v3.d.ts +121 -0
  25. package/dist/types/circuits/atomic-query-v3.d.ts.map +1 -0
  26. package/dist/types/circuits/auth-v2.d.ts +46 -0
  27. package/dist/types/circuits/auth-v2.d.ts.map +1 -0
  28. package/dist/types/circuits/common.d.ts +153 -0
  29. package/dist/types/circuits/common.d.ts.map +1 -0
  30. package/dist/types/circuits/comparer.d.ts +122 -0
  31. package/dist/types/circuits/comparer.d.ts.map +1 -0
  32. package/dist/types/circuits/index.d.ts +13 -0
  33. package/dist/types/circuits/index.d.ts.map +1 -0
  34. package/dist/types/circuits/linked-multi-query.d.ts +38 -0
  35. package/dist/types/circuits/linked-multi-query.d.ts.map +1 -0
  36. package/dist/types/circuits/models.d.ts +189 -0
  37. package/dist/types/circuits/models.d.ts.map +1 -0
  38. package/dist/types/circuits/state-transition.d.ts +49 -0
  39. package/dist/types/circuits/state-transition.d.ts.map +1 -0
  40. package/dist/types/credentials/credential-wallet.d.ts +200 -0
  41. package/dist/types/credentials/credential-wallet.d.ts.map +1 -0
  42. package/dist/types/credentials/index.d.ts +12 -0
  43. package/dist/types/credentials/index.d.ts.map +1 -0
  44. package/dist/types/credentials/models.d.ts +84 -0
  45. package/dist/types/credentials/models.d.ts.map +1 -0
  46. package/dist/types/credentials/rhs.d.ts +38 -0
  47. package/dist/types/credentials/rhs.d.ts.map +1 -0
  48. package/dist/types/credentials/status/agent-revocation.d.ts +20 -0
  49. package/dist/types/credentials/status/agent-revocation.d.ts.map +1 -0
  50. package/dist/types/credentials/status/credential-status-publisher.d.ts +73 -0
  51. package/dist/types/credentials/status/credential-status-publisher.d.ts.map +1 -0
  52. package/dist/types/credentials/status/did-resolver-revocation.d.ts +8 -0
  53. package/dist/types/credentials/status/did-resolver-revocation.d.ts.map +1 -0
  54. package/dist/types/credentials/status/on-chain-revocation.d.ts +58 -0
  55. package/dist/types/credentials/status/on-chain-revocation.d.ts.map +1 -0
  56. package/dist/types/credentials/status/resolver.d.ts +69 -0
  57. package/dist/types/credentials/status/resolver.d.ts.map +1 -0
  58. package/dist/types/credentials/status/reverse-sparse-merkle-tree.d.ts +126 -0
  59. package/dist/types/credentials/status/reverse-sparse-merkle-tree.d.ts.map +1 -0
  60. package/dist/types/credentials/status/sparse-merkle-tree.d.ts +38 -0
  61. package/dist/types/credentials/status/sparse-merkle-tree.d.ts.map +1 -0
  62. package/dist/types/credentials/utils.d.ts +15 -0
  63. package/dist/types/credentials/utils.d.ts.map +1 -0
  64. package/dist/types/iden3comm/constants.d.ts +61 -0
  65. package/dist/types/iden3comm/constants.d.ts.map +1 -0
  66. package/dist/types/iden3comm/errors.d.ts +10 -0
  67. package/dist/types/iden3comm/errors.d.ts.map +1 -0
  68. package/dist/types/iden3comm/handlers/auth.d.ts +157 -0
  69. package/dist/types/iden3comm/handlers/auth.d.ts.map +1 -0
  70. package/dist/types/iden3comm/handlers/common.d.ts +72 -0
  71. package/dist/types/iden3comm/handlers/common.d.ts.map +1 -0
  72. package/dist/types/iden3comm/handlers/contract-request.d.ts +96 -0
  73. package/dist/types/iden3comm/handlers/contract-request.d.ts.map +1 -0
  74. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +120 -0
  75. package/dist/types/iden3comm/handlers/credential-proposal.d.ts.map +1 -0
  76. package/dist/types/iden3comm/handlers/discovery-protocol.d.ts +101 -0
  77. package/dist/types/iden3comm/handlers/discovery-protocol.d.ts.map +1 -0
  78. package/dist/types/iden3comm/handlers/fetch.d.ts +130 -0
  79. package/dist/types/iden3comm/handlers/fetch.d.ts.map +1 -0
  80. package/dist/types/iden3comm/handlers/index.d.ts +12 -0
  81. package/dist/types/iden3comm/handlers/index.d.ts.map +1 -0
  82. package/dist/types/iden3comm/handlers/message-handler.d.ts +93 -0
  83. package/dist/types/iden3comm/handlers/message-handler.d.ts.map +1 -0
  84. package/dist/types/iden3comm/handlers/payment.d.ts +167 -0
  85. package/dist/types/iden3comm/handlers/payment.d.ts.map +1 -0
  86. package/dist/types/iden3comm/handlers/problem-report.d.ts +18 -0
  87. package/dist/types/iden3comm/handlers/problem-report.d.ts.map +1 -0
  88. package/dist/types/iden3comm/handlers/refresh.d.ts +57 -0
  89. package/dist/types/iden3comm/handlers/refresh.d.ts.map +1 -0
  90. package/dist/types/iden3comm/handlers/revocation-status.d.ts +76 -0
  91. package/dist/types/iden3comm/handlers/revocation-status.d.ts.map +1 -0
  92. package/dist/types/iden3comm/index.d.ts +9 -0
  93. package/dist/types/iden3comm/index.d.ts.map +1 -0
  94. package/dist/types/iden3comm/packageManager.d.ts +47 -0
  95. package/dist/types/iden3comm/packageManager.d.ts.map +1 -0
  96. package/dist/types/iden3comm/packers/index.d.ts +4 -0
  97. package/dist/types/iden3comm/packers/index.d.ts.map +1 -0
  98. package/dist/types/iden3comm/packers/jws.d.ts +56 -0
  99. package/dist/types/iden3comm/packers/jws.d.ts.map +1 -0
  100. package/dist/types/iden3comm/packers/plain.d.ts +47 -0
  101. package/dist/types/iden3comm/packers/plain.d.ts.map +1 -0
  102. package/dist/types/iden3comm/packers/zkp.d.ts +98 -0
  103. package/dist/types/iden3comm/packers/zkp.d.ts.map +1 -0
  104. package/dist/types/iden3comm/types/index.d.ts +17 -0
  105. package/dist/types/iden3comm/types/index.d.ts.map +1 -0
  106. package/dist/types/iden3comm/types/models.d.ts +7 -0
  107. package/dist/types/iden3comm/types/models.d.ts.map +1 -0
  108. package/dist/types/iden3comm/types/packageManager.d.ts +100 -0
  109. package/dist/types/iden3comm/types/packageManager.d.ts.map +1 -0
  110. package/dist/types/iden3comm/types/packer.d.ts +158 -0
  111. package/dist/types/iden3comm/types/packer.d.ts.map +1 -0
  112. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts +8 -0
  113. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts.map +1 -0
  114. package/dist/types/iden3comm/types/protocol/attachment.d.ts +11 -0
  115. package/dist/types/iden3comm/types/protocol/attachment.d.ts.map +1 -0
  116. package/dist/types/iden3comm/types/protocol/auth.d.ts +90 -0
  117. package/dist/types/iden3comm/types/protocol/auth.d.ts.map +1 -0
  118. package/dist/types/iden3comm/types/protocol/common.d.ts +11 -0
  119. package/dist/types/iden3comm/types/protocol/common.d.ts.map +1 -0
  120. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +62 -0
  121. package/dist/types/iden3comm/types/protocol/contract-request.d.ts.map +1 -0
  122. package/dist/types/iden3comm/types/protocol/credentials.d.ts +82 -0
  123. package/dist/types/iden3comm/types/protocol/credentials.d.ts.map +1 -0
  124. package/dist/types/iden3comm/types/protocol/discovery-protocol.d.ts +42 -0
  125. package/dist/types/iden3comm/types/protocol/discovery-protocol.d.ts.map +1 -0
  126. package/dist/types/iden3comm/types/protocol/messages.d.ts +12 -0
  127. package/dist/types/iden3comm/types/protocol/messages.d.ts.map +1 -0
  128. package/dist/types/iden3comm/types/protocol/payment.d.ts +178 -0
  129. package/dist/types/iden3comm/types/protocol/payment.d.ts.map +1 -0
  130. package/dist/types/iden3comm/types/protocol/problem-report.d.ts +17 -0
  131. package/dist/types/iden3comm/types/protocol/problem-report.d.ts.map +1 -0
  132. package/dist/types/iden3comm/types/protocol/proof.d.ts +22 -0
  133. package/dist/types/iden3comm/types/protocol/proof.d.ts.map +1 -0
  134. package/dist/types/iden3comm/types/protocol/proposal-request.d.ts +33 -0
  135. package/dist/types/iden3comm/types/protocol/proposal-request.d.ts.map +1 -0
  136. package/dist/types/iden3comm/types/protocol/revocation.d.ts +20 -0
  137. package/dist/types/iden3comm/types/protocol/revocation.d.ts.map +1 -0
  138. package/dist/types/iden3comm/utils/accept-profile.d.ts +4 -0
  139. package/dist/types/iden3comm/utils/accept-profile.d.ts.map +1 -0
  140. package/dist/types/iden3comm/utils/did.d.ts +8 -0
  141. package/dist/types/iden3comm/utils/did.d.ts.map +1 -0
  142. package/dist/types/iden3comm/utils/envelope.d.ts +32 -0
  143. package/dist/types/iden3comm/utils/envelope.d.ts.map +1 -0
  144. package/dist/types/iden3comm/utils/index.d.ts +5 -0
  145. package/dist/types/iden3comm/utils/index.d.ts.map +1 -0
  146. package/dist/types/iden3comm/utils/message.d.ts +20 -0
  147. package/dist/types/iden3comm/utils/message.d.ts.map +1 -0
  148. package/dist/types/identity/common.d.ts +27 -0
  149. package/dist/types/identity/common.d.ts.map +1 -0
  150. package/dist/types/identity/identity-wallet.d.ts +472 -0
  151. package/dist/types/identity/identity-wallet.d.ts.map +1 -0
  152. package/dist/types/identity/index.d.ts +3 -0
  153. package/dist/types/identity/index.d.ts.map +1 -0
  154. package/dist/types/index.d.ts +17 -0
  155. package/dist/types/index.d.ts.map +1 -0
  156. package/dist/types/kms/index.d.ts +5 -0
  157. package/dist/types/kms/index.d.ts.map +1 -0
  158. package/dist/types/kms/key-providers/bjj-provider.d.ts +54 -0
  159. package/dist/types/kms/key-providers/bjj-provider.d.ts.map +1 -0
  160. package/dist/types/kms/key-providers/ed25519-provider.d.ts +61 -0
  161. package/dist/types/kms/key-providers/ed25519-provider.d.ts.map +1 -0
  162. package/dist/types/kms/key-providers/index.d.ts +4 -0
  163. package/dist/types/kms/key-providers/index.d.ts.map +1 -0
  164. package/dist/types/kms/key-providers/secp256k1-provider.d.ts +62 -0
  165. package/dist/types/kms/key-providers/secp256k1-provider.d.ts.map +1 -0
  166. package/dist/types/kms/kms.d.ts +120 -0
  167. package/dist/types/kms/kms.d.ts.map +1 -0
  168. package/dist/types/kms/provider-helpers.d.ts +10 -0
  169. package/dist/types/kms/provider-helpers.d.ts.map +1 -0
  170. package/dist/types/kms/store/abstract-key-store.d.ts +41 -0
  171. package/dist/types/kms/store/abstract-key-store.d.ts.map +1 -0
  172. package/dist/types/kms/store/index.d.ts +6 -0
  173. package/dist/types/kms/store/index.d.ts.map +1 -0
  174. package/dist/types/kms/store/indexed-db-key-store.d.ts +44 -0
  175. package/dist/types/kms/store/indexed-db-key-store.d.ts.map +1 -0
  176. package/dist/types/kms/store/local-storage-key-store.d.ts +42 -0
  177. package/dist/types/kms/store/local-storage-key-store.d.ts.map +1 -0
  178. package/dist/types/kms/store/memory-key-store.d.ts +24 -0
  179. package/dist/types/kms/store/memory-key-store.d.ts.map +1 -0
  180. package/dist/types/kms/store/types.d.ts +21 -0
  181. package/dist/types/kms/store/types.d.ts.map +1 -0
  182. package/dist/types/proof/common.d.ts +49 -0
  183. package/dist/types/proof/common.d.ts.map +1 -0
  184. package/dist/types/proof/index.d.ts +5 -0
  185. package/dist/types/proof/index.d.ts.map +1 -0
  186. package/dist/types/proof/proof-service.d.ts +169 -0
  187. package/dist/types/proof/proof-service.d.ts.map +1 -0
  188. package/dist/types/proof/provers/index.d.ts +4 -0
  189. package/dist/types/proof/provers/index.d.ts.map +1 -0
  190. package/dist/types/proof/provers/inputs-generator.d.ts +57 -0
  191. package/dist/types/proof/provers/inputs-generator.d.ts.map +1 -0
  192. package/dist/types/proof/provers/prover.d.ts +56 -0
  193. package/dist/types/proof/provers/prover.d.ts.map +1 -0
  194. package/dist/types/proof/provers/witness_calculator.d.ts +17 -0
  195. package/dist/types/proof/provers/witness_calculator.d.ts.map +1 -0
  196. package/dist/types/proof/verifiers/index.d.ts +4 -0
  197. package/dist/types/proof/verifiers/index.d.ts.map +1 -0
  198. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +60 -0
  199. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts.map +1 -0
  200. package/dist/types/proof/verifiers/query-hash.d.ts +4 -0
  201. package/dist/types/proof/verifiers/query-hash.d.ts.map +1 -0
  202. package/dist/types/proof/verifiers/query.d.ts +43 -0
  203. package/dist/types/proof/verifiers/query.d.ts.map +1 -0
  204. package/dist/types/schema-processor/index.d.ts +4 -0
  205. package/dist/types/schema-processor/index.d.ts.map +1 -0
  206. package/dist/types/schema-processor/json/index.d.ts +3 -0
  207. package/dist/types/schema-processor/json/index.d.ts.map +1 -0
  208. package/dist/types/schema-processor/json/parser.d.ts +141 -0
  209. package/dist/types/schema-processor/json/parser.d.ts.map +1 -0
  210. package/dist/types/schema-processor/json/validator.d.ts +26 -0
  211. package/dist/types/schema-processor/json/validator.d.ts.map +1 -0
  212. package/dist/types/schema-processor/jsonld/cache.d.ts +3 -0
  213. package/dist/types/schema-processor/jsonld/cache.d.ts.map +1 -0
  214. package/dist/types/schema-processor/jsonld/index.d.ts +3 -0
  215. package/dist/types/schema-processor/jsonld/index.d.ts.map +1 -0
  216. package/dist/types/schema-processor/jsonld/parser.d.ts +30 -0
  217. package/dist/types/schema-processor/jsonld/parser.d.ts.map +1 -0
  218. package/dist/types/schema-processor/utils.d.ts +54 -0
  219. package/dist/types/schema-processor/utils.d.ts.map +1 -0
  220. package/dist/types/storage/blockchain/common.d.ts +8 -0
  221. package/dist/types/storage/blockchain/common.d.ts.map +1 -0
  222. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts +17 -0
  223. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts.map +1 -0
  224. package/dist/types/storage/blockchain/erc20-helper.d.ts +20 -0
  225. package/dist/types/storage/blockchain/erc20-helper.d.ts.map +1 -0
  226. package/dist/types/storage/blockchain/errors.d.ts +4 -0
  227. package/dist/types/storage/blockchain/errors.d.ts.map +1 -0
  228. package/dist/types/storage/blockchain/index.d.ts +8 -0
  229. package/dist/types/storage/blockchain/index.d.ts.map +1 -0
  230. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts +67 -0
  231. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts.map +1 -0
  232. package/dist/types/storage/blockchain/onchain-issuer.d.ts +41 -0
  233. package/dist/types/storage/blockchain/onchain-issuer.d.ts.map +1 -0
  234. package/dist/types/storage/blockchain/onchain-revocation.d.ts +41 -0
  235. package/dist/types/storage/blockchain/onchain-revocation.d.ts.map +1 -0
  236. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +116 -0
  237. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts.map +1 -0
  238. package/dist/types/storage/blockchain/state.d.ts +127 -0
  239. package/dist/types/storage/blockchain/state.d.ts.map +1 -0
  240. package/dist/types/storage/entities/circuitData.d.ts +8 -0
  241. package/dist/types/storage/entities/circuitData.d.ts.map +1 -0
  242. package/dist/types/storage/entities/identity.d.ts +17 -0
  243. package/dist/types/storage/entities/identity.d.ts.map +1 -0
  244. package/dist/types/storage/entities/index.d.ts +5 -0
  245. package/dist/types/storage/entities/index.d.ts.map +1 -0
  246. package/dist/types/storage/entities/mt.d.ts +22 -0
  247. package/dist/types/storage/entities/mt.d.ts.map +1 -0
  248. package/dist/types/storage/entities/state.d.ts +92 -0
  249. package/dist/types/storage/entities/state.d.ts.map +1 -0
  250. package/dist/types/storage/errors.d.ts +9 -0
  251. package/dist/types/storage/errors.d.ts.map +1 -0
  252. package/dist/types/storage/filters/index.d.ts +2 -0
  253. package/dist/types/storage/filters/index.d.ts.map +1 -0
  254. package/dist/types/storage/filters/jsonQuery.d.ts +83 -0
  255. package/dist/types/storage/filters/jsonQuery.d.ts.map +1 -0
  256. package/dist/types/storage/fs/circuits-storage.d.ts +64 -0
  257. package/dist/types/storage/fs/circuits-storage.d.ts.map +1 -0
  258. package/dist/types/storage/fs/index.d.ts +2 -0
  259. package/dist/types/storage/fs/index.d.ts.map +1 -0
  260. package/dist/types/storage/index.d.ts +10 -0
  261. package/dist/types/storage/index.d.ts.map +1 -0
  262. package/dist/types/storage/indexed-db/data-source.d.ts +44 -0
  263. package/dist/types/storage/indexed-db/data-source.d.ts.map +1 -0
  264. package/dist/types/storage/indexed-db/index.d.ts +3 -0
  265. package/dist/types/storage/indexed-db/index.d.ts.map +1 -0
  266. package/dist/types/storage/indexed-db/merkletree.d.ts +43 -0
  267. package/dist/types/storage/indexed-db/merkletree.d.ts.map +1 -0
  268. package/dist/types/storage/interfaces/circuits.d.ts +26 -0
  269. package/dist/types/storage/interfaces/circuits.d.ts.map +1 -0
  270. package/dist/types/storage/interfaces/credentials.d.ts +53 -0
  271. package/dist/types/storage/interfaces/credentials.d.ts.map +1 -0
  272. package/dist/types/storage/interfaces/data-source.d.ts +39 -0
  273. package/dist/types/storage/interfaces/data-source.d.ts.map +1 -0
  274. package/dist/types/storage/interfaces/data-storage.d.ts +17 -0
  275. package/dist/types/storage/interfaces/data-storage.d.ts.map +1 -0
  276. package/dist/types/storage/interfaces/identity.d.ts +70 -0
  277. package/dist/types/storage/interfaces/identity.d.ts.map +1 -0
  278. package/dist/types/storage/interfaces/index.d.ts +11 -0
  279. package/dist/types/storage/interfaces/index.d.ts.map +1 -0
  280. package/dist/types/storage/interfaces/merkletree.d.ts +44 -0
  281. package/dist/types/storage/interfaces/merkletree.d.ts.map +1 -0
  282. package/dist/types/storage/interfaces/onchain-issuer.d.ts +13 -0
  283. package/dist/types/storage/interfaces/onchain-issuer.d.ts.map +1 -0
  284. package/dist/types/storage/interfaces/onchain-revocation.d.ts +19 -0
  285. package/dist/types/storage/interfaces/onchain-revocation.d.ts.map +1 -0
  286. package/dist/types/storage/interfaces/onchain-zkp-verifier.d.ts +63 -0
  287. package/dist/types/storage/interfaces/onchain-zkp-verifier.d.ts.map +1 -0
  288. package/dist/types/storage/interfaces/state.d.ts +74 -0
  289. package/dist/types/storage/interfaces/state.d.ts.map +1 -0
  290. package/dist/types/storage/local-storage/data-source.d.ts +41 -0
  291. package/dist/types/storage/local-storage/data-source.d.ts.map +1 -0
  292. package/dist/types/storage/local-storage/index.d.ts +3 -0
  293. package/dist/types/storage/local-storage/index.d.ts.map +1 -0
  294. package/dist/types/storage/local-storage/merkletree.d.ts +41 -0
  295. package/dist/types/storage/local-storage/merkletree.d.ts.map +1 -0
  296. package/dist/types/storage/memory/cache-lru.d.ts +11 -0
  297. package/dist/types/storage/memory/cache-lru.d.ts.map +1 -0
  298. package/dist/types/storage/memory/data-source.d.ts +20 -0
  299. package/dist/types/storage/memory/data-source.d.ts.map +1 -0
  300. package/dist/types/storage/memory/index.d.ts +4 -0
  301. package/dist/types/storage/memory/index.d.ts.map +1 -0
  302. package/dist/types/storage/memory/merkletree.d.ts +48 -0
  303. package/dist/types/storage/memory/merkletree.d.ts.map +1 -0
  304. package/dist/types/storage/shared/circuit-storage.d.ts +39 -0
  305. package/dist/types/storage/shared/circuit-storage.d.ts.map +1 -0
  306. package/dist/types/storage/shared/credential-storage.d.ts +39 -0
  307. package/dist/types/storage/shared/credential-storage.d.ts.map +1 -0
  308. package/dist/types/storage/shared/identity-storage.d.ts +45 -0
  309. package/dist/types/storage/shared/identity-storage.d.ts.map +1 -0
  310. package/dist/types/storage/shared/index.d.ts +4 -0
  311. package/dist/types/storage/shared/index.d.ts.map +1 -0
  312. package/dist/types/storage/utils.d.ts +4 -0
  313. package/dist/types/storage/utils.d.ts.map +1 -0
  314. package/dist/types/utils/compare-func.d.ts +2 -0
  315. package/dist/types/utils/compare-func.d.ts.map +1 -0
  316. package/dist/types/utils/did-helper.d.ts +38 -0
  317. package/dist/types/utils/did-helper.d.ts.map +1 -0
  318. package/dist/types/utils/encoding.d.ts +25 -0
  319. package/dist/types/utils/encoding.d.ts.map +1 -0
  320. package/dist/types/utils/index.d.ts +8 -0
  321. package/dist/types/utils/index.d.ts.map +1 -0
  322. package/dist/types/utils/message-bus.d.ts +63 -0
  323. package/dist/types/utils/message-bus.d.ts.map +1 -0
  324. package/dist/types/utils/object.d.ts +10 -0
  325. package/dist/types/utils/object.d.ts.map +1 -0
  326. package/dist/types/utils/payments/evm.d.ts +19 -0
  327. package/dist/types/utils/payments/evm.d.ts.map +1 -0
  328. package/dist/types/utils/payments/solana.d.ts +88 -0
  329. package/dist/types/utils/payments/solana.d.ts.map +1 -0
  330. package/dist/types/verifiable/constants.d.ts +188 -0
  331. package/dist/types/verifiable/constants.d.ts.map +1 -0
  332. package/dist/types/verifiable/core-utils.d.ts +87 -0
  333. package/dist/types/verifiable/core-utils.d.ts.map +1 -0
  334. package/dist/types/verifiable/credential.d.ts +150 -0
  335. package/dist/types/verifiable/credential.d.ts.map +1 -0
  336. package/dist/types/verifiable/index.d.ts +7 -0
  337. package/dist/types/verifiable/index.d.ts.map +1 -0
  338. package/dist/types/verifiable/presentation.d.ts +11 -0
  339. package/dist/types/verifiable/presentation.d.ts.map +1 -0
  340. package/dist/types/verifiable/proof.d.ts +211 -0
  341. package/dist/types/verifiable/proof.d.ts.map +1 -0
  342. package/dist/types/verifiable/schema.d.ts +3 -0
  343. package/dist/types/verifiable/schema.d.ts.map +1 -0
  344. package/package.json +104 -0
  345. package/src/blockchain/index.ts +1 -0
  346. package/src/blockchain/transaction-service.ts +121 -0
  347. package/src/circuits/atomic-query-mtp-v2-on-chain.ts +338 -0
  348. package/src/circuits/atomic-query-mtp-v2.ts +283 -0
  349. package/src/circuits/atomic-query-sig-v2-on-chain.ts +411 -0
  350. package/src/circuits/atomic-query-sig-v2.ts +340 -0
  351. package/src/circuits/atomic-query-v3-on-chain.ts +531 -0
  352. package/src/circuits/atomic-query-v3.ts +461 -0
  353. package/src/circuits/auth-v2.ts +159 -0
  354. package/src/circuits/common.ts +261 -0
  355. package/src/circuits/comparer.ts +227 -0
  356. package/src/circuits/index.ts +12 -0
  357. package/src/circuits/linked-multi-query.ts +180 -0
  358. package/src/circuits/models.ts +263 -0
  359. package/src/circuits/state-transition.ts +139 -0
  360. package/src/credentials/credential-wallet.ts +353 -0
  361. package/src/credentials/index.ts +11 -0
  362. package/src/credentials/models.ts +93 -0
  363. package/src/credentials/rhs.ts +176 -0
  364. package/src/credentials/status/agent-revocation.ts +69 -0
  365. package/src/credentials/status/credential-status-publisher.ts +143 -0
  366. package/src/credentials/status/did-resolver-revocation.ts +24 -0
  367. package/src/credentials/status/on-chain-revocation.ts +174 -0
  368. package/src/credentials/status/resolver.ts +81 -0
  369. package/src/credentials/status/reverse-sparse-merkle-tree.ts +366 -0
  370. package/src/credentials/status/sparse-merkle-tree.ts +50 -0
  371. package/src/credentials/utils.ts +36 -0
  372. package/src/iden3comm/constants.ts +119 -0
  373. package/src/iden3comm/errors.ts +14 -0
  374. package/src/iden3comm/handlers/auth.ts +520 -0
  375. package/src/iden3comm/handlers/common.ts +324 -0
  376. package/src/iden3comm/handlers/contract-request.ts +367 -0
  377. package/src/iden3comm/handlers/credential-proposal.ts +371 -0
  378. package/src/iden3comm/handlers/discovery-protocol.ts +277 -0
  379. package/src/iden3comm/handlers/fetch.ts +450 -0
  380. package/src/iden3comm/handlers/index.ts +11 -0
  381. package/src/iden3comm/handlers/message-handler.ts +165 -0
  382. package/src/iden3comm/handlers/payment.ts +698 -0
  383. package/src/iden3comm/handlers/problem-report.ts +41 -0
  384. package/src/iden3comm/handlers/refresh.ts +138 -0
  385. package/src/iden3comm/handlers/revocation-status.ts +228 -0
  386. package/src/iden3comm/index.ts +9 -0
  387. package/src/iden3comm/packageManager.ts +143 -0
  388. package/src/iden3comm/packers/index.ts +3 -0
  389. package/src/iden3comm/packers/jws.ts +225 -0
  390. package/src/iden3comm/packers/plain.ts +86 -0
  391. package/src/iden3comm/packers/zkp.ts +243 -0
  392. package/src/iden3comm/types/index.ts +17 -0
  393. package/src/iden3comm/types/models.ts +7 -0
  394. package/src/iden3comm/types/packageManager.ts +112 -0
  395. package/src/iden3comm/types/packer.ts +190 -0
  396. package/src/iden3comm/types/protocol/accept-profile.ts +14 -0
  397. package/src/iden3comm/types/protocol/attachment.ts +12 -0
  398. package/src/iden3comm/types/protocol/auth.ts +104 -0
  399. package/src/iden3comm/types/protocol/common.ts +10 -0
  400. package/src/iden3comm/types/protocol/contract-request.ts +76 -0
  401. package/src/iden3comm/types/protocol/credentials.ts +96 -0
  402. package/src/iden3comm/types/protocol/discovery-protocol.ts +49 -0
  403. package/src/iden3comm/types/protocol/messages.ts +13 -0
  404. package/src/iden3comm/types/protocol/payment.ts +231 -0
  405. package/src/iden3comm/types/protocol/problem-report.ts +18 -0
  406. package/src/iden3comm/types/protocol/proof.ts +25 -0
  407. package/src/iden3comm/types/protocol/proposal-request.ts +38 -0
  408. package/src/iden3comm/types/protocol/revocation.ts +23 -0
  409. package/src/iden3comm/utils/accept-profile.ts +121 -0
  410. package/src/iden3comm/utils/did.ts +71 -0
  411. package/src/iden3comm/utils/envelope.ts +101 -0
  412. package/src/iden3comm/utils/index.ts +4 -0
  413. package/src/iden3comm/utils/message.ts +41 -0
  414. package/src/identity/common.ts +69 -0
  415. package/src/identity/identity-wallet.ts +1592 -0
  416. package/src/identity/index.ts +2 -0
  417. package/src/index.ts +16 -0
  418. package/src/kms/index.ts +4 -0
  419. package/src/kms/key-providers/bjj-provider.ts +118 -0
  420. package/src/kms/key-providers/ed25519-provider.ts +105 -0
  421. package/src/kms/key-providers/index.ts +3 -0
  422. package/src/kms/key-providers/secp256k1-provider.ts +125 -0
  423. package/src/kms/kms.ts +173 -0
  424. package/src/kms/provider-helpers.ts +13 -0
  425. package/src/kms/store/abstract-key-store.ts +34 -0
  426. package/src/kms/store/index.ts +5 -0
  427. package/src/kms/store/indexed-db-key-store.ts +60 -0
  428. package/src/kms/store/local-storage-key-store.ts +69 -0
  429. package/src/kms/store/memory-key-store.ts +29 -0
  430. package/src/kms/store/types.ts +21 -0
  431. package/src/proof/common.ts +273 -0
  432. package/src/proof/index.ts +4 -0
  433. package/src/proof/proof-service.ts +623 -0
  434. package/src/proof/provers/index.ts +3 -0
  435. package/src/proof/provers/inputs-generator.ts +627 -0
  436. package/src/proof/provers/prover.ts +104 -0
  437. package/src/proof/provers/witness_calculator.ts +315 -0
  438. package/src/proof/verifiers/index.ts +3 -0
  439. package/src/proof/verifiers/pub-signals-verifier.ts +730 -0
  440. package/src/proof/verifiers/query-hash.ts +57 -0
  441. package/src/proof/verifiers/query.ts +340 -0
  442. package/src/schema-processor/index.ts +3 -0
  443. package/src/schema-processor/json/index.ts +2 -0
  444. package/src/schema-processor/json/parser.ts +256 -0
  445. package/src/schema-processor/json/validator.ts +67 -0
  446. package/src/schema-processor/jsonld/cache.ts +49 -0
  447. package/src/schema-processor/jsonld/index.ts +2 -0
  448. package/src/schema-processor/jsonld/parser.ts +93 -0
  449. package/src/schema-processor/utils.ts +84 -0
  450. package/src/storage/blockchain/abi/CredentialStatusResolver.json +1 -0
  451. package/src/storage/blockchain/abi/ERC20.json +1 -0
  452. package/src/storage/blockchain/abi/ERC20Permit.json +1 -0
  453. package/src/storage/blockchain/abi/IdentityBase.json +1 -0
  454. package/src/storage/blockchain/abi/State.json +1 -0
  455. package/src/storage/blockchain/abi/ZkpVerifier.json +789 -0
  456. package/src/storage/blockchain/common.ts +20 -0
  457. package/src/storage/blockchain/did-resolver-readonly-storage.ts +90 -0
  458. package/src/storage/blockchain/erc20-helper.ts +66 -0
  459. package/src/storage/blockchain/errors.ts +46 -0
  460. package/src/storage/blockchain/index.ts +7 -0
  461. package/src/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.ts +327 -0
  462. package/src/storage/blockchain/onchain-issuer.ts +104 -0
  463. package/src/storage/blockchain/onchain-revocation.ts +143 -0
  464. package/src/storage/blockchain/onchain-zkp-verifier.ts +704 -0
  465. package/src/storage/blockchain/state.ts +471 -0
  466. package/src/storage/entities/circuitData.ts +7 -0
  467. package/src/storage/entities/identity.ts +18 -0
  468. package/src/storage/entities/index.ts +4 -0
  469. package/src/storage/entities/mt.ts +25 -0
  470. package/src/storage/entities/state.ts +97 -0
  471. package/src/storage/errors.ts +8 -0
  472. package/src/storage/filters/index.ts +1 -0
  473. package/src/storage/filters/jsonQuery.ts +368 -0
  474. package/src/storage/fs/circuits-storage.ts +149 -0
  475. package/src/storage/fs/index.ts +1 -0
  476. package/src/storage/index.ts +9 -0
  477. package/src/storage/indexed-db/data-source.ts +58 -0
  478. package/src/storage/indexed-db/index.ts +2 -0
  479. package/src/storage/indexed-db/merkletree.ts +140 -0
  480. package/src/storage/interfaces/circuits.ts +27 -0
  481. package/src/storage/interfaces/credentials.ts +53 -0
  482. package/src/storage/interfaces/data-source.ts +41 -0
  483. package/src/storage/interfaces/data-storage.ts +17 -0
  484. package/src/storage/interfaces/identity.ts +73 -0
  485. package/src/storage/interfaces/index.ts +10 -0
  486. package/src/storage/interfaces/merkletree.ts +52 -0
  487. package/src/storage/interfaces/onchain-issuer.ts +13 -0
  488. package/src/storage/interfaces/onchain-revocation.ts +22 -0
  489. package/src/storage/interfaces/onchain-zkp-verifier.ts +94 -0
  490. package/src/storage/interfaces/state.ts +81 -0
  491. package/src/storage/local-storage/data-source.ts +87 -0
  492. package/src/storage/local-storage/index.ts +2 -0
  493. package/src/storage/local-storage/merkletree.ts +137 -0
  494. package/src/storage/memory/cache-lru.ts +30 -0
  495. package/src/storage/memory/data-source.ts +45 -0
  496. package/src/storage/memory/index.ts +3 -0
  497. package/src/storage/memory/merkletree.ts +116 -0
  498. package/src/storage/shared/circuit-storage.ts +49 -0
  499. package/src/storage/shared/credential-storage.ts +70 -0
  500. package/src/storage/shared/identity-storage.ts +82 -0
  501. package/src/storage/shared/index.ts +3 -0
  502. package/src/storage/utils.ts +19 -0
  503. package/src/utils/compare-func.ts +5 -0
  504. package/src/utils/did-helper.ts +157 -0
  505. package/src/utils/encoding.ts +47 -0
  506. package/src/utils/index.ts +7 -0
  507. package/src/utils/message-bus.ts +88 -0
  508. package/src/utils/object.ts +52 -0
  509. package/src/utils/payments/evm.ts +152 -0
  510. package/src/utils/payments/solana.ts +360 -0
  511. package/src/verifiable/constants.ts +239 -0
  512. package/src/verifiable/core-utils.ts +307 -0
  513. package/src/verifiable/credential.ts +649 -0
  514. package/src/verifiable/index.ts +6 -0
  515. package/src/verifiable/presentation.ts +97 -0
  516. package/src/verifiable/proof.ts +277 -0
  517. package/src/verifiable/schema.ts +241 -0
@@ -0,0 +1,1592 @@
1
+ import { KMS, KmsKeyId, KmsKeyType } from '../kms';
2
+ import {
3
+ Blockchain,
4
+ buildDIDType,
5
+ BytesHelper,
6
+ Claim,
7
+ ClaimOptions,
8
+ DID,
9
+ DidMethod,
10
+ getUnixTimestamp,
11
+ Id,
12
+ NetworkId,
13
+ SchemaHash
14
+ } from '@mocanetwork/moca-iden3';
15
+ import {
16
+ poseidon,
17
+ PublicKey,
18
+ sha256,
19
+ Signature,
20
+ Hex,
21
+ getRandomBytes,
22
+ Poseidon
23
+ } from '@iden3/js-crypto';
24
+ import { Hash, hashElems, ZERO_HASH } from '@iden3/js-merkletree';
25
+ import { generateProfileDID, subjectPositionIndex } from './common';
26
+ import * as uuid from 'uuid';
27
+ import { JSONSchema, JsonSchemaValidator, cacheLoader } from '../schema-processor';
28
+ import { IDataStorage, MerkleTreeType, Profile, UserStateTransitionInfo } from '../storage';
29
+ import {
30
+ VerifiableConstants,
31
+ BJJSignatureProof2021,
32
+ MerklizedRootPosition,
33
+ SubjectPosition,
34
+ W3CCredential,
35
+ MerkleTreeProofWithTreeState,
36
+ Iden3SparseMerkleTreeProof,
37
+ ProofType,
38
+ CredentialStatusType,
39
+ ProofQuery,
40
+ CoreClaimCreationOptions
41
+ } from '../verifiable';
42
+ import {
43
+ CredentialRequest,
44
+ getKMSIdByAuthCredential,
45
+ getNodesRepresentation,
46
+ ICredentialWallet,
47
+ ProofNode,
48
+ PublishMode,
49
+ pushHashesToRHS,
50
+ TreesModel
51
+ } from '../credentials';
52
+ import { CircuitId, StateTransitionInputs, TreeState } from '../circuits';
53
+ import { buildDIDFromEthPubKey, byteEncoder, isEthereumIdentity } from '../utils';
54
+ import { Options } from '@iden3/js-jsonld-merklization';
55
+ import { Signer, TransactionReceipt } from 'ethers';
56
+ import {
57
+ CredentialStatusPublisherRegistry,
58
+ Iden3SmtRhsCredentialStatusPublisher
59
+ } from '../credentials/status/credential-status-publisher';
60
+ import { InputGenerator, IZKProver } from '../proof';
61
+ import { ITransactionService, TransactionService } from '../blockchain';
62
+
63
+ /**
64
+ * DID creation options
65
+ * seed - seed to generate BJJ key pair
66
+ * revocationOpts -
67
+
68
+ * @type IdentityCreationOptions
69
+ */
70
+ export type IdentityCreationOptions = {
71
+ method?: string;
72
+ blockchain?: string;
73
+ networkId?: string;
74
+ } & AuthBJJCredentialCreationOptions;
75
+
76
+ /**
77
+ * Options for creating Auth BJJ credential
78
+ * seed - seed to generate BJJ key pair
79
+ * revocationOpts
80
+ * nonce - explicit revocation nonce to use
81
+ * onChain - onchain status related option
82
+ * txCallback - defines how the TransactionReceipt is handled
83
+ * publishMode - specifies the work of transaction polling type: sync / async / callback
84
+ * genesisPublishingDisabled - genesis is publishing by default. Set `true` to prevent genesis publishing
85
+ */
86
+ export type AuthBJJCredentialCreationOptions = {
87
+ revocationOpts: {
88
+ id: string;
89
+ type: CredentialStatusType;
90
+ nonce?: number;
91
+ genesisPublishingDisabled?: boolean;
92
+ onChain?: {
93
+ txCallback?: (tx: TransactionReceipt) => Promise<void>;
94
+ publishMode?: PublishMode;
95
+ };
96
+ };
97
+ seed?: Uint8Array;
98
+ };
99
+
100
+ /**
101
+ * Options for creating Ethereum based identity
102
+ */
103
+ export type EthereumBasedIdentityCreationOptions = IdentityCreationOptions & {
104
+ ethSigner?: Signer;
105
+ createBjjCredential?: boolean;
106
+ };
107
+
108
+ /**
109
+ * Options for RevocationInfoOptions.
110
+ */
111
+ export type RevocationInfoOptions = {
112
+ revokedNonces?: number[];
113
+ treeModel?: TreesModel;
114
+ rhsUrl?: string;
115
+ onChain?: {
116
+ txCallback?: (tx: TransactionReceipt) => Promise<void>;
117
+ publishMode?: PublishMode;
118
+ };
119
+ };
120
+
121
+ /**
122
+ * Proof creation result
123
+ *
124
+ * @public
125
+ * @interface Iden3ProofCreationResult
126
+ */
127
+ export interface Iden3ProofCreationResult {
128
+ credentials: W3CCredential[];
129
+ oldTreeState: TreeState;
130
+ newTreeState: TreeState;
131
+ }
132
+ /**
133
+ * Interface for IdentityWallet
134
+ * @public
135
+ */
136
+ export interface IIdentityWallet {
137
+ /**
138
+ * Create Identity creates Auth BJJ credential,
139
+ * Merkle trees for claims, revocations and root of roots,
140
+ * adds auth BJJ credential to claims tree and generates mtp of inclusion
141
+ * based on the resulting state it provides an identifier in DID form.
142
+ *
143
+ * @param {IdentityCreationOptions} opts - default is did:iden3:polygon:amoy** with generated key.
144
+ * @returns `Promise<{ did: DID; credential: W3CCredential }>` - returns did and Auth BJJ credential
145
+ * @public
146
+ */
147
+ createIdentity(opts: IdentityCreationOptions): Promise<{ did: DID; credential: W3CCredential }>;
148
+
149
+ /**
150
+ * Credential wallet getter
151
+ *
152
+ * @returns {ICredentialWallet}
153
+ * @memberof IIdentityWallet
154
+ */
155
+ get credentialWallet(): ICredentialWallet;
156
+
157
+ /**
158
+ * Create Identity based in Ethereum address and it provides an identifier in DID form.
159
+ *
160
+ * @param {IdentityCreationOptions} opts - default is did:iden3:polygon:amoy** with generated key.
161
+ * @returns `Promise<{ did: DID; credential: W3CCredential | undefined }>` - returns did and Auth BJJ credential
162
+ * @public
163
+ */
164
+ createEthereumBasedIdentity(
165
+ opts: EthereumBasedIdentityCreationOptions
166
+ ): Promise<{ did: DID; credential: W3CCredential | undefined }>;
167
+
168
+ /**
169
+ * Creates profile based on genesis identifier
170
+ *
171
+ * @param {DID} did - identity to derive profile from
172
+ * @param {number |string} nonce - unique integer number to generate a profile
173
+ * @param {string} verifier - verifier identity/alias in a string from
174
+ * @param {string[]} tags - optional tag that can be assigned to profile by client
175
+ * @returns `Promise<DID>` - profile did
176
+ */
177
+ createProfile(did: DID, nonce: number | string, verifier: string, tags?: string[]): Promise<DID>;
178
+
179
+ /**
180
+ * Generates a new key
181
+ *
182
+ * @param {KmsKeyType} keyType - supported key type by KMS
183
+ * @returns `Promise<KmsKeyId>` - creates a new key BJJ or ECDSA
184
+ */
185
+ generateKey(keyType: KmsKeyType): Promise<KmsKeyId>;
186
+
187
+ /**
188
+ * Issues new credential from issuer according to the claim request
189
+ *
190
+ * @param {DID} issuerDID - issuer identity
191
+ * @param {CredentialRequest} req - claim request
192
+ * @returns `Promise<W3CCredential>` - returns created W3CCredential
193
+ */
194
+ issueCredential(issuerDID: DID, req: CredentialRequest, opts?: Options): Promise<W3CCredential>;
195
+
196
+ /**
197
+ * Gets a tree model for given did that includes claims tree, revocation tree, the root of roots tree and calculated state hash
198
+ *
199
+ * @param {DID} did - did which trees info we need to receive
200
+ * @returns `Promise<TreesModel>`
201
+ * */
202
+ getDIDTreeModel(did: DID): Promise<TreesModel>;
203
+
204
+ /**
205
+ * Generates proof of credential inclusion / non-inclusion to the given claims tree
206
+ * and its root or to the current root of the Claims tree in the given Merkle tree storage.
207
+ *
208
+ * @param {DID} did - issuer did
209
+ * @param {W3CCredential} credential - credential to generate mtp
210
+ * @param {TreeState} [treeState] - tree state when to generate a proof
211
+ * @returns `Promise<MerkleTreeProofWithTreeState>` - MerkleTreeProof and TreeState on which proof has been generated
212
+ */
213
+ generateCredentialMtp(
214
+ did: DID,
215
+ credential: W3CCredential,
216
+ treeState?: TreeState
217
+ ): Promise<MerkleTreeProofWithTreeState>;
218
+
219
+ /**
220
+ * Generates proof of core claim inclusion / non-inclusion to the given claims tree
221
+ * and its root or to the current root of the Claims tree in the given Merkle tree storage.
222
+ *
223
+ * @param {DID} did - issuer did
224
+ * @param {core.Claim} core - core claim to generate mtp
225
+ * @param {TreeState} [treeState] - tree state when to generate a proof
226
+ * @returns `Promise<MerkleTreeProofWithTreeState>` - MerkleTreeProof and TreeState on which proof has been generated
227
+ */
228
+ generateCoreClaimMtp(
229
+ did: DID,
230
+ coreClaim: Claim,
231
+ treeState?: TreeState
232
+ ): Promise<MerkleTreeProofWithTreeState>;
233
+
234
+ /**
235
+ * Generates proof of credential revocation nonce (with credential as a param) inclusion / non-inclusion to the given revocation tree
236
+ * and its root or to the current root of the Revocation tree in the given Merkle tree storage.
237
+ *
238
+ * @param {DID} did
239
+ * @param {W3CCredential} credential
240
+ * @param {TreeState} [treeState]
241
+ * @returns `Promise<MerkleTreeProofWithTreeState>` - MerkleTreeProof and TreeState on which proof has been generated
242
+ */
243
+ generateNonRevocationMtp(
244
+ did: DID,
245
+ credential: W3CCredential,
246
+ treeState?: TreeState
247
+ ): Promise<MerkleTreeProofWithTreeState>;
248
+
249
+ /**
250
+ * Generates proof of credential revocation nonce (with revNonce as a param) inclusion / non-inclusion to the given revocation tree
251
+ * and its root or to the current root of the Revocation tree in the given Merkle tree storage.
252
+ *
253
+ * @param {DID} did
254
+ * @param {bigint} revNonce
255
+ * @param {TreeState} [treeState]
256
+ * @returns `Promise<MerkleTreeProofWithTreeState>` - MerkleTreeProof and TreeState on which proof has been generated
257
+ */
258
+ generateNonRevocationMtpWithNonce(
259
+ did: DID,
260
+ revNonce: bigint,
261
+ treeState?: TreeState
262
+ ): Promise<MerkleTreeProofWithTreeState>;
263
+
264
+ /**
265
+ * Signs a payload of arbitrary size with an Auth BJJ Credential that identifies a key for signing.
266
+ *
267
+ * @param {Uint8Array} payload
268
+ * @param {W3CCredential} credential - Auth BJJ Credential
269
+ * @returns `Promise<Signature>`- the signature object with R8 and S params
270
+ */
271
+ sign(payload: Uint8Array, credential: W3CCredential): Promise<Signature>;
272
+
273
+ /**
274
+ * Signs a big integer with an Auth BJJ Credential that identifies a key for signing.
275
+ *
276
+ *
277
+ * @param {bigint} payload - big number in Field
278
+ * @param {W3CCredential} credential - Auth BJJ credential
279
+ * @returns `Promise<Signature>` - the signature object with R8 and S params
280
+ */
281
+ signChallenge(payload: bigint, credential: W3CCredential): Promise<Signature>;
282
+
283
+ /**
284
+ *
285
+ *
286
+ * @param {DID} issuerDID - identifier of the issuer
287
+ * @param {W3CCredential} credential - credential to revoke
288
+ * @returns `Promise<number>` a revocation nonce of credential
289
+ */
290
+ revokeCredential(issuerDID: DID, credential: W3CCredential): Promise<number>;
291
+
292
+ /**
293
+ * Generate Iden3SparseMerkleTree proof of inclusion to issuer state of specific credentials
294
+ *
295
+ * @param {DID} issuerDID - issuer did
296
+ * @param {W3CCredential[]} credentials - list of verifiable credentials to generate a proof
297
+ * @param {string} txId - transaction hash in which state transition has been done
298
+ * @param {number} [blockNumber] - block number in which state transition has been done
299
+ * @param {number} [blockTimestamp] - block timestamp in which state transition has been done
300
+ * @returns `Promise<W3CCredential[]>` credentials with an Iden3SparseMerkleTreeProof
301
+ */
302
+ generateIden3SparseMerkleTreeProof(
303
+ issuerDID: DID,
304
+ credentials: W3CCredential[],
305
+ txId: string,
306
+ blockNumber?: number,
307
+ blockTimestamp?: number
308
+ ): Promise<W3CCredential[]>;
309
+
310
+ /**
311
+ * Adds verifiable credentials to issuer Claims Merkle tree
312
+ *
313
+ * @param {W3CCredential[]} credentials - credentials to include in the claims tree
314
+ * @param {DID} issuerDID - issuer did
315
+ * @returns `Promise<Iden3ProofCreationResult>`- old tree state and tree state with included credentials
316
+ */
317
+ addCredentialsToMerkleTree(
318
+ credentials: W3CCredential[],
319
+ issuerDID: DID
320
+ ): Promise<Iden3ProofCreationResult>;
321
+
322
+ /**
323
+ * Publishes issuer state to the reverse hash service by given URL
324
+ *
325
+ * @deprecated use publishRevocationInfoByCredentialStatusType instead with the same arguments in opts
326
+ * @param {DID} issuerDID - issuer did
327
+ * @param {string} rhsURL - reverse hash service URL
328
+ * @param {number[]} [revokedNonces] - revoked nonces for the period from the last published
329
+ * @returns `Promise<void>`
330
+ */
331
+ publishStateToRHS(
332
+ issuerDID: DID,
333
+ rhsURL: string,
334
+ revokedNonces?: number[],
335
+ opts?: object
336
+ ): Promise<void>;
337
+
338
+ /**
339
+ * Publishes specific state to the reverse hash service by given URL
340
+ * @deprecated use publishRevocationInfoByCredentialStatusType instead with the same arguments in opts
341
+ * @param {TreesModel} treeModel - trees model to publish
342
+ * @param {string} rhsURL - reverse hash service URL
343
+ * @param {number[]} [revokedNonces] - revoked nonces for the period from the last published
344
+ * @returns `Promise<void>`
345
+ */
346
+ publishSpecificStateToRHS(
347
+ treeModel: TreesModel,
348
+ rhsURL: string,
349
+ revokedNonces?: number[],
350
+ opts?: object
351
+ ): Promise<void>;
352
+
353
+ /**
354
+ * Publishes revocation info by credential status predefined publishers
355
+ *
356
+ * @param {(RevocationInfoOptions)} opts
357
+ * @returns {Promise<void>}
358
+ * @memberof IIdentityWallet
359
+ */
360
+ publishRevocationInfoByCredentialStatusType(
361
+ issuerDID: DID,
362
+ credentialStatusType: CredentialStatusType,
363
+ opts?: RevocationInfoOptions
364
+ ): Promise<void>;
365
+
366
+ /**
367
+ * Extracts core claim from signature or merkle tree proof. If both proof persists core claim must be the same
368
+ *
369
+ * @public
370
+ * @param {W3CCredential} credential - credential to extract core claim
371
+ * @returns `{Promise<Claim>}`
372
+ */
373
+ getCoreClaimFromCredential(credential: W3CCredential): Promise<Claim>;
374
+
375
+ /**
376
+ *
377
+ * gets profile identity by genesis identifiers
378
+ *
379
+ * @param {DID} did - genesis identifier from which profile has been derived
380
+ * @returns `{Promise<Profile[]>}`
381
+ */
382
+ getProfilesByDID(did: DID): Promise<Profile[]>;
383
+
384
+ /**
385
+ *
386
+ * gets profile nonce by it's id. if profile is genesis identifier - 0 is returned
387
+ *
388
+ * @param {DID} did - profile that has been derived or genesis identity
389
+ * @returns `{Promise<{nonce:number, genesisIdentifier: DID}>}`
390
+ */
391
+ getGenesisDIDMetadata(did: DID): Promise<{ nonce: number | string; genesisDID: DID }>;
392
+
393
+ /**
394
+ *
395
+ * find all credentials that belong to any profile or genesis identity for the given did
396
+ *
397
+ * @param {DID} did - profile that has been derived or genesis identity
398
+ * @returns `{Promise<W3CCredential[]>}`
399
+ */
400
+ findOwnedCredentialsByDID(did: DID, query: ProofQuery): Promise<W3CCredential[]>;
401
+ /**
402
+ *
403
+ * gets profile identity by verifier
404
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
405
+ * @param {string} verifier - identifier of the verifier
406
+ * @returns `{Promise<Profile>}`
407
+ */
408
+ getProfileByVerifier(verifier: string): Promise<Profile | undefined>;
409
+
410
+ /**
411
+ * gets profile by verifiers
412
+ *
413
+ * @param {string} verifier - verifier to which profile has been shared
414
+ * @param {string} tags - optional, tags to filter profile entry
415
+ * @returns `{Promise<Profile[]>}`
416
+ */
417
+ getProfilesByVerifier(verifier: string, tags?: string[]): Promise<Profile[]>;
418
+
419
+ /**
420
+ *
421
+ * updates latest identity state in storage with given state or latest from the trees.
422
+ *
423
+ * @param {DID} issuerDID - identifier of the issuer
424
+ * @param {boolean} published - if states is published onchain
425
+ * @param {TreeState} treeState - contains state to upgrade
426
+ * @returns `{Promise<void>}`
427
+ */
428
+ updateIdentityState(issuerDID: DID, published: boolean, treeState?: TreeState): Promise<void>;
429
+
430
+ /**
431
+ *
432
+ * gets actual auth credential with proofs for provided tree state or latest from the trees.
433
+ *
434
+ * @param {DID} issuerDID - identifier of the issuer
435
+ * @param {TreeState} treeStateInfo - optional, state for retrieval
436
+ * @returns `{Promise<{
437
+ authCredential: W3CCredential;
438
+ incProof: MerkleTreeProofWithTreeState;
439
+ nonRevProof: MerkleTreeProofWithTreeState;
440
+ }>}`
441
+ */
442
+ getActualAuthCredential(
443
+ did: DID,
444
+ treeStateInfo?: TreeState
445
+ ): Promise<{
446
+ authCredential: W3CCredential;
447
+ incProof: MerkleTreeProofWithTreeState;
448
+ nonRevProof: MerkleTreeProofWithTreeState;
449
+ }>;
450
+
451
+ /**
452
+ * Transit state for the identity with the given DID
453
+ *
454
+ * @param {DID} did - identifier of the user
455
+ * @param {TreeState} oldTreeState - old state of the user
456
+ * @param {boolean} isOldStateGenesis - if the old state is genesis
457
+ * @param {IStateStorage} stateStorage - storage to save the new state
458
+ * @param {Signer} ethSigner - signer to sign the transaction
459
+ */
460
+ transitState(
461
+ did: DID,
462
+ oldTreeState: TreeState,
463
+ isOldStateGenesis: boolean,
464
+ ethSigner: Signer,
465
+ prover?: IZKProver
466
+ ): Promise<string>;
467
+
468
+ /**
469
+ * Add BJJ credential and transit state
470
+ *
471
+ * @param {DID} did - identifier of the user
472
+ * @param {TreeState} oldTreeState - old tree state of the user
473
+ * @param {boolean} isOldTreeState - if the old state is genesis
474
+ * @param {Signer} ethSigner - signer to sign the transaction
475
+ * @param {AuthBJJCredentialCreationOptions} opts - additional options
476
+ */
477
+ addBJJAuthCredential(
478
+ did: DID,
479
+ oldTreeState: TreeState,
480
+ isOldTreeStateGenesis: boolean,
481
+ ethSigner: Signer,
482
+ opts?: AuthBJJCredentialCreationOptions
483
+ ): Promise<W3CCredential>;
484
+ }
485
+
486
+ /**
487
+ * @public
488
+ * Wallet instance to manage the digital identity based on iden3 protocol
489
+ * allows to: create identity/profile, sign payloads (bigint / bytes), generate keys,
490
+ * generate Merkle tree proofs of inclusion / non-inclusion to Merkle trees, issue credentials with a BJJSignature and Iden3SparseMerkleTree Proofs,
491
+ * revoke credentials, add credentials to Merkle trees, push states to reverse hash service
492
+ *
493
+ *
494
+ * @class IdentityWallet - class
495
+ * @implements implements IIdentityWallet interface
496
+ */
497
+ export class IdentityWallet implements IIdentityWallet {
498
+ private readonly _credentialStatusPublisherRegistry: CredentialStatusPublisherRegistry;
499
+ private readonly _inputsGenerator: InputGenerator;
500
+ private readonly _transactionService: ITransactionService;
501
+
502
+ /**
503
+ * Constructs a new instance of the `IdentityWallet` class
504
+ *
505
+ * @param {KMS} _kms - Key Management System that allows signing data with BJJ key
506
+ * @param {IDataStorage} _storage - data storage to access credential / identity / Merkle tree data
507
+ * @param {ICredentialWallet} _credentialWallet - credential wallet instance to quickly access credential CRUD functionality
508
+ * @public
509
+ */
510
+ public constructor(
511
+ private readonly _kms: KMS,
512
+ private readonly _storage: IDataStorage,
513
+ private readonly _credentialWallet: ICredentialWallet,
514
+ private readonly _opts?: {
515
+ credentialStatusPublisherRegistry?: CredentialStatusPublisherRegistry;
516
+ }
517
+ ) {
518
+ this._credentialStatusPublisherRegistry = this.getCredentialStatusPublisherRegistry(_opts);
519
+ this._inputsGenerator = new InputGenerator(this, _credentialWallet, _storage.states);
520
+ this._transactionService = new TransactionService(_storage.states.getRpcProvider());
521
+ }
522
+
523
+ get credentialWallet(): ICredentialWallet {
524
+ return this._credentialWallet;
525
+ }
526
+
527
+ private getCredentialStatusPublisherRegistry(
528
+ _opts:
529
+ | { credentialStatusPublisherRegistry?: CredentialStatusPublisherRegistry | undefined }
530
+ | undefined
531
+ ): CredentialStatusPublisherRegistry {
532
+ if (!_opts?.credentialStatusPublisherRegistry) {
533
+ const registry = new CredentialStatusPublisherRegistry();
534
+ const emptyPublisher = { publish: () => Promise.resolve() };
535
+ registry.register(
536
+ CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
537
+ new Iden3SmtRhsCredentialStatusPublisher()
538
+ );
539
+ registry.register(CredentialStatusType.SparseMerkleTreeProof, emptyPublisher);
540
+ registry.register(CredentialStatusType.Iden3commRevocationStatusV1, emptyPublisher);
541
+ return registry;
542
+ } else {
543
+ return this._opts?.credentialStatusPublisherRegistry as CredentialStatusPublisherRegistry;
544
+ }
545
+ }
546
+
547
+ private async createAuthCoreClaim(
548
+ revNonce: number,
549
+ seed: Uint8Array
550
+ ): Promise<{ authClaim: Claim; pubKey: PublicKey }> {
551
+ const keyId = await this._kms.createKeyFromSeed(KmsKeyType.BabyJubJub, seed);
552
+ const pubKeyHex = await this._kms.publicKey(keyId);
553
+ const pubKey = PublicKey.newFromHex(pubKeyHex);
554
+
555
+ const schemaHash = SchemaHash.authSchemaHash;
556
+
557
+ const authClaim = Claim.newClaim(
558
+ schemaHash,
559
+ ClaimOptions.withIndexDataInts(pubKey.p[0], pubKey.p[1]),
560
+ ClaimOptions.withRevocationNonce(BigInt(0))
561
+ );
562
+ authClaim.setRevocationNonce(BigInt(revNonce));
563
+
564
+ return { authClaim, pubKey };
565
+ }
566
+
567
+ private async createAuthBJJCredential(
568
+ did: DID,
569
+ pubKey: PublicKey,
570
+ authClaim: Claim,
571
+ currentState: Hash,
572
+ revocationOpts: { id: string; type: CredentialStatusType }
573
+ ): Promise<W3CCredential> {
574
+ const authData = authClaim.getExpirationDate();
575
+ const expiration = authData ? getUnixTimestamp(authData) : 0;
576
+
577
+ const request: CredentialRequest = {
578
+ credentialSchema: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,
579
+ type: VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,
580
+ credentialSubject: {
581
+ x: pubKey.p[0].toString(),
582
+ y: pubKey.p[1].toString()
583
+ },
584
+ subjectPosition: subjectPositionIndex(authClaim.getIdPosition()),
585
+ version: 0,
586
+ expiration,
587
+ revocationOpts: {
588
+ nonce: Number(authClaim.getRevocationNonce()),
589
+ id: revocationOpts.id.replace(/\/$/, ''),
590
+ type: revocationOpts.type,
591
+ issuerState: currentState.hex()
592
+ }
593
+ };
594
+
595
+ // Check if has already an auth credential
596
+ const authCredentials = await this._credentialWallet.getAllAuthBJJCredentials(did);
597
+
598
+ let credential: W3CCredential = new W3CCredential();
599
+ if (authCredentials.length === 0) {
600
+ const schema = JSON.parse(VerifiableConstants.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);
601
+ try {
602
+ credential = this._credentialWallet.createCredential(did, request, schema);
603
+ } catch (e) {
604
+ throw new Error(`Error create w3c credential ${(e as Error).message}`);
605
+ }
606
+ } else {
607
+ // credential with sigProof signed with previous auth bjj credential
608
+ credential = await this.issueCredential(did, request);
609
+ }
610
+ return credential;
611
+ }
612
+
613
+ /**
614
+ * {@inheritDoc IIdentityWallet.createIdentity}
615
+ */
616
+ async createIdentity(
617
+ opts: IdentityCreationOptions
618
+ ): Promise<{ did: DID; credential: W3CCredential }> {
619
+ const tmpIdentifier = opts.seed ? uuid.v5(Hex.encode(sha256(opts.seed)), uuid.NIL) : uuid.v4();
620
+ opts.seed = opts.seed ?? getRandomBytes(32);
621
+
622
+ await this._storage.mt.createIdentityMerkleTrees(tmpIdentifier);
623
+
624
+ const revNonce = opts.revocationOpts.nonce ?? 0;
625
+
626
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(revNonce, opts.seed);
627
+
628
+ const { hi, hv } = authClaim.hiHv();
629
+ await this._storage.mt.addToMerkleTree(tmpIdentifier, MerkleTreeType.Claims, hi, hv);
630
+
631
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
632
+ tmpIdentifier,
633
+ MerkleTreeType.Claims
634
+ );
635
+
636
+ const ctr = await claimsTree.root();
637
+
638
+ const currentState = hashElems([ctr.bigInt(), ZERO_HASH.bigInt(), ZERO_HASH.bigInt()]);
639
+
640
+ const didType = buildDIDType(
641
+ opts.method || DidMethod.Iden3,
642
+ opts.blockchain || Blockchain.Polygon,
643
+ opts.networkId || NetworkId.Amoy
644
+ );
645
+ const identifier = Id.idGenesisFromIdenState(didType, currentState.bigInt());
646
+ const did = DID.parseFromId(identifier);
647
+
648
+ await this._storage.mt.bindMerkleTreeToNewIdentifier(tmpIdentifier, did.string());
649
+
650
+ const oldTreeState = {
651
+ revocationRoot: ZERO_HASH,
652
+ claimsRoot: ctr,
653
+ state: currentState,
654
+ rootOfRoots: ZERO_HASH
655
+ };
656
+
657
+ const identity = await this._storage.identity.getIdentity(did.string());
658
+ if (!identity) {
659
+ await this._storage.identity.saveIdentity({
660
+ did: did.string(),
661
+ state: currentState,
662
+ isStatePublished: false,
663
+ isStateGenesis: true
664
+ });
665
+ }
666
+
667
+ // check whether we have auth credential, if not - create a new one
668
+ const credentials = await this._credentialWallet.findByQuery({
669
+ credentialSubject: {
670
+ x: {
671
+ $eq: pubKey.p[0].toString()
672
+ },
673
+ y: {
674
+ $eq: pubKey.p[1].toString()
675
+ }
676
+ },
677
+ allowedIssuers: [did.string()]
678
+ });
679
+
680
+ // if credential exists with the same credential status type we return this credential
681
+ if (
682
+ credentials.length === 1 &&
683
+ credentials[0].credentialStatus.type === opts.revocationOpts.type
684
+ ) {
685
+ return {
686
+ did,
687
+ credential: credentials[0]
688
+ };
689
+ }
690
+
691
+ // otherwise something is already wrong with storage as it has more than 1 credential in it or credential status type of existing credential is different from what user provides - We should remove everything and create new credential.
692
+ // in this way credential status of auth credential can be upgraded
693
+ for (let i = 0; i < credentials.length; i++) {
694
+ await this._credentialWallet.remove(credentials[i].id);
695
+ }
696
+
697
+ // otherwise we create a new credential
698
+ const credential = await this.createAuthBJJCredential(
699
+ did,
700
+ pubKey,
701
+ authClaim,
702
+ currentState,
703
+ opts.revocationOpts
704
+ );
705
+
706
+ const index = authClaim.hIndex();
707
+ const { proof } = await claimsTree.generateProof(index, ctr);
708
+
709
+ const mtpProof: Iden3SparseMerkleTreeProof = new Iden3SparseMerkleTreeProof({
710
+ mtp: proof,
711
+ issuerData: {
712
+ id: did,
713
+ state: {
714
+ rootOfRoots: oldTreeState.rootOfRoots,
715
+ revocationTreeRoot: oldTreeState.revocationRoot,
716
+ claimsTreeRoot: ctr,
717
+ value: currentState
718
+ }
719
+ },
720
+ coreClaim: authClaim
721
+ });
722
+
723
+ credential.proof = [mtpProof];
724
+
725
+ // only if user specified that genesis state publishing is not needed we won't do this.
726
+ if (!opts.revocationOpts.genesisPublishingDisabled) {
727
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
728
+ rhsUrl: opts.revocationOpts.id,
729
+ onChain: opts.revocationOpts.onChain
730
+ });
731
+ }
732
+
733
+ await this._credentialWallet.save(credential);
734
+
735
+ return {
736
+ did,
737
+ credential
738
+ };
739
+ }
740
+
741
+ /**
742
+ * {@inheritDoc IIdentityWallet.createEthereumBasedIdentity}
743
+ */
744
+ async createEthereumBasedIdentity(
745
+ opts: EthereumBasedIdentityCreationOptions
746
+ ): Promise<{ did: DID; credential: W3CCredential | undefined }> {
747
+ opts.seed = opts.seed ?? getRandomBytes(32);
748
+ opts.createBjjCredential = opts.createBjjCredential ?? true;
749
+
750
+ let credential;
751
+ const ethSigner = opts.ethSigner;
752
+
753
+ if (opts.createBjjCredential && !ethSigner) {
754
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);
755
+ }
756
+
757
+ const currentState = ZERO_HASH; // In Ethereum identities we don't have an initial state with the auth credential
758
+
759
+ const didType = buildDIDType(
760
+ opts.method || DidMethod.Iden3,
761
+ opts.blockchain || Blockchain.Polygon,
762
+ opts.networkId || NetworkId.Amoy
763
+ );
764
+
765
+ const keyIdEth = await this._kms.createKeyFromSeed(KmsKeyType.Secp256k1, opts.seed);
766
+ const pubKeyHexEth = (await this._kms.publicKey(keyIdEth)).slice(2); // 04 + x + y (uncompressed key)
767
+ const did = buildDIDFromEthPubKey(didType, pubKeyHexEth);
768
+
769
+ await this._storage.mt.createIdentityMerkleTrees(did.string());
770
+
771
+ await this._storage.identity.saveIdentity({
772
+ did: did.string(),
773
+ state: currentState,
774
+ isStatePublished: false,
775
+ isStateGenesis: true
776
+ });
777
+
778
+ if (opts.createBjjCredential && ethSigner) {
779
+ // Old tree state genesis state
780
+ const oldTreeState: TreeState = {
781
+ revocationRoot: ZERO_HASH,
782
+ claimsRoot: ZERO_HASH,
783
+ state: currentState,
784
+ rootOfRoots: ZERO_HASH
785
+ };
786
+
787
+ credential = await this.addBJJAuthCredential(did, oldTreeState, true, ethSigner, opts);
788
+ }
789
+
790
+ return {
791
+ did,
792
+ credential
793
+ };
794
+ }
795
+
796
+ /** {@inheritDoc IIdentityWallet.getGenesisDIDMetadata} */
797
+ async getGenesisDIDMetadata(did: DID): Promise<{ nonce: number | string; genesisDID: DID }> {
798
+ // check if it is a genesis identity
799
+ const identity = await this._storage.identity.getIdentity(did.string());
800
+
801
+ if (identity) {
802
+ return { nonce: 0, genesisDID: DID.parse(identity.did) };
803
+ }
804
+ const profile = await this._storage.identity.getProfileById(did.string());
805
+
806
+ if (!profile) {
807
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);
808
+ }
809
+ return { nonce: profile.nonce, genesisDID: DID.parse(profile.genesisIdentifier) };
810
+ }
811
+
812
+ /** {@inheritDoc IIdentityWallet.createProfile} */
813
+ async createProfile(
814
+ did: DID,
815
+ nonce: number | string,
816
+ verifier: string,
817
+ tags?: string[]
818
+ ): Promise<DID> {
819
+ const profileDID = generateProfileDID(did, nonce);
820
+
821
+ const identityProfiles = await this._storage.identity.getProfilesByGenesisIdentifier(
822
+ did.string()
823
+ );
824
+
825
+ const profilesForTagAndVerifier = await this._storage.identity.getProfilesByVerifier(
826
+ verifier,
827
+ tags
828
+ );
829
+ if (profilesForTagAndVerifier.length) {
830
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);
831
+ }
832
+
833
+ const existingProfileWithNonce = identityProfiles.find((p) => p.nonce == nonce);
834
+ if (existingProfileWithNonce) {
835
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);
836
+ }
837
+
838
+ await this._storage.identity.saveProfile({
839
+ id: profileDID.string(),
840
+ nonce,
841
+ genesisIdentifier: did.string(),
842
+ verifier,
843
+ tags
844
+ });
845
+
846
+ return profileDID;
847
+ }
848
+
849
+ /**
850
+ *
851
+ * gets profile identity by genesis identifiers
852
+ *
853
+ * @param {string} genesisIdentifier - genesis identifier from which profile has been derived
854
+ * @returns `{Promise<Profile[]>}`
855
+ */
856
+ async getProfilesByDID(did: DID): Promise<Profile[]> {
857
+ return this._storage.identity.getProfilesByGenesisIdentifier(did.string());
858
+ }
859
+ /** {@inheritDoc IIdentityWallet.generateKey} */
860
+ async generateKey(keyType: KmsKeyType): Promise<KmsKeyId> {
861
+ const key = await this._kms.createKeyFromSeed(keyType, getRandomBytes(32));
862
+ return key;
863
+ }
864
+ /**
865
+ * @deprecated The method should not be used. It returns only one profile per verifier, which can potentially restrict business use cases
866
+ * {@inheritDoc IIdentityWallet.getProfileByVerifier}
867
+ */
868
+ async getProfileByVerifier(verifier: string): Promise<Profile | undefined> {
869
+ return this._storage.identity.getProfileByVerifier(verifier);
870
+ }
871
+
872
+ /** {@inheritDoc IIdentityWallet.getProfilesByVerifier} */
873
+ async getProfilesByVerifier(verifier: string, tags?: string[]): Promise<Profile[]> {
874
+ return this._storage.identity.getProfilesByVerifier(verifier, tags);
875
+ }
876
+
877
+ /** {@inheritDoc IIdentityWallet.getDIDTreeModel} */
878
+ async getDIDTreeModel(did: DID): Promise<TreesModel> {
879
+ const didStr = did.string();
880
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
881
+ didStr,
882
+ MerkleTreeType.Claims
883
+ );
884
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
885
+ didStr,
886
+ MerkleTreeType.Revocations
887
+ );
888
+ const rootsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
889
+ didStr,
890
+ MerkleTreeType.Roots
891
+ );
892
+ const state = hashElems([
893
+ (await claimsTree.root()).bigInt(),
894
+ (await revocationTree.root()).bigInt(),
895
+ (await rootsTree.root()).bigInt()
896
+ ]);
897
+
898
+ return {
899
+ state,
900
+ claimsTree,
901
+ revocationTree,
902
+ rootsTree
903
+ };
904
+ }
905
+
906
+ /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
907
+ async generateCredentialMtp(
908
+ did: DID,
909
+ credential: W3CCredential,
910
+ treeState?: TreeState
911
+ ): Promise<MerkleTreeProofWithTreeState> {
912
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
913
+ return this.generateCoreClaimMtp(did, coreClaim, treeState);
914
+ }
915
+
916
+ /** {@inheritDoc IIdentityWallet.generateClaimMtp} */
917
+ async generateCoreClaimMtp(
918
+ did: DID,
919
+ coreClaim: Claim,
920
+ treeState?: TreeState
921
+ ): Promise<MerkleTreeProofWithTreeState> {
922
+ const treesModel = await this.getDIDTreeModel(did);
923
+
924
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
925
+ did.string(),
926
+ MerkleTreeType.Claims
927
+ );
928
+
929
+ const claimsRoot = await treesModel.claimsTree.root();
930
+ const rootOfRoots = await treesModel.rootsTree.root();
931
+ const revocationRoot = await treesModel.revocationTree.root();
932
+ const { proof } = await claimsTree.generateProof(
933
+ coreClaim.hIndex(),
934
+ treeState ? treeState.claimsRoot : claimsRoot
935
+ );
936
+
937
+ return {
938
+ proof,
939
+ treeState: treeState ?? {
940
+ state: treesModel.state,
941
+ claimsRoot,
942
+ rootOfRoots,
943
+ revocationRoot
944
+ }
945
+ };
946
+ }
947
+
948
+ /** {@inheritDoc IIdentityWallet.generateNonRevocationMtp} */
949
+ async generateNonRevocationMtp(
950
+ did: DID,
951
+ credential: W3CCredential,
952
+ treeState?: TreeState
953
+ ): Promise<MerkleTreeProofWithTreeState> {
954
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
955
+
956
+ const revNonce = coreClaim.getRevocationNonce();
957
+ return this.generateNonRevocationMtpWithNonce(did, revNonce, treeState);
958
+ }
959
+
960
+ /** {@inheritDoc IIdentityWallet.generateNonRevocationMtpWithNonce} */
961
+ async generateNonRevocationMtpWithNonce(
962
+ did: DID,
963
+ revNonce: bigint,
964
+ treeState?: TreeState
965
+ ): Promise<MerkleTreeProofWithTreeState> {
966
+ const treesModel = await this.getDIDTreeModel(did);
967
+
968
+ const revocationTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
969
+ did.string(),
970
+ MerkleTreeType.Revocations
971
+ );
972
+
973
+ const claimsRoot = await treesModel.claimsTree.root();
974
+ const rootOfRoots = await treesModel.rootsTree.root();
975
+ const revocationRoot = await treesModel.revocationTree.root();
976
+ const { proof } = await revocationTree.generateProof(
977
+ revNonce,
978
+ treeState ? treeState.revocationRoot : revocationRoot
979
+ );
980
+
981
+ return {
982
+ proof,
983
+ treeState: treeState ?? {
984
+ state: treesModel.state,
985
+ claimsRoot,
986
+ rootOfRoots,
987
+ revocationRoot
988
+ }
989
+ };
990
+ }
991
+
992
+ /** {@inheritDoc IIdentityWallet.sign} */
993
+ async sign(message: Uint8Array, credential: W3CCredential): Promise<Signature> {
994
+ const keyKMSId = getKMSIdByAuthCredential(credential);
995
+ const payload = poseidon.hashBytes(message);
996
+
997
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(payload));
998
+
999
+ return Signature.newFromCompressed(signature);
1000
+ }
1001
+
1002
+ /** {@inheritDoc IIdentityWallet.signChallenge} */
1003
+ async signChallenge(challenge: bigint, credential: W3CCredential): Promise<Signature> {
1004
+ const keyKMSId = getKMSIdByAuthCredential(credential);
1005
+
1006
+ const signature = await this._kms.sign(keyKMSId, BytesHelper.intToBytes(challenge));
1007
+
1008
+ return Signature.newFromCompressed(signature);
1009
+ }
1010
+
1011
+ /** {@inheritDoc IIdentityWallet.issueCredential} */
1012
+ async issueCredential(
1013
+ issuerDID: DID,
1014
+ req: CredentialRequest,
1015
+ opts?: Options
1016
+ ): Promise<W3CCredential> {
1017
+ req.revocationOpts.id = req.revocationOpts.id.replace(/\/$/, '');
1018
+
1019
+ let schema: object;
1020
+
1021
+ const loader = opts?.documentLoader ?? cacheLoader(opts);
1022
+ try {
1023
+ schema = (await loader(req.credentialSchema)).document;
1024
+ } catch (e) {
1025
+ throw new Error(`can't load credential schema ${req.credentialSchema}`);
1026
+ }
1027
+
1028
+ const jsonSchema = schema as JSONSchema;
1029
+ let credential: W3CCredential = new W3CCredential();
1030
+
1031
+ const issuerRoots = await this.getDIDTreeModel(issuerDID);
1032
+ req.revocationOpts.issuerState = issuerRoots.state.hex();
1033
+
1034
+ req.revocationOpts.nonce =
1035
+ typeof req.revocationOpts.nonce === 'number'
1036
+ ? req.revocationOpts.nonce
1037
+ : new DataView(getRandomBytes(16).buffer).getUint32(0, false);
1038
+
1039
+ req.subjectPosition = req.subjectPosition ?? SubjectPosition.Index;
1040
+
1041
+ try {
1042
+ credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
1043
+
1044
+ const encodedCred = byteEncoder.encode(JSON.stringify(credential));
1045
+ const encodedSchema = byteEncoder.encode(JSON.stringify(schema));
1046
+
1047
+ await new JsonSchemaValidator().validate(encodedCred, encodedSchema);
1048
+ } catch (e) {
1049
+ throw new Error(`Error create w3c credential ${(e as Error).message}`);
1050
+ }
1051
+
1052
+ const { authCredential: issuerAuthBJJCredential } = await this.getActualAuthCredential(
1053
+ issuerDID
1054
+ );
1055
+
1056
+ const coreClaimOpts: CoreClaimCreationOptions = {
1057
+ revNonce: req.revocationOpts.nonce,
1058
+ subjectPosition: req.subjectPosition,
1059
+ merklizedRootPosition: req.merklizedRootPosition ?? MerklizedRootPosition.None,
1060
+ updatable: false,
1061
+ version: 0,
1062
+ merklizeOpts: { ...opts, documentLoader: loader }
1063
+ };
1064
+
1065
+ const coreClaim = await credential.toCoreClaim(coreClaimOpts);
1066
+
1067
+ const { hi, hv } = coreClaim.hiHv();
1068
+
1069
+ const coreClaimHash = poseidon.hash([hi, hv]);
1070
+
1071
+ const signature = await this.signChallenge(coreClaimHash, issuerAuthBJJCredential);
1072
+
1073
+ if (!issuerAuthBJJCredential.proof) {
1074
+ throw new Error(
1075
+ VerifiableConstants.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF
1076
+ );
1077
+ }
1078
+
1079
+ const mtpAuthBJJProof = issuerAuthBJJCredential.getIden3SparseMerkleTreeProof();
1080
+ if (!mtpAuthBJJProof) {
1081
+ throw new Error(
1082
+ VerifiableConstants.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF
1083
+ );
1084
+ }
1085
+
1086
+ const sigProof = new BJJSignatureProof2021({
1087
+ issuerData: {
1088
+ id: issuerDID,
1089
+ state: mtpAuthBJJProof.issuerData.state,
1090
+ authCoreClaim: mtpAuthBJJProof.coreClaim,
1091
+ mtp: mtpAuthBJJProof.mtp,
1092
+ credentialStatus: issuerAuthBJJCredential.credentialStatus
1093
+ },
1094
+ coreClaim,
1095
+ signature
1096
+ });
1097
+ credential.proof = [sigProof];
1098
+
1099
+ return credential;
1100
+ }
1101
+
1102
+ /** {@inheritDoc IIdentityWallet.getActualAuthCredential} */
1103
+ async getActualAuthCredential(
1104
+ did: DID,
1105
+ treeStateInfo?: TreeState
1106
+ ): Promise<{
1107
+ authCredential: W3CCredential;
1108
+ incProof: MerkleTreeProofWithTreeState;
1109
+ nonRevProof: MerkleTreeProofWithTreeState;
1110
+ }> {
1111
+ const authCredentials = await this._credentialWallet.getAllAuthBJJCredentials(did);
1112
+ for (let i = 0; i < authCredentials.length; i++) {
1113
+ const incProof = await this.generateCredentialMtp(did, authCredentials[i], treeStateInfo);
1114
+
1115
+ if (!incProof.proof.existence) {
1116
+ continue;
1117
+ }
1118
+
1119
+ const nonRevProof = await this.generateNonRevocationMtp(
1120
+ did,
1121
+ authCredentials[i],
1122
+ treeStateInfo
1123
+ );
1124
+
1125
+ if (!nonRevProof.proof.existence) {
1126
+ return {
1127
+ authCredential: authCredentials[i],
1128
+ incProof,
1129
+ nonRevProof
1130
+ };
1131
+ }
1132
+ }
1133
+
1134
+ throw new Error(VerifiableConstants.ERRORS.NO_AUTH_CRED_FOUND);
1135
+ }
1136
+
1137
+ /** {@inheritDoc IIdentityWallet.revokeCredential} */
1138
+ async revokeCredential(issuerDID: DID, credential: W3CCredential): Promise<number> {
1139
+ const issuerTree = await this.getDIDTreeModel(issuerDID);
1140
+
1141
+ const coreClaim = await this.getCoreClaimFromCredential(credential);
1142
+
1143
+ if (!coreClaim) {
1144
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);
1145
+ }
1146
+ const nonce = coreClaim.getRevocationNonce();
1147
+
1148
+ await issuerTree.revocationTree.add(nonce, BigInt(0));
1149
+
1150
+ return Number(BigInt.asUintN(64, nonce));
1151
+ }
1152
+
1153
+ /** {@inheritDoc IIdentityWallet.addCredentialsToMerkleTree} */
1154
+ async addCredentialsToMerkleTree(
1155
+ credentials: W3CCredential[],
1156
+ issuerDID: DID
1157
+ ): Promise<Iden3ProofCreationResult> {
1158
+ const oldIssuerTree = await this.getDIDTreeModel(issuerDID);
1159
+ let claimsRoot = await oldIssuerTree.claimsTree.root();
1160
+ let rootOfRoots = await oldIssuerTree.rootsTree.root();
1161
+ let revocationRoot = await oldIssuerTree.revocationTree.root();
1162
+ const oldTreeState: TreeState = {
1163
+ state: oldIssuerTree.state,
1164
+ claimsRoot,
1165
+ revocationRoot,
1166
+ rootOfRoots
1167
+ };
1168
+
1169
+ for (let index = 0; index < credentials.length; index++) {
1170
+ const credential = credentials[index];
1171
+
1172
+ // credential must have a bjj signature proof
1173
+ const coreClaim = credential.getCoreClaimFromProof(ProofType.BJJSignature);
1174
+
1175
+ if (!coreClaim) {
1176
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);
1177
+ }
1178
+
1179
+ await this._storage.mt.addToMerkleTree(
1180
+ issuerDID.string(),
1181
+ MerkleTreeType.Claims,
1182
+ coreClaim.hIndex(),
1183
+ coreClaim.hValue()
1184
+ );
1185
+ }
1186
+
1187
+ const newIssuerTreeState = await this.getDIDTreeModel(issuerDID);
1188
+ const claimTreeRoot = await newIssuerTreeState.claimsTree.root();
1189
+ await this._storage.mt.addToMerkleTree(
1190
+ issuerDID.string(),
1191
+ MerkleTreeType.Roots,
1192
+ claimTreeRoot.bigInt(),
1193
+ BigInt(0)
1194
+ );
1195
+ const newIssuerTreeStateWithROR = await this.getDIDTreeModel(issuerDID);
1196
+
1197
+ claimsRoot = await newIssuerTreeStateWithROR.claimsTree.root();
1198
+ rootOfRoots = await newIssuerTreeStateWithROR.rootsTree.root();
1199
+ revocationRoot = await newIssuerTreeStateWithROR.revocationTree.root();
1200
+ return {
1201
+ credentials,
1202
+ newTreeState: {
1203
+ state: newIssuerTreeStateWithROR.state,
1204
+ claimsRoot,
1205
+ rootOfRoots,
1206
+ revocationRoot
1207
+ },
1208
+ oldTreeState: oldTreeState
1209
+ };
1210
+ }
1211
+
1212
+ /** {@inheritDoc IIdentityWallet.generateIden3SparseMerkleTreeProof} */
1213
+ // treeState - optional, if it is not passed proof of claim inclusion will be generated on the latest state in the tree.
1214
+ async generateIden3SparseMerkleTreeProof(
1215
+ issuerDID: DID,
1216
+ credentials: W3CCredential[],
1217
+ txId: string,
1218
+ blockNumber?: number,
1219
+ blockTimestamp?: number,
1220
+ treeState?: TreeState,
1221
+ opts?: CoreClaimCreationOptions
1222
+ ): Promise<W3CCredential[]> {
1223
+ for (let index = 0; index < credentials.length; index++) {
1224
+ const credential = credentials[index];
1225
+
1226
+ // TODO: return coreClaim from generateCredentialMtp and use it below
1227
+ // credential must have a bjj signature proof
1228
+
1229
+ const coreClaim =
1230
+ credential.getCoreClaimFromProof(ProofType.BJJSignature) ||
1231
+ (await credential.toCoreClaim(opts));
1232
+
1233
+ if (!coreClaim) {
1234
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);
1235
+ }
1236
+ const mtpWithProof = await this.generateCoreClaimMtp(issuerDID, coreClaim, treeState);
1237
+
1238
+ const mtpProof: Iden3SparseMerkleTreeProof = new Iden3SparseMerkleTreeProof({
1239
+ mtp: mtpWithProof.proof,
1240
+ issuerData: {
1241
+ id: issuerDID,
1242
+ state: {
1243
+ claimsTreeRoot: mtpWithProof.treeState.claimsRoot,
1244
+ revocationTreeRoot: mtpWithProof.treeState.revocationRoot,
1245
+ rootOfRoots: mtpWithProof.treeState.rootOfRoots,
1246
+ value: mtpWithProof.treeState.state,
1247
+ txId,
1248
+ blockNumber,
1249
+ blockTimestamp
1250
+ }
1251
+ },
1252
+ coreClaim
1253
+ });
1254
+
1255
+ if (Array.isArray(credentials[index].proof)) {
1256
+ (credentials[index].proof as unknown[]).push(mtpProof);
1257
+ } else {
1258
+ credentials[index].proof = credentials[index].proof
1259
+ ? [credentials[index].proof, mtpProof]
1260
+ : [mtpProof];
1261
+ }
1262
+ }
1263
+ return credentials;
1264
+ }
1265
+
1266
+ /** {@inheritDoc IIdentityWallet.publishSpecificStateToRHS} */
1267
+ async publishSpecificStateToRHS(
1268
+ treeModel: TreesModel,
1269
+ rhsURL: string,
1270
+ revokedNonces?: number[]
1271
+ ): Promise<void> {
1272
+ await pushHashesToRHS(treeModel.state, treeModel, rhsURL, revokedNonces);
1273
+ }
1274
+
1275
+ /** {@inheritDoc IIdentityWallet.publishStateToRHS} */
1276
+ async publishStateToRHS(issuerDID: DID, rhsURL: string, revokedNonces?: number[]): Promise<void> {
1277
+ const treeState = await this.getDIDTreeModel(issuerDID);
1278
+ await pushHashesToRHS(
1279
+ treeState.state,
1280
+ {
1281
+ revocationTree: treeState.revocationTree,
1282
+ claimsTree: treeState.claimsTree,
1283
+ state: treeState.state,
1284
+ rootsTree: treeState.rootsTree
1285
+ },
1286
+ rhsURL,
1287
+ revokedNonces
1288
+ );
1289
+ }
1290
+
1291
+ /** {@inheritDoc IIdentityWallet.publishRevocationInfoByCredentialStatusType} */
1292
+ async publishRevocationInfoByCredentialStatusType(
1293
+ issuerDID: DID,
1294
+ credentialStatusType: CredentialStatusType,
1295
+ opts?: RevocationInfoOptions
1296
+ ): Promise<void> {
1297
+ const rhsPublishers = this._credentialStatusPublisherRegistry.get(credentialStatusType);
1298
+ if (!rhsPublishers) {
1299
+ throw new Error(
1300
+ `there is no registered publisher to save hash is not registered for ${credentialStatusType} is not registered`
1301
+ );
1302
+ }
1303
+
1304
+ let nodes: ProofNode[] = [];
1305
+
1306
+ const tree = opts?.treeModel ?? (await this.getDIDTreeModel(issuerDID));
1307
+ nodes = await getNodesRepresentation(
1308
+ opts?.revokedNonces ?? [],
1309
+ {
1310
+ revocationTree: tree.revocationTree,
1311
+ claimsTree: tree.claimsTree,
1312
+ state: tree.state,
1313
+ rootsTree: tree.rootsTree
1314
+ },
1315
+ tree.state
1316
+ );
1317
+
1318
+ if (!nodes.length) {
1319
+ return;
1320
+ }
1321
+
1322
+ const rhsPublishersTask = rhsPublishers.map((publisher) =>
1323
+ publisher.publish({ nodes, ...opts, credentialStatusType, issuerDID })
1324
+ );
1325
+
1326
+ await Promise.all(rhsPublishersTask);
1327
+ }
1328
+
1329
+ public async getCoreClaimFromCredential(credential: W3CCredential): Promise<Claim> {
1330
+ const coreClaimFromSigProof = credential.getCoreClaimFromProof(ProofType.BJJSignature);
1331
+
1332
+ const coreClaimFromMtpProof = credential.getCoreClaimFromProof(
1333
+ ProofType.Iden3SparseMerkleTreeProof
1334
+ );
1335
+
1336
+ if (
1337
+ coreClaimFromMtpProof &&
1338
+ coreClaimFromSigProof &&
1339
+ coreClaimFromMtpProof.hex() !== coreClaimFromSigProof.hex()
1340
+ ) {
1341
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);
1342
+ }
1343
+ if (!coreClaimFromMtpProof && !coreClaimFromSigProof) {
1344
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);
1345
+ }
1346
+
1347
+ //eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1348
+ const coreClaim = coreClaimFromMtpProof ?? coreClaimFromSigProof!;
1349
+
1350
+ return coreClaim;
1351
+ }
1352
+
1353
+ async findOwnedCredentialsByDID(did: DID, query: ProofQuery): Promise<W3CCredential[]> {
1354
+ const credentials = await this._credentialWallet.findByQuery(query);
1355
+ if (!credentials.length) {
1356
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);
1357
+ }
1358
+
1359
+ const { genesisDID } = await this.getGenesisDIDMetadata(did);
1360
+
1361
+ const profiles = await this.getProfilesByDID(genesisDID);
1362
+
1363
+ return credentials.filter((cred) => {
1364
+ const credentialSubjectId = cred.credentialSubject['id'] as string; // credential subject
1365
+ return (
1366
+ credentialSubjectId == genesisDID.string() ||
1367
+ profiles.some((p) => {
1368
+ return p.id === credentialSubjectId;
1369
+ })
1370
+ );
1371
+ });
1372
+ }
1373
+
1374
+ /** {@inheritDoc IIdentityWallet.updateIdentityState} */
1375
+ async updateIdentityState(
1376
+ issuerDID: DID,
1377
+ published: boolean,
1378
+ treeState?: TreeState
1379
+ ): Promise<void> {
1380
+ const latestTreeState = await this.getDIDTreeModel(issuerDID);
1381
+
1382
+ await this._storage.identity.saveIdentity({
1383
+ did: issuerDID.string(),
1384
+ state: treeState?.state ?? latestTreeState.state,
1385
+ isStatePublished: published,
1386
+ isStateGenesis: false
1387
+ });
1388
+ }
1389
+
1390
+ /** {@inheritdoc IIdentityWallet.transitState} */
1391
+ async transitState(
1392
+ did: DID,
1393
+ oldTreeState: TreeState,
1394
+ isOldStateGenesis: boolean,
1395
+ ethSigner: Signer,
1396
+ prover?: IZKProver
1397
+ ): Promise<string> {
1398
+ const newTreeModel = await this.getDIDTreeModel(did);
1399
+ const claimsRoot = await newTreeModel.claimsTree.root();
1400
+ const rootOfRoots = await newTreeModel.rootsTree.root();
1401
+ const revocationRoot = await newTreeModel.revocationTree.root();
1402
+
1403
+ const newTreeState: TreeState = {
1404
+ revocationRoot,
1405
+ claimsRoot,
1406
+ state: newTreeModel.state,
1407
+ rootOfRoots
1408
+ };
1409
+
1410
+ const userId = DID.idFromDID(did);
1411
+
1412
+ let proof;
1413
+ const isEthIdentity = isEthereumIdentity(did); // don't generate proof for ethereum identities
1414
+
1415
+ let txId;
1416
+ if (!isEthIdentity) {
1417
+ if (!prover) {
1418
+ throw new Error(VerifiableConstants.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);
1419
+ }
1420
+ // generate the proof
1421
+ const authInfo = await this._inputsGenerator.prepareAuthBJJCredential(did, oldTreeState);
1422
+ const challenge = Poseidon.hash([oldTreeState.state.bigInt(), newTreeState.state.bigInt()]);
1423
+
1424
+ const signature = await this.signChallenge(challenge, authInfo.credential);
1425
+
1426
+ const circuitInputs = new StateTransitionInputs();
1427
+ circuitInputs.id = userId;
1428
+
1429
+ circuitInputs.signature = signature;
1430
+ circuitInputs.isOldStateGenesis = isOldStateGenesis;
1431
+
1432
+ const authClaimIncProofNewState = await this.generateCredentialMtp(
1433
+ did,
1434
+ authInfo.credential,
1435
+ newTreeState
1436
+ );
1437
+
1438
+ circuitInputs.newTreeState = authClaimIncProofNewState.treeState;
1439
+ circuitInputs.authClaimNewStateIncProof = authClaimIncProofNewState.proof;
1440
+
1441
+ circuitInputs.oldTreeState = oldTreeState;
1442
+ circuitInputs.authClaim = {
1443
+ claim: authInfo.coreClaim,
1444
+ incProof: authInfo.incProof,
1445
+ nonRevProof: authInfo.nonRevProof
1446
+ };
1447
+
1448
+ const inputs = circuitInputs.inputsMarshal();
1449
+
1450
+ proof = await prover.generate(inputs, CircuitId.StateTransition);
1451
+
1452
+ txId = await this._storage.states.publishState(proof, ethSigner);
1453
+ } else {
1454
+ const oldUserState = oldTreeState.state;
1455
+ const newUserState = newTreeState.state;
1456
+ const userStateTransitionInfo: UserStateTransitionInfo = {
1457
+ userId,
1458
+ oldUserState,
1459
+ newUserState,
1460
+ isOldStateGenesis,
1461
+ methodId: BigInt(1),
1462
+ methodParams: '0x'
1463
+ } as UserStateTransitionInfo;
1464
+ txId = await this._storage.states.publishStateGeneric(ethSigner, userStateTransitionInfo);
1465
+ }
1466
+ await this.updateIdentityState(did, true, newTreeState);
1467
+
1468
+ return txId;
1469
+ }
1470
+
1471
+ private async getAuthBJJCredential(
1472
+ did: DID,
1473
+ oldTreeState: TreeState,
1474
+ {
1475
+ nonce,
1476
+ seed,
1477
+ id,
1478
+ type
1479
+ }: { nonce: number; seed: Uint8Array; id: string; type: CredentialStatusType }
1480
+ ): Promise<W3CCredential> {
1481
+ const { authClaim, pubKey } = await this.createAuthCoreClaim(nonce, seed);
1482
+
1483
+ const { hi, hv } = authClaim.hiHv();
1484
+ await this._storage.mt.addToMerkleTree(did.string(), MerkleTreeType.Claims, hi, hv);
1485
+
1486
+ // Calculate current state after adding credential to merkle tree
1487
+ const claimsTree = await this._storage.mt.getMerkleTreeByIdentifierAndType(
1488
+ did.string(),
1489
+ MerkleTreeType.Claims
1490
+ );
1491
+ const currentState = hashElems([
1492
+ (await claimsTree.root()).bigInt(),
1493
+ oldTreeState.revocationRoot.bigInt(),
1494
+ oldTreeState.rootOfRoots.bigInt()
1495
+ ]);
1496
+
1497
+ return this.createAuthBJJCredential(did, pubKey, authClaim, currentState, {
1498
+ id,
1499
+ type
1500
+ });
1501
+ }
1502
+
1503
+ /** {@inheritdoc IIdentityWallet.addBJJAuthCredential} */
1504
+ async addBJJAuthCredential(
1505
+ did: DID,
1506
+ oldTreeState: TreeState,
1507
+ isOldStateGenesis: boolean,
1508
+ ethSigner: Signer,
1509
+ opts: AuthBJJCredentialCreationOptions,
1510
+ prover?: IZKProver // it will be needed in case of non ethereum identities
1511
+ ): Promise<W3CCredential> {
1512
+ opts.seed = opts.seed ?? getRandomBytes(32);
1513
+ opts.revocationOpts.nonce =
1514
+ opts.revocationOpts.nonce ??
1515
+ (isOldStateGenesis
1516
+ ? 0
1517
+ : opts.revocationOpts.nonce ?? new DataView(getRandomBytes(12).buffer).getUint32(0));
1518
+
1519
+ const credential = await this.getAuthBJJCredential(did, oldTreeState, {
1520
+ nonce: opts.revocationOpts.nonce,
1521
+ seed: opts.seed,
1522
+ id: opts.revocationOpts.id,
1523
+ type: opts.revocationOpts.type
1524
+ });
1525
+
1526
+ const addMtpToCredAndPublishRevState = async () => {
1527
+ const { receipt, block } = await this._transactionService.getTransactionReceiptAndBlock(txId);
1528
+ const credsWithIden3MTPProof = await this.generateIden3SparseMerkleTreeProof(
1529
+ did,
1530
+ [credential],
1531
+ txId,
1532
+ receipt?.blockNumber,
1533
+ block?.timestamp,
1534
+ undefined,
1535
+ {
1536
+ revNonce: opts.revocationOpts.nonce ?? 0,
1537
+ subjectPosition: SubjectPosition.None,
1538
+ merklizedRootPosition: MerklizedRootPosition.None,
1539
+ updatable: false,
1540
+ version: 0,
1541
+ merklizeOpts: { documentLoader: cacheLoader() }
1542
+ }
1543
+ );
1544
+
1545
+ await this._credentialWallet.saveAll(credsWithIden3MTPProof);
1546
+
1547
+ await this.publishRevocationInfoByCredentialStatusType(did, opts.revocationOpts.type, {
1548
+ rhsUrl: opts.revocationOpts.id,
1549
+ onChain: opts.revocationOpts.onChain
1550
+ });
1551
+
1552
+ return credsWithIden3MTPProof[0];
1553
+ };
1554
+
1555
+ let txId = '';
1556
+
1557
+ let attempt = 2;
1558
+ do {
1559
+ try {
1560
+ txId = await this.transitState(did, oldTreeState, isOldStateGenesis, ethSigner, prover);
1561
+ break;
1562
+ } catch (err) {
1563
+ // eslint-disable-next-line no-console
1564
+ console.warn(
1565
+ `Error while transiting state, retrying state transition, attempt: ${attempt}`,
1566
+ err
1567
+ );
1568
+ }
1569
+ } while (--attempt);
1570
+
1571
+ if (!txId) {
1572
+ const oldTransitStateInfoJson = JSON.stringify(
1573
+ {
1574
+ claimsRoot: oldTreeState.claimsRoot.hex(),
1575
+ revocationRoot: oldTreeState.revocationRoot.hex(),
1576
+ rootOfRoots: oldTreeState.rootOfRoots.hex(),
1577
+ state: oldTreeState.state.hex(),
1578
+ isOldStateGenesis,
1579
+ credentialId: credential.id,
1580
+ did: did.string()
1581
+ },
1582
+ null,
1583
+ 2
1584
+ );
1585
+ await this._credentialWallet.save(credential);
1586
+
1587
+ throw new Error(`Error publishing state, info to publish: ${oldTransitStateInfoJson}`);
1588
+ }
1589
+
1590
+ return addMtpToCredAndPublishRevState();
1591
+ }
1592
+ }