@0xpolygonid/js-sdk 1.35.7 → 1.35.8
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.
- package/dist/browser/esm/index.js +10 -20
- package/dist/browser/esm/index.js.map +1 -1
- package/dist/browser/umd/index.global.js +1 -1
- package/dist/browser/umd/index.global.js.map +1 -1
- package/dist/node/cjs/index.cjs +10 -20
- package/dist/node/cjs/index.cjs.map +1 -1
- package/dist/node/esm/index.js +10 -20
- package/dist/node/esm/index.js.map +1 -1
- package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +0 -3
- package/dist/types/proof/verifiers/pub-signals-verifier.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/proof/verifiers/pub-signals-verifier.ts +16 -26
|
@@ -432,7 +432,7 @@ if (cid) {
|
|
|
432
432
|
`?i="":(i!==""&&(i+=" "),i+=l)},showSharedRWMemory:function(){u()}}}),s=e;return new nF(o,s);function c(){let l="",d=o.exports.getMessageChar();for(;d!=0;)l+=String.fromCharCode(d),d=o.exports.getMessageChar();return l}function u(){let l=o.exports.getFieldNumLen32(),d=new Uint32Array(l);for(let h=0;h<l;h++)d[l-1-h]=o.exports.readSharedRWMemory(h);i!==""&&(i+=" "),i+=rF(d).toString()}}var nF=class{constructor(e,t){this.instance=e;this.instance=e,this.version=this.instance.exports.getVersion(),this.n32=this.instance.exports.getFieldNumLen32(),this.instance.exports.getRawPrime();let r=new Uint32Array(this.n32);for(let i=0;i<this.n32;i++)r[this.n32-1-i]=this.instance.exports.readSharedRWMemory(i);this.prime=rF(r),this.witnessSize=this.instance.exports.getWitnessSize(),this.sanityCheck=t}version;n32;prime;witnessSize;sanityCheck;circom_version(){return this.instance.exports.getVersion()}async _doCalculateWitness(e,t){this.instance.exports.init(this.sanityCheck||t?1:0);let r=Object.keys(e),i=0;if(r.forEach(o=>{let s=FRe(o),a=parseInt(s.slice(0,8),16),c=parseInt(s.slice(8,16),16),u=ORe(e[o]),l=this.instance.exports.getInputSignalSize(a,c);if(l<0)throw new Error(`Signal ${o} not found
|
|
433
433
|
`);if(u.length<l)throw new Error(`Not enough values for input signal ${o}
|
|
434
434
|
`);if(u.length>l)throw new Error(`Too many values for input signal ${o}
|
|
435
|
-
`);for(let d=0;d<u.length;d++){let h=MRe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(rF(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function MRe(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function rF(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function ORe(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function FRe(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var oI=class n{constructor(e){this._circuitStorage=e}static curveName="bn128";async verify(e,t){try{let r=await this._circuitStorage.loadCircuitData(t);if(!r.verificationKey)throw new Error(`verification file doesn't exist for circuit ${t}`);return pO(e,JSON.parse(lt.decode(r.verificationKey)))}catch(r){return console.log(r),!1}}async generate(e,t){let r=await this._circuitStorage.loadCircuitData(t);if(!r.wasm)throw new Error(`wasm file doesn't exist for circuit ${t}`);let i=await iF(r.wasm.buffer),o=JSON.parse(lt.decode(e)),s=await i.calculateWTNSBin(o,0);if(!r.provingKey)throw new Error(`proving file doesn't exist for circuit ${t}`);let{proof:a,publicSignals:c}=await LC.prove(r.provingKey,s);return await this.terminateCurve(),{proof:a,pub_signals:c}}async terminateCurve(){(await FE(n.curveName)).terminate()}};var oF=Object.values(fn),Uee=[0,1,2,3,4,5,6,16],Gee=[1,2,3,4,5,6],gh={credentialAtomicQueryMTPV2:{maxQueriesCount:1,supportedOperations:Uee},credentialAtomicQueryMTPV2OnChain:{maxQueriesCount:1,supportedOperations:Gee},credentialAtomicQuerySigV2:{maxQueriesCount:1,supportedOperations:Uee},credentialAtomicQuerySigV2OnChain:{maxQueriesCount:1,supportedOperations:Gee},"credentialAtomicQueryV3-beta.1":{maxQueriesCount:1,supportedOperations:oF},"credentialAtomicQueryV3OnChain-beta.1":{maxQueriesCount:1,supportedOperations:oF},authV2:{maxQueriesCount:0,supportedOperations:[]},authV3:{maxQueriesCount:0,supportedOperations:[]},"authV3-8-32":{maxQueriesCount:0,supportedOperations:[]},stateTransition:{maxQueriesCount:0,supportedOperations:[]},"linkedMultiQuery10-beta.1":{maxQueriesCount:10,supportedOperations:oF}},Z0=class{constructor(e,t,r){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=r}async generateInputs(e){let{circuitId:t}=e.proofReq,r=`${t.split("-")[0]}PrepareInputs`;if(e.circuitQueries.length>gh[t].maxQueriesCount)throw new Error(`circuit ${t} supports only ${gh[t].maxQueriesCount} queries`);let o=this[r];if(!o)throw new Error(`inputs generator for ${t} not found`);return o(e)}async newCircuitClaimData(e){let t=e.credential.getIden3SparseMerkleTreeProof(),r=new tE;r.claim=e.credentialCoreClaim,r.issuerId=ve.idFromDID(ve.parse(e.credential.issuer)),t&&(r.proof=t.mtp,r.treeState={state:t.issuerData.state.value,claimsRoot:t.issuerData.state.claimsTreeRoot,revocationRoot:t.issuerData.state.revocationTreeRoot,rootOfRoots:t.issuerData.state.rootOfRoots});let i=e.credential.getBJJSignature2021Proof();if(i){let o=i.issuerData.id,s=zl(o,e.credential),{credentialStatus:a,mtp:c,authCoreClaim:u}=i.issuerData;if(!a)throw new Error("can't check the validity of issuer auth claim: no credential status in proof");if(!c)throw new Error("issuer auth credential must have a mtp proof");if(!u)throw new Error("issuer auth credential must have a core claim proof");let l={issuerGenesisState:i.issuerData.state,issuerDID:o,userDID:s},d=await this._credentialWallet.getRevocationStatus(a,l),h=Hu(d);r.signatureProof={signature:i.signature,issuerAuthIncProof:{proof:i.issuerData.mtp,treeState:{state:i.issuerData.state.value,claimsRoot:i.issuerData.state.claimsTreeRoot,revocationRoot:i.issuerData.state.revocationTreeRoot,rootOfRoots:i.issuerData.state.rootOfRoots}},issuerAuthClaim:i.issuerData.authCoreClaim,issuerAuthNonRevProof:h}}return r}async prepareAuthBJJCredential(e,t){let{authCredential:r,incProof:i,nonRevProof:o}=await this._identityWallet.getActualAuthCredential(e,t),s=r.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(!s)throw new Error("auth core claim is not defined for auth bjj credential");return{credential:r,incProof:i,nonRevProof:o,coreClaim:s}}credentialAtomicQueryMTPV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a=new nE;a.id=ve.idFromDID(t),a.requestID=BigInt(r.id);let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},a.currentTimeStamp=Ct(new Date),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQueryMTPV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=Hu(e.revStatus);let u=new iE,l=ve.idFromDID(t);u.id=ve.idFromDID(t),u.requestID=BigInt(r.id);let d=await this._stateStorage.getGISTProof(l.bigInt()),h=mh(d);if(u.gistProof=h,c?.treeState&&(u.treeState={state:c?.treeState?.state,claimsRoot:c?.treeState?.claimsRoot,revocationRoot:c?.treeState?.revocationRoot,rootOfRoots:c?.treeState?.rootOfRoots}),u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let f=await this._identityWallet.signChallenge(i.challenge,a.credential);u.signature=f,u.challenge=i.challenge;let m=o[0];return u.query=m,u.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},u.currentTimeStamp=Ct(new Date),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,m.operator),u.inputsMarshal()};credentialAtomicQuerySigV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a=new sE;a.id=ve.idFromDID(t),a.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},a.requestID=BigInt(r.id),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation;let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.currentTimeStamp=Ct(new Date),this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQuerySigV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=Hu(e.revStatus);let u=new fE,l=ve.idFromDID(t);u.id=l,u.claim={issuerID:s.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let d=o[0];u.query=d,u.currentTimeStamp=Ct(new Date),c.treeState&&(u.treeState={state:c.treeState?.state,claimsRoot:c.treeState?.claimsRoot,revocationRoot:c.treeState?.revocationRoot,rootOfRoots:c.treeState?.rootOfRoots});let h=await this._stateStorage.getGISTProof(l.bigInt()),f=mh(h);if(u.gistProof=f,u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let m=await this._identityWallet.signChallenge(i.challenge,a.credential);return u.signature=m,u.challenge=i.challenge,this.checkOperatorSupport(r.circuitId,d.operator),u.inputsMarshal()};credentialAtomicQueryV3PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a;switch(r.query.proofType){case"BJJSignature2021":a="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":a="Iden3SparseMerkleTreeProof";break;default:if(s.proof)a="Iden3SparseMerkleTreeProof";else if(s.signatureProof)a="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let c=new cE;c.id=ve.idFromDID(t),c.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof,incProof:{proof:s.proof,treeState:s.treeState}},c.requestID=BigInt(r.id),c.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),c.profileNonce=BigInt(i.authProfileNonce),c.skipClaimRevocationCheck=i.skipRevocation;let u=o[0];return u.values=[16,0].includes(u.operator)?[]:u.values,c.query=u,c.currentTimeStamp=Ct(new Date),c.proofType=a,c.linkNonce=i.linkNonce??BigInt(0),c.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,c.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0),this.checkOperatorSupport(r.circuitId,u.operator),c.inputsMarshal()};credentialAtomicQueryV3OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=ve.idFromDID(t),a=await this.newCircuitClaimData(e);a.nonRevProof=Hu(e.revStatus);let c;switch(r.query.proofType){case"BJJSignature2021":c="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":c="Iden3SparseMerkleTreeProof";break;default:if(a.proof)c="Iden3SparseMerkleTreeProof";else if(a.signatureProof)c="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let u=new lE;u.id=ve.idFromDID(t),u.claim={issuerID:a?.issuerId,signatureProof:a.signatureProof,claim:a.claim,nonRevProof:a.nonRevProof,incProof:{proof:a.proof,treeState:a.treeState}},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let l=o[0];l.values=[16,0].includes(l.operator)?[]:l.values,u.query=l,u.currentTimeStamp=Ct(new Date),u.proofType=c,u.linkNonce=i.linkNonce??BigInt(0),u.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,u.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0);let d=lp(t);u.isBJJAuthEnabled=d?0:1,u.challenge=BigInt(i.challenge??0);let h=await this._stateStorage.getGISTProof(s.bigInt()),f=mh(h);if(u.gistProof=f,u.isBJJAuthEnabled===1){let m=await this.prepareAuthBJJCredential(t),b=await this.newCircuitClaimData({credential:m.credential,credentialCoreClaim:m.coreClaim}),w=await this._identityWallet.signChallenge(u.challenge,m.credential);u.authClaim=b.claim,u.authClaimIncMtp=b.proof,u.authClaimNonRevMtp=m.nonRevProof.proof,u.treeState=b.treeState,u.signature=w}return this.checkOperatorSupport(r.circuitId,l.operator),u.inputsMarshal()};linkedMultiQuery10PrepareInputs=async({preparedCredential:e,params:t,proofReq:r,circuitQueries:i})=>{let o=await this.newCircuitClaimData(e);o.nonRevProof=Hu(e.revStatus);let s=new id;return s.linkNonce=t.linkNonce??BigInt(0),s.claim=o.claim,s.query=i,i.forEach(a=>{this.checkOperatorSupport(r.circuitId,a.operator)}),i.forEach(a=>{a.values=[16,0].includes(a.operator)?[]:a.values}),s.inputsMarshal()};transformV2QueryOperator(e){return e===16||e===0?1:e}checkOperatorSupport(e,t){if(!gh[e].supportedOperations.includes(t))throw new Error(`operator ${$1(t)} is not supported by ${e}`)}};var NRe=1440*60*1e3;async function t8(n,e,t,r,i,o,s){let a=ve.parseFromId(r.issuerId);if(!(!n.allowedIssuers||n.allowedIssuers?.some(f=>f==="*"||f===a.string())))throw new Error("issuer is not in allowed list");if(!n.type)throw new Error("query type is missing");let u=await Nr.getTypeIDFromContext(JSON.stringify(t),n.type,{documentLoader:o});if(Yl(Me.encode(u)).bigInt()!==r.schemaHash.bigInt())throw new Error("schema that was used is not equal to requested in query");if(!n.skipClaimRevocationCheck&&r.isRevocationChecked===0)throw new Error("check revocation is required");Kee(i,e);let d=NRe;if(s?.acceptedProofGenerationDelay&&(d=s.acceptedProofGenerationDelay),Date.now()-ra(Number(r.timestamp)).getTime()>d)throw new Error("generated proof is outdated")}function Kee(n,e){let t=gh[n];if(e.length>t.maxQueriesCount)throw new Error(`circuit ${n} supports only ${gh[n].maxQueriesCount} queries`)}function n8(n,e){if(!gh[n].supportedOperations.includes(e))throw new Error(`circuit ${n} not support ${$1(e)} operator`)}function sF(n,e){if(n.operator!=fn.$noop){if(n.merklized===1){if(n.claimPathNotExists===1)throw new Error("proof doesn't contains target query key");if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}function aF(n,e){if(n.operator!=0){if(n.operator===11&&!n.merklized)throw new Error("$exists operator is not supported for non-merklized credential");if(n.merklized===1){if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}async function cF(n,e){if(e.operator!==1)throw new Error("empty credentialSubject request available only for equal operation");for(let i=1;i<e.value.length;i++)if(e.value[i]!==0n)throw new Error("empty credentialSubject request not available for array of values");let r=await Nr.newPath([qe.CREDENTIAL_SUBJECT_PATH]).mtEntry();if(e.claimPathKey!==r)throw new Error("proof doesn't contain credentialSubject in claimPathKey")}async function r8(n,e){if(e.operator!==n.operator)throw new Error("operator that was used is not equal to request");if(e.operator!==0){for(let t=0;t<e.value.length;t++)if(e.value[t]!==n.values[t]){if(e.value[t]===0n&&n.values[t]===void 0)continue;throw new Error("comparison value that was used is not equal to requested in query")}}}async function uF(n,e,t,r){if(await sI(n.fieldName,t,r)!==e.value[0])throw new Error("value that was used is not equal to requested in query");if(e.operator!==1)throw new Error("operator for selective disclosure must be $eq");for(let o=1;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("selective disclosure not available for array of values")}async function lF(n,e,t,r){if(await sI(n.fieldName,t,r)!==e.operatorOutput)throw new Error("operator output should be equal to disclosed value");if(e.operator!==16)throw new Error("operator for selective disclosure must be $sd");for(let o=0;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("public signal values must be zero")}async function dF(n){if(n.operator!==0)throw new Error("empty credentialSubject request available only for $noop operation");for(let e=1;e<n.value.length;e++)if(n.value[e]!==0n)throw new Error("empty credentialSubject request not available for array of values")}var sI=async(n,e,t)=>{if(!e)throw new Error("verifiablePresentation is required for selective disclosure request");let r,i=JSON.stringify(e);try{r=await Cu.merklizeJSONLD(i,{documentLoader:t})}catch{throw new Error("can't merklize verifiablePresentation")}let o;try{let c=`verifiableCredential.credentialSubject.${n}`;o=await Nr.fromDocument(null,i,c,{documentLoader:t})}catch{throw new Error(`can't build path to '${n}' key`)}let s,a;try{({proof:s,value:a}=await r.proof(o))}catch{throw new Error(`can't get value by path '${n}'`)}if(!a)throw new Error(`can't get merkle value for field '${n}'`);if(!s.existence)throw new Error(`path [${o.parts}] doesn't exist in verifiablePresentation document`);return await a.mtEntry()};function URe(n){let e=Array(n.length).fill("uint256");return BigInt(nn.keccak256(nn.solidityPacked(e,n)))&BigInt("0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")}function GRe(n,e){return(BigInt(nn.keccak256(nn.solidityPacked(["bytes","address"],[n,e])))&BigInt("0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))+BigInt("0x0001000000000000000000000000000000000000000000000000000000000000")}function KRe(n,e,t){return BigInt(nn.keccak256(nn.solidityPacked(["uint256[]","uint256[]","address"],[n,e,t])))}function HRe(n,e,t,r,i,o){let s=Yr(n,64),a=On.spongeHashX(s,6);return On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(o),a])}function fF(n,e,t,r,i,o,s,a,c,u){let l=Yr(n,jS),d=On.spongeHashX(l,6),h=On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(s),d]);return On.hash([h,BigInt(o),BigInt(a),BigInt(c),BigInt(u),0n])}var JRe=new Error("user state is not valid"),i8=0n,aI=class{constructor(e,t){this._documentLoader=e;this._stateStorage=t}userId;challenge;async verify(e,t){let r=`${e.split("-")[0]}Verify`,i=this[r];if(!i)throw new Error(`public signals verifier for ${e} not found`);return i(t)}credentialAtomicQueryMTPV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new rE;if(a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),!a.userID)throw new Error("user id is not presented in proof public signals");if(!a.requestID)throw new Error("requestId is not presented in proof public signals");this.userId=a.userID,this.challenge=a.requestID;let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQueryMTPV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerClaimIdenState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i),a};credentialAtomicQuerySigV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new aE;a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),this.userId=a.userID,this.challenge=a.requestID;let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQuerySigV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerAuthState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i),a};credentialAtomicQueryV3Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s,params:a})=>{let c=new uE;c=c.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),this.userId=c.userID,this.challenge=c.requestID;let u={issuerId:c.issuerID,schemaHash:c.claimSchema,slotIndex:c.slotIndex,operator:c.operator,value:c.value,timestamp:c.timestamp,merklized:c.merklized,claimPathKey:c.claimPathKey,valueArraySize:c.getValueArrSize(),operatorOutput:c.operatorOutput,isRevocationChecked:c.isRevocationChecked};if(!e.type)throw new Error("proof query type is undefined");let l=this._documentLoader??Ho(),d;try{d=(await l(e.context??"")).document}catch{throw new Error("can't load schema for request query")}let h=await iI(e.type,JSON.stringify(d),e.credentialSubject,{documentLoader:l}),f="credentialAtomicQueryV3-beta.1";await t8(e,h,d,u,f,this._documentLoader,s);let m=h[0];if(n8(f,u.operator),m.operator===16)try{await lF(m,u,t,l)}catch(K){throw new Error(`failed to validate selective disclosure: ${K.message}`)}else if(!m.fieldName&&m.operator==0)try{await dF(u)}catch(K){throw new Error(`failed to validate operators: ${K.message}`)}else try{await r8(m,u)}catch(K){throw new Error(`failed to validate operators: ${K.message}`)}aF(u,m);let{proofType:b,verifierID:w,nullifier:S,nullifierSessionID:T,linkID:G}=c;switch(e.proofType){case"BJJSignature2021":if(b!==1)throw new Error("wrong proof type for BJJSignature");break;case"Iden3SparseMerkleTreeProof":if(b!==2)throw new Error("wrong proof type for Iden3SparseMerkleTreeProof");break;default:}let U=BigInt(a?.nullifierSessionId??0);if(U!==0n){if(BigInt(S??0)===0n)throw new Error("nullifier should be provided for nullification and should not be 0");let K=a?.verifierDid;if(!K)throw new Error("verifierDid is required");let M=ve.idFromDID(K);if(w.bigInt()!=M.bigInt())throw new Error("wrong verifier is used for nullification");if(T!==U)throw new Error(`wrong verifier session id is used for nullification, expected ${U}, got ${T}`)}else if(T!==0n)throw new Error("Nullifier id is generated but wasn't requested");if(!e.groupId&&G!==0n)throw new Error("proof contains link id, but group id is not provided");if(e.groupId&&G===0n)throw new Error("proof doesn't contain link id, but group id is provided");return await this.checkStateExistenceForId(c.issuerID,c.issuerState),c.isRevocationChecked!==0&&await this.checkRevocationState(c.issuerID,c.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i),c};authV2Verify=async({sender:e,challenge:t,pubSignals:r,opts:i})=>{let o=new Xs;o=o.pubSignalsUnmarshal(Me.encode(JSON.stringify(r))),this.userId=o.userID,this.challenge=o.challenge;let s=await this.checkGlobalState(o.GISTRoot,this.userId),a=Wr.DEFAULT_AUTH_VERIFY_DELAY;if(i?.acceptedStateTransitionDelay&&(a=i.acceptedStateTransitionDelay),!s.latest&&Date.now()-ra(Number(s.transitionTimestamp)).getTime()>a)throw new Error("global state is outdated");return this.verifyIdOwnership(e,t),new kn};linkedMultiQuery10Verify=async({query:e,verifiablePresentation:t,pubSignals:r})=>{let i=new gE;i=i.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let o,s={documentLoader:this._documentLoader};try{o=(await s.documentLoader(e.context||"")).document}catch{throw new Error("can't load schema for request query")}let a=JSON.stringify(o),c=e.credentialSubject,u=await Nr.getTypeIDFromContext(a,e.type||"",s),l=Yl(Me.encode(u)),d=await iI(e.type||"",a,c,s),h=[],f=d[0]?.merklizedSchema?1:0;for(let w=0;w<id.queryCount;w++){let S=d[w],T=S?.values??[],G=T.length,U=fF(T,l,S?.slotIndex??0,S?.operator??0,S?.claimPathKey.toString()??0,G,f,0,0,0);h.push({queryHash:U,queryMeta:S})}let m=(w,S)=>w.queryHash<S.queryHash?-1:w.queryHash>S.queryHash?1:0,b=i.circuitQueryHash.map((w,S)=>({queryHash:w,operatorOutput:i.operatorOutput[S]}));b.sort(m),h.sort(m);for(let w=0;w<id.queryCount;w++){if(h[w].queryHash!=b[w].queryHash)throw new Error("query hashes do not match");if(h[w].queryMeta?.operator===16&&await sI(h[w].queryMeta.fieldName,t,this._documentLoader)!=b[w].operatorOutput)throw new Error("disclosed value is not in the proof outputs")}return i};verifyIdOwnership=(e,t)=>{if(ve.idFromDID(ve.parse(e)).string()!==this.userId.string())throw new Error(`sender id is not used for proof creation, expected ${e}, user from public signals: ${this.userId.string()}`);if(t!==this.challenge)throw new Error(`challenge is not used for proof creation, expected ${t}, challenge from public signals: ${this.challenge} `)};async checkQueryV2Circuits(e,t,r,i,o){if(!t.type)throw new Error("proof query type is undefined");let s=this._documentLoader??Ho(),a;try{a=(await s(t.context??"")).document}catch{throw new Error("can't load schema for request query")}let c=await iI(t.type,JSON.stringify(a),t.credentialSubject,{documentLoader:s});await t8(t,c,a,r,e,this._documentLoader,i);let u=c[0];if(n8(e,r.operator),u.operator===16)try{await uF(u,r,o,s)}catch(l){throw new Error(`failed to validate selective disclosure: ${l.message}`)}else if(!u.fieldName&&u.operator==0)try{await cF(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}else try{await r8(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}sF(r,u)}async resolve(e,t){let r=e.bigInt(),i=ve.parseFromId(e),o=nu(i,t),s;try{s=await this._stateStorage.getStateInfoByIdAndState(r,t)}catch(a){if(AO(a)){if(o)return{latest:!0,transitionTimestamp:0};throw new Error("State is not genesis and not registered in the smart contract")}throw a}if(!s.id||s.id.toString()!==r.toString())throw new Error("state was recorded for another identity");if(!s.state||s.state.toString()!==t.toString()){if(!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===i8.toString())throw new Error("no information about state transition");return{latest:!1,transitionTimestamp:s.replacedAtTimestamp.toString()}}return{latest:!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===i8.toString(),transitionTimestamp:s.replacedAtTimestamp?.toString()??0}}async rootResolve(e,t){let r;try{r=await this._stateStorage.getGISTRootInfo(e,t)}catch(i){throw xO(i)?new Error("GIST root does not exist in the smart contract"):i}if(r.root.toString()!==e.toString())throw new Error("gist info contains invalid state");if(r.replacedByRoot.toString()!==i8.toString()){if(r.replacedAtTimestamp.toString()===i8.toString())throw new Error("state was replaced, but replaced time unknown");return{latest:!1,transitionTimestamp:r.replacedAtTimestamp.toString()}}return{latest:!0,transitionTimestamp:0}}checkStateExistenceForId=async(e,t)=>{await this.resolve(e,t.bigInt())};checkGlobalState=async(e,t)=>this.rootResolve(e.bigInt(),t.bigInt());checkRevocationStateForId=async(e,t)=>await this.resolve(e,t.bigInt());checkRevocationState=async(e,t,r)=>{let i=await this.checkRevocationStateForId(e,t),o=r?.acceptedStateTransitionDelay??Wr.DEFAULT_PROOF_VERIFY_DELAY;if(!i.latest&&Date.now()-ra(Number(i.transitionTimestamp)).getTime()>o)throw new Error("issuer state is outdated")}};var hF=class{constructor(e,t,r,i,o){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=i;this._prover=o?.prover??new oI(r),this._ldOptions={...o,documentLoader:o?.documentLoader??T0(o)},this._inputsGenerator=new Z0(e,t,i),this._pubSignalsVerifier=new aI(o?.documentLoader??T0(o),i)}_prover;_ldOptions;_inputsGenerator;_pubSignalsVerifier;async verifyProof(e,t){return this._prover.verify(e,t)}async verifyZKPResponse(e,t){if(!await this._prover.verify(e,e.circuitId))throw Error(`Proof with circuit id ${e.circuitId} and request id ${e.id} is not valid`);let i={pubSignals:e.pub_signals,query:t.query,verifiablePresentation:e.vp,sender:t.sender,challenge:BigInt(e.id),opts:t.opts,params:t.params};return{linkID:(await this._pubSignalsVerifier.verify(e.circuitId,i)).linkID}}async generateProof(e,t,r){r||(r={skipRevocation:!1,challenge:0n});let i={cred:r.credential,revStatus:r.credentialRevocationStatus};if(r.credential||(i=await this.findCredentialByProofQuery(t,e.query)),r.credential&&!r.credentialRevocationStatus&&!r.skipRevocation){let j=await this._credentialWallet.getRevocationStatusFromCredential(r.credential);i={cred:r.credential,revStatus:j}}if(!i.cred)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+` ${JSON.stringify(e.query)}`);let o=await this._identityWallet.getCoreClaimFromCredential(i.cred),{nonce:s,genesisDID:a}=await this._identityWallet.getGenesisDIDMetadata(t),c={credential:i.cred,credentialCoreClaim:o,revStatus:i.revStatus},u=ve.parse(c.credential.credentialSubject.id),{nonce:l,genesisDID:d}=await this._identityWallet.getGenesisDIDMetadata(u);if(d.string()!==a.string())throw new Error(qe.ERRORS.PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH);let h=_C(e.query.credentialSubject);if(!h.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST);let f=c.credentialCoreClaim.getMerklizedPosition(),m;f!==jn.None&&(m=await c.credential.merklize(this._ldOptions));let b=e.query.context,w=e.query.groupId,S=await this.loadLdContext(b),T=e.query.type,G=[],U=[];for(let j of h){let Y=await $C(j,lt.decode(S),T,this._ldOptions);G.push(Y);let Q=await this.toCircuitsQuery(c.credential,Y,m);U.push(Q)}let K=await this.generateInputs(c,a,e,{...r,authProfileNonce:s,credentialSubjectProfileNonce:l,linkNonce:w?r.linkNonce:0n},U),M=G.filter(j=>j.operator===16),A;M.length&&(A=VT(b,T,c.credential,M));let{proof:D,pub_signals:z}=await this._prover.generate(K,e.circuitId);return{id:e.id,circuitId:e.circuitId,vp:A,proof:D,pub_signals:z}}async generateAuthProof(e,t,r){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error("CircuitId is not supported");r||(r={challenge:0n});let i=r.challenge?vt.intToBytes(r.challenge).reverse():new Uint8Array(32),o=await this.generateAuthInputs(i,t,e),s=await this._prover.generate(o,e);return{circuitId:e,proof:s.proof,pub_signals:s.pub_signals}}async transitState(e,t,r,i,o){return this._identityWallet.transitState(e,t,r,o,this._prover)}async generateInputs(e,t,r,i,o){return this._inputsGenerator.generateInputs({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})}async toCircuitsQuery(e,t,r){if(t.merklizedSchema&&!r)throw new Error("merklized root position is set to None for merklized schema");if(!t.merklizedSchema&&r)throw new Error("merklized root position is not set to None for non-merklized schema");let i=new eE;if(i.slotIndex=t.slotIndex,i.operator=t.operator,i.values=t.values,t.merklizedSchema&&r){let{proof:o,value:s}=await r.proof(t.path);i.valueProof=new jr,i.valueProof.mtp=o,i.valueProof.path=t.claimPathKey;let a=await s?.mtEntry()??0n;if(i.valueProof.value=a,!t.fieldName)return i.values=[a],i}if(t.operator===16){let[o,...s]=t.fieldName.split("."),a=e.credentialSubject[o];for(let c of s)a=a[c];if(typeof a>"u")throw new Error(`credential doesn't contain value for field ${t.fieldName}`);i.values=await e8(a,t.datatype)}return i}async loadLdContext(e){let t=Ho(this._ldOptions),r;try{r=(await t(e)).document}catch{throw new Error(`can't load ld context from url ${e}`)}return Me.encode(JSON.stringify(r))}async generateAuthV2Inputs(e,t,r){if(r!=="authV2")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=mh(l),h=new k0;return h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthInputs(e,t,r){if(r!=="authV2"&&r!=="authV3"&&r!=="authV3-8-32")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=mh(l),h=new yE;return r==="authV3-8-32"&&(h.mtLevel=8,h.mtLevelOnChain=32),h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthV2Proof(e,t){let r=await this.generateAuthInputs(e,t,"authV2");return await this._prover.generate(r,"authV2")}async verifyState(e,t,r={acceptedStateTransitionDelay:Wr.DEFAULT_AUTH_VERIFY_DELAY}){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error(`CircuitId is not supported ${e}`);let i,o;if(e==="authV2"){let a=new Xs().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}else{let a=new M0().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}let s=await this._stateStorage.getGISTRootInfo(i,o);if(s.root!==i)throw new Error("gist info contains invalid state");if(s.replacedByRoot!==0n){if(s.replacedAtTimestamp===0n)throw new Error("state was replaced, but replaced time unknown");if(Date.now()-ra(Number(s.replacedAtTimestamp)).getTime()>(r?.acceptedStateTransitionDelay??Wr.DEFAULT_AUTH_VERIFY_DELAY))throw new Error("global state is outdated")}return!0}async findCredentialByProofQuery(e,t){let r=await this._identityWallet.findOwnedCredentialsByDID(e,t);if(!r.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE);return t.skipClaimRevocationCheck?{cred:r[0],revStatus:void 0}:await this._credentialWallet.findNonRevokedCredential(r)}};var pF=class{constructor(e,t,r,i){this._kms=e;this._storage=t;this._credentialWallet=r;this._opts=i;this._credentialStatusPublisherRegistry=this.getCredentialStatusPublisherRegistry(i),this._inputsGenerator=new Z0(this,r,t.states),this._transactionService=new _s(t.states.getRpcProvider())}_credentialStatusPublisherRegistry;_inputsGenerator;_transactionService;get credentialWallet(){return this._credentialWallet}getCredentialStatusPublisherRegistry(e){if(e?.credentialStatusPublisherRegistry)return this._opts?.credentialStatusPublisherRegistry;{let t=new nI,r={publish:()=>Promise.resolve()};return t.register("Iden3ReverseSparseMerkleTreeProof",new W0),t.register("SparseMerkleTreeProof",r),t.register("Iden3commRevocationStatusV1.0",r),t}}async createAuthCoreClaim(e,t){let r=await this._kms.createKeyFromSeed("BJJ",t),i=await this._kms.publicKey(r),o=Vu.newFromHex(i),s=$o.authSchemaHash,a=Mr.newClaim(s,za.withIndexDataInts(o.p[0],o.p[1]),za.withRevocationNonce(BigInt(0)));return a.setRevocationNonce(BigInt(e)),{authClaim:a,pubKey:o}}async createAuthBJJCredential(e,t,r,i,o){let s=r.getExpirationDate(),a=s?Ct(s):0,c={credentialSchema:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,credentialSubject:{x:t.p[0].toString(),y:t.p[1].toString()},subjectPosition:HP(r.getIdPosition()),version:0,expiration:a,revocationOpts:{nonce:Number(r.getRevocationNonce()),id:o.id.replace(/\/$/,""),type:o.type,issuerState:i.hex()}},u=await this._credentialWallet.getAllAuthBJJCredentials(e),l=new Ur;if(u.length===0){let d=JSON.parse(qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);try{l=this._credentialWallet.createCredential(e,c,d)}catch(h){throw new Error(`Error create w3c credential ${h.message}`)}}else l=await this.issueCredential(e,c);return l}async createIdentity(e){let t=e.seed?XP(Pn.encode(Qu(e.seed)),qP):Ft();e.seed=e.seed??Gc(32),await this._storage.mt.createIdentityMerkleTrees(t);let r=e.revocationOpts.nonce??0,{authClaim:i,pubKey:o}=await this.createAuthCoreClaim(r,e.seed),{hi:s,hv:a}=i.hiHv();await this._storage.mt.addToMerkleTree(t,0,s,a);let c=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),u=await c.root(),l=Eh([u.bigInt(),Ne.bigInt(),Ne.bigInt()]),d=Jc(e.method||Ni.Iden3,e.blockchain||Ht.Polygon,e.networkId||Jt.Amoy),h=$e.idGenesisFromIdenState(d,l.bigInt()),f=ve.parseFromId(h);await this._storage.mt.bindMerkleTreeToNewIdentifier(t,f.string());let m={revocationRoot:Ne,claimsRoot:u,state:l,rootOfRoots:Ne};await this._storage.identity.getIdentity(f.string())||await this._storage.identity.saveIdentity({did:f.string(),state:l,isStatePublished:!1,isStateGenesis:!0});let w=await this._credentialWallet.findByQuery({credentialSubject:{x:{$eq:o.p[0].toString()},y:{$eq:o.p[1].toString()}},allowedIssuers:[f.string()]});if(w.length===1&&w[0].credentialStatus.type===e.revocationOpts.type)return{did:f,credential:w[0]};for(let K=0;K<w.length;K++)await this._credentialWallet.remove(w[K].id);let S=await this.createAuthBJJCredential(f,o,i,l,e.revocationOpts),T=i.hIndex(),{proof:G}=await c.generateProof(T,u),U=new mc({mtp:G,issuerData:{id:f,state:{rootOfRoots:m.rootOfRoots,revocationTreeRoot:m.revocationRoot,claimsTreeRoot:u,value:l}},coreClaim:i});return S.proof=[U],e.revocationOpts.genesisPublishingDisabled||await this.publishRevocationInfoByCredentialStatusType(f,e.revocationOpts.type,{rhsUrl:e.revocationOpts.id,onChain:e.revocationOpts.onChain}),await this._credentialWallet.save(S),{did:f,credential:S}}async createEthereumBasedIdentity(e){e.seed=e.seed??Gc(32),e.createBjjCredential=e.createBjjCredential??!0;let t,r=e.ethSigner;if(e.createBjjCredential&&!r)throw new Error(qe.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);let i=Ne,o=Jc(e.method||Ni.Iden3,e.blockchain||Ht.Polygon,e.networkId||Jt.Amoy),s=await this._kms.createKeyFromSeed("Secp256k1",e.seed),a=(await this._kms.publicKey(s)).slice(2),c=e4(o,a);if(await this._storage.mt.createIdentityMerkleTrees(c.string()),await this._storage.identity.saveIdentity({did:c.string(),state:i,isStatePublished:!1,isStateGenesis:!0}),e.createBjjCredential&&r){let u={revocationRoot:Ne,claimsRoot:Ne,state:i,rootOfRoots:Ne};t=await this.addBJJAuthCredential(c,u,!0,r,e)}return{did:c,credential:t}}async getGenesisDIDMetadata(e){let t=await this._storage.identity.getIdentity(e.string());if(t)return{nonce:0,genesisDID:ve.parse(t.did)};let r=await this._storage.identity.getProfileById(e.string());if(!r)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);return{nonce:r.nonce,genesisDID:ve.parse(r.genesisIdentifier)}}async createProfile(e,t,r,i){let o=JP(e,t),s=Array.isArray(i),a=s?i:i?.tags,{didDocument:c,encryptionKeyOps:u}=s?{}:i??{},l=await this._storage.identity.getProfilesByGenesisIdentifier(e.string());if((await this._storage.identity.getProfilesByVerifier(r,a)).length)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);if(l.find(m=>m.nonce==t))throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);let f=c;if(u?.provider){let m=new vE(u.provider,{alias:u.alias});if(!f)f=(await new xE(o.string()).addVerificationMethod(m,iC)).build();else{let b=await m.build(o.string()),w=[f["@context"]].flat().filter(S=>typeof S=="string");f={...f,verificationMethod:[...f.verificationMethod??[],b],"@context":[...new Set([...w,iC])]}}}return await this._storage.identity.saveProfile({id:o.string(),nonce:t,genesisIdentifier:e.string(),verifier:r,tags:a,did_doc:f}),o}async getProfilesByDID(e){return this._storage.identity.getProfilesByGenesisIdentifier(e.string())}async generateKey(e){return await this._kms.createKeyFromSeed(e,Gc(32))}async getProfileByVerifier(e){return this._storage.identity.getProfileByVerifier(e)}async getProfilesByVerifier(e,t){return this._storage.identity.getProfilesByVerifier(e,t)}async getDIDTreeModel(e){let t=e.string(),r=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),i=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,1),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,2);return{state:Eh([(await r.root()).bigInt(),(await i.root()).bigInt(),(await o.root()).bigInt()]),claimsTree:r,revocationTree:i,rootsTree:o}}async generateCredentialMtp(e,t,r){let i=await this.getCoreClaimFromCredential(t);return this.generateCoreClaimMtp(e,i,r)}async generateCoreClaimMtp(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t.hIndex(),r?r.claimsRoot:s);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async generateNonRevocationMtp(e,t,r){let o=(await this.getCoreClaimFromCredential(t)).getRevocationNonce();return this.generateNonRevocationMtpWithNonce(e,o,r)}async generateNonRevocationMtpWithNonce(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),1),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t,r?r.revocationRoot:c);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async sign(e,t){let r=Jv(t),i=On.hashBytes(e),o=await this._kms.sign(r,vt.intToBytes(i));return Ld.newFromCompressed(o)}async signChallenge(e,t){let r=Jv(t),i=await this._kms.sign(r,vt.intToBytes(e));return Ld.newFromCompressed(i)}async issueCredential(e,t,r){t.revocationOpts.id=t.revocationOpts.id.replace(/\/$/,"");let i,o=r?.documentLoader??T0(r);try{i=(await o(t.credentialSchema)).document}catch{throw new Error(`can't load credential schema ${t.credentialSchema}`)}let s=i,a=new Ur,c=await this.getDIDTreeModel(e);t.revocationOpts.issuerState=c.state.hex(),t.revocationOpts.nonce=typeof t.revocationOpts.nonce=="number"?t.revocationOpts.nonce:new DataView(Gc(16).buffer).getUint32(0,!1),t.subjectPosition=t.subjectPosition??"index";try{a=this._credentialWallet.createCredential(e,t,s);let T=Me.encode(JSON.stringify(a)),G=Me.encode(JSON.stringify(i));await new _1().validate(T,G)}catch(T){throw new Error(`Error create w3c credential ${T.message}`)}let{authCredential:u}=await this.getActualAuthCredential(e),l={revNonce:t.revocationOpts.nonce,subjectPosition:t.subjectPosition,merklizedRootPosition:t.merklizedRootPosition??"",updatable:!1,version:0,merklizeOpts:{...r,documentLoader:o}},d=await a.toCoreClaim(l),{hi:h,hv:f}=d.hiHv(),m=On.hash([h,f]),b=await this.signChallenge(m,u);if(!u.proof)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF);let w=u.getIden3SparseMerkleTreeProof();if(!w)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF);let S=new wf({issuerData:{id:e,state:w.issuerData.state,authCoreClaim:w.coreClaim,mtp:w.mtp,credentialStatus:u.credentialStatus},coreClaim:d,signature:b});return a.proof=[S],a}async getActualAuthCredential(e,t){let r=await this._credentialWallet.getAllAuthBJJCredentials(e);for(let i=0;i<r.length;i++){let o=await this.generateCredentialMtp(e,r[i],t);if(!o.proof.existence)continue;let s=await this.generateNonRevocationMtp(e,r[i],t);if(!s.proof.existence)return{authCredential:r[i],incProof:o,nonRevProof:s}}throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND)}async revokeCredential(e,t){let r=await this.getDIDTreeModel(e),i=await this.getCoreClaimFromCredential(t);if(!i)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);let o=i.getRevocationNonce();return await r.revocationTree.add(o,BigInt(0)),Number(BigInt.asUintN(64,o))}async addCredentialsToMerkleTree(e,t){let r=await this.getDIDTreeModel(t),i=await r.claimsTree.root(),o=await r.rootsTree.root(),s=await r.revocationTree.root(),a={state:r.state,claimsRoot:i,revocationRoot:s,rootOfRoots:o};for(let d=0;d<e.length;d++){let f=e[d].getCoreClaimFromProof("BJJSignature2021");if(!f)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);await this._storage.mt.addToMerkleTree(t.string(),0,f.hIndex(),f.hValue())}let u=await(await this.getDIDTreeModel(t)).claimsTree.root();await this._storage.mt.addToMerkleTree(t.string(),2,u.bigInt(),BigInt(0));let l=await this.getDIDTreeModel(t);return i=await l.claimsTree.root(),o=await l.rootsTree.root(),s=await l.revocationTree.root(),{credentials:e,newTreeState:{state:l.state,claimsRoot:i,rootOfRoots:o,revocationRoot:s},oldTreeState:a}}async generateIden3SparseMerkleTreeProof(e,t,r,i,o,s,a){for(let c=0;c<t.length;c++){let u=t[c],l=u.getCoreClaimFromProof("BJJSignature2021")||await u.toCoreClaim(a);if(!l)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);let d=await this.generateCoreClaimMtp(e,l,s),h=new mc({mtp:d.proof,issuerData:{id:e,state:{claimsTreeRoot:d.treeState.claimsRoot,revocationTreeRoot:d.treeState.revocationRoot,rootOfRoots:d.treeState.rootOfRoots,value:d.treeState.state,txId:r,blockNumber:i,blockTimestamp:o}},coreClaim:l});Array.isArray(t[c].proof)?t[c].proof.push(h):t[c].proof=t[c].proof?[t[c].proof,h]:[h]}return t}async publishSpecificStateToRHS(e,t,r){await ZC(e.state,e,t,r)}async publishStateToRHS(e,t,r){let i=await this.getDIDTreeModel(e);await ZC(i.state,{revocationTree:i.revocationTree,claimsTree:i.claimsTree,state:i.state,rootsTree:i.rootsTree},t,r)}async publishRevocationInfoByCredentialStatusType(e,t,r){let i=this._credentialStatusPublisherRegistry.get(t);if(!i)throw new Error(`there is no registered publisher to save hash is not registered for ${t} is not registered`);let o=[],s=r?.treeModel??await this.getDIDTreeModel(e);if(o=await XC(r?.revokedNonces??[],{revocationTree:s.revocationTree,claimsTree:s.claimsTree,state:s.state,rootsTree:s.rootsTree},s.state),!o.length)return;let a=i.map(c=>c.publish({nodes:o,...r,credentialStatusType:t,issuerDID:e}));await Promise.all(a)}async getCoreClaimFromCredential(e){let t=e.getCoreClaimFromProof("BJJSignature2021"),r=e.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(r&&t&&r.hex()!==t.hex())throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);if(!r&&!t)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);return r??t}async findOwnedCredentialsByDID(e,t){let r=await this._credentialWallet.findByQuery(t);if(!r.length)throw new Error(qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);let{genesisDID:i}=await this.getGenesisDIDMetadata(e),o=await this.getProfilesByDID(i);return r.filter(s=>{let a=s.credentialSubject.id;return a==i.string()||o.some(c=>c.id===a)})}async updateIdentityState(e,t,r){let i=await this.getDIDTreeModel(e);await this._storage.identity.saveIdentity({did:e.string(),state:r?.state??i.state,isStatePublished:t,isStateGenesis:!1})}async transitState(e,t,r,i,o){let s=await this.getDIDTreeModel(e),a=await s.claimsTree.root(),c=await s.rootsTree.root(),l={revocationRoot:await s.revocationTree.root(),claimsRoot:a,state:s.state,rootOfRoots:c},d=ve.idFromDID(e),h,f=lp(e),m;if(f){let b=t.state,w=l.state,S={userId:d,oldUserState:b,newUserState:w,isOldStateGenesis:r,methodId:BigInt(1),methodParams:"0x"};m=await this._storage.states.publishStateGeneric(i,S)}else{if(!o)throw new Error(qe.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);let b=await this._inputsGenerator.prepareAuthBJJCredential(e,t),w=T8.hash([t.state.bigInt(),l.state.bigInt()]),S=await this.signChallenge(w,b.credential),T=new pE;T.id=d,T.signature=S,T.isOldStateGenesis=r;let G=await this.generateCredentialMtp(e,b.credential,l);T.newTreeState=G.treeState,T.authClaimNewStateIncProof=G.proof,T.oldTreeState=t,T.authClaim={claim:b.coreClaim,incProof:b.incProof,nonRevProof:b.nonRevProof};let U=T.inputsMarshal();h=await o.generate(U,"stateTransition"),m=await this._storage.states.publishState(h,i)}return await this.updateIdentityState(e,!0,l),m}async getAuthBJJCredential(e,t,{nonce:r,seed:i,id:o,type:s}){let{authClaim:a,pubKey:c}=await this.createAuthCoreClaim(r,i),{hi:u,hv:l}=a.hiHv();await this._storage.mt.addToMerkleTree(e.string(),0,u,l);let d=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),h=Eh([(await d.root()).bigInt(),t.revocationRoot.bigInt(),t.rootOfRoots.bigInt()]);return this.createAuthBJJCredential(e,c,a,h,{id:o,type:s})}async addBJJAuthCredential(e,t,r,i,o,s){o.seed=o.seed??Gc(32),o.revocationOpts.nonce=o.revocationOpts.nonce??(r?0:o.revocationOpts.nonce??new DataView(Gc(12).buffer).getUint32(0));let a=await this.getAuthBJJCredential(e,t,{nonce:o.revocationOpts.nonce,seed:o.seed,id:o.revocationOpts.id,type:o.revocationOpts.type}),c=async()=>{let{receipt:d,block:h}=await this._transactionService.getTransactionReceiptAndBlock(u),f=await this.generateIden3SparseMerkleTreeProof(e,[a],u,d?.blockNumber,h?.timestamp,void 0,{revNonce:o.revocationOpts.nonce??0,subjectPosition:"",merklizedRootPosition:"",updatable:!1,version:0,merklizeOpts:{documentLoader:T0()}});return await this._credentialWallet.saveAll(f),await this.publishRevocationInfoByCredentialStatusType(e,o.revocationOpts.type,{rhsUrl:o.revocationOpts.id,onChain:o.revocationOpts.onChain}),f[0]},u="",l=2;do try{u=await this.transitState(e,t,r,i,s);break}catch(d){console.warn(`Error while transiting state, retrying state transition, attempt: ${l}`,d)}while(--l);if(!u){let d=JSON.stringify({claimsRoot:t.claimsRoot.hex(),revocationRoot:t.revocationRoot.hex(),rootOfRoots:t.rootOfRoots.hex(),state:t.state.hex(),isOldStateGenesis:r,credentialId:a.id,did:e.string()},null,2);throw await this._credentialWallet.save(a),new Error(`Error publishing state, info to publish: ${d}`)}return c()}};return b8(qRe);})();
|
|
435
|
+
`);for(let d=0;d<u.length;d++){let h=MRe(BigInt(u[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,c,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(rF(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let c=7;for(let d=0;d<this.n32;d++)r[c+d]=this.instance.exports.readSharedRWMemory(d);c+=this.n32,r[c]=this.witnessSize,c++,r[c]=2,c++;let l=(o*this.witnessSize).toString(16);r[c]=parseInt(l.slice(0,8),16),r[c+1]=parseInt(l.slice(8,16),16),c+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[c+h]=this.instance.exports.readSharedRWMemory(h);c+=this.n32}return i}};function MRe(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function rF(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function ORe(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function FRe(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var oI=class n{constructor(e){this._circuitStorage=e}static curveName="bn128";async verify(e,t){try{let r=await this._circuitStorage.loadCircuitData(t);if(!r.verificationKey)throw new Error(`verification file doesn't exist for circuit ${t}`);return pO(e,JSON.parse(lt.decode(r.verificationKey)))}catch(r){return console.log(r),!1}}async generate(e,t){let r=await this._circuitStorage.loadCircuitData(t);if(!r.wasm)throw new Error(`wasm file doesn't exist for circuit ${t}`);let i=await iF(r.wasm.buffer),o=JSON.parse(lt.decode(e)),s=await i.calculateWTNSBin(o,0);if(!r.provingKey)throw new Error(`proving file doesn't exist for circuit ${t}`);let{proof:a,publicSignals:c}=await LC.prove(r.provingKey,s);return await this.terminateCurve(),{proof:a,pub_signals:c}}async terminateCurve(){(await FE(n.curveName)).terminate()}};var oF=Object.values(fn),Uee=[0,1,2,3,4,5,6,16],Gee=[1,2,3,4,5,6],gh={credentialAtomicQueryMTPV2:{maxQueriesCount:1,supportedOperations:Uee},credentialAtomicQueryMTPV2OnChain:{maxQueriesCount:1,supportedOperations:Gee},credentialAtomicQuerySigV2:{maxQueriesCount:1,supportedOperations:Uee},credentialAtomicQuerySigV2OnChain:{maxQueriesCount:1,supportedOperations:Gee},"credentialAtomicQueryV3-beta.1":{maxQueriesCount:1,supportedOperations:oF},"credentialAtomicQueryV3OnChain-beta.1":{maxQueriesCount:1,supportedOperations:oF},authV2:{maxQueriesCount:0,supportedOperations:[]},authV3:{maxQueriesCount:0,supportedOperations:[]},"authV3-8-32":{maxQueriesCount:0,supportedOperations:[]},stateTransition:{maxQueriesCount:0,supportedOperations:[]},"linkedMultiQuery10-beta.1":{maxQueriesCount:10,supportedOperations:oF}},Z0=class{constructor(e,t,r){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=r}async generateInputs(e){let{circuitId:t}=e.proofReq,r=`${t.split("-")[0]}PrepareInputs`;if(e.circuitQueries.length>gh[t].maxQueriesCount)throw new Error(`circuit ${t} supports only ${gh[t].maxQueriesCount} queries`);let o=this[r];if(!o)throw new Error(`inputs generator for ${t} not found`);return o(e)}async newCircuitClaimData(e){let t=e.credential.getIden3SparseMerkleTreeProof(),r=new tE;r.claim=e.credentialCoreClaim,r.issuerId=ve.idFromDID(ve.parse(e.credential.issuer)),t&&(r.proof=t.mtp,r.treeState={state:t.issuerData.state.value,claimsRoot:t.issuerData.state.claimsTreeRoot,revocationRoot:t.issuerData.state.revocationTreeRoot,rootOfRoots:t.issuerData.state.rootOfRoots});let i=e.credential.getBJJSignature2021Proof();if(i){let o=i.issuerData.id,s=zl(o,e.credential),{credentialStatus:a,mtp:c,authCoreClaim:u}=i.issuerData;if(!a)throw new Error("can't check the validity of issuer auth claim: no credential status in proof");if(!c)throw new Error("issuer auth credential must have a mtp proof");if(!u)throw new Error("issuer auth credential must have a core claim proof");let l={issuerGenesisState:i.issuerData.state,issuerDID:o,userDID:s},d=await this._credentialWallet.getRevocationStatus(a,l),h=Hu(d);r.signatureProof={signature:i.signature,issuerAuthIncProof:{proof:i.issuerData.mtp,treeState:{state:i.issuerData.state.value,claimsRoot:i.issuerData.state.claimsTreeRoot,revocationRoot:i.issuerData.state.revocationTreeRoot,rootOfRoots:i.issuerData.state.rootOfRoots}},issuerAuthClaim:i.issuerData.authCoreClaim,issuerAuthNonRevProof:h}}return r}async prepareAuthBJJCredential(e,t){let{authCredential:r,incProof:i,nonRevProof:o}=await this._identityWallet.getActualAuthCredential(e,t),s=r.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(!s)throw new Error("auth core claim is not defined for auth bjj credential");return{credential:r,incProof:i,nonRevProof:o,coreClaim:s}}credentialAtomicQueryMTPV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a=new nE;a.id=ve.idFromDID(t),a.requestID=BigInt(r.id);let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},a.currentTimeStamp=Ct(new Date),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQueryMTPV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=Hu(e.revStatus);let u=new iE,l=ve.idFromDID(t);u.id=ve.idFromDID(t),u.requestID=BigInt(r.id);let d=await this._stateStorage.getGISTProof(l.bigInt()),h=mh(d);if(u.gistProof=h,c?.treeState&&(u.treeState={state:c?.treeState?.state,claimsRoot:c?.treeState?.claimsRoot,revocationRoot:c?.treeState?.revocationRoot,rootOfRoots:c?.treeState?.rootOfRoots}),u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let f=await this._identityWallet.signChallenge(i.challenge,a.credential);u.signature=f,u.challenge=i.challenge;let m=o[0];return u.query=m,u.claim={issuerID:s.issuerId,claim:s.claim,incProof:{proof:s.proof,treeState:s.treeState},nonRevProof:s.nonRevProof},u.currentTimeStamp=Ct(new Date),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation,this.checkOperatorSupport(r.circuitId,m.operator),u.inputsMarshal()};credentialAtomicQuerySigV2PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a=new sE;a.id=ve.idFromDID(t),a.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},a.requestID=BigInt(r.id),a.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),a.profileNonce=BigInt(i.authProfileNonce),a.skipClaimRevocationCheck=i.skipRevocation;let c=o[0];return c.operator=this.transformV2QueryOperator(c.operator),a.query=c,a.currentTimeStamp=Ct(new Date),this.checkOperatorSupport(r.circuitId,c.operator),a.inputsMarshal()};credentialAtomicQuerySigV2OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e),a=await this.prepareAuthBJJCredential(t),c=await this.newCircuitClaimData({credential:a.credential,credentialCoreClaim:a.coreClaim});s.nonRevProof=Hu(e.revStatus);let u=new fE,l=ve.idFromDID(t);u.id=l,u.claim={issuerID:s.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let d=o[0];u.query=d,u.currentTimeStamp=Ct(new Date),c.treeState&&(u.treeState={state:c.treeState?.state,claimsRoot:c.treeState?.claimsRoot,revocationRoot:c.treeState?.revocationRoot,rootOfRoots:c.treeState?.rootOfRoots});let h=await this._stateStorage.getGISTProof(l.bigInt()),f=mh(h);if(u.gistProof=f,u.authClaim=c.claim,u.authClaimIncMtp=c.proof,u.authClaimNonRevMtp=a.nonRevProof.proof,!i.challenge)throw new Error("challenge must be provided for onchain circuits");let m=await this._identityWallet.signChallenge(i.challenge,a.credential);return u.signature=m,u.challenge=i.challenge,this.checkOperatorSupport(r.circuitId,d.operator),u.inputsMarshal()};credentialAtomicQueryV3PrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=await this.newCircuitClaimData(e);s.nonRevProof=Hu(e.revStatus);let a;switch(r.query.proofType){case"BJJSignature2021":a="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":a="Iden3SparseMerkleTreeProof";break;default:if(s.proof)a="Iden3SparseMerkleTreeProof";else if(s.signatureProof)a="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let c=new cE;c.id=ve.idFromDID(t),c.claim={issuerID:s?.issuerId,signatureProof:s.signatureProof,claim:s.claim,nonRevProof:s.nonRevProof,incProof:{proof:s.proof,treeState:s.treeState}},c.requestID=BigInt(r.id),c.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),c.profileNonce=BigInt(i.authProfileNonce),c.skipClaimRevocationCheck=i.skipRevocation;let u=o[0];return u.values=[16,0].includes(u.operator)?[]:u.values,c.query=u,c.currentTimeStamp=Ct(new Date),c.proofType=a,c.linkNonce=i.linkNonce??BigInt(0),c.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,c.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0),this.checkOperatorSupport(r.circuitId,u.operator),c.inputsMarshal()};credentialAtomicQueryV3OnChainPrepareInputs=async({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})=>{let s=ve.idFromDID(t),a=await this.newCircuitClaimData(e);a.nonRevProof=Hu(e.revStatus);let c;switch(r.query.proofType){case"BJJSignature2021":c="BJJSignature2021";break;case"Iden3SparseMerkleTreeProof":c="Iden3SparseMerkleTreeProof";break;default:if(a.proof)c="Iden3SparseMerkleTreeProof";else if(a.signatureProof)c="BJJSignature2021";else throw Error("claim has no MTP or signature proof");break}let u=new lE;u.id=ve.idFromDID(t),u.claim={issuerID:a?.issuerId,signatureProof:a.signatureProof,claim:a.claim,nonRevProof:a.nonRevProof,incProof:{proof:a.proof,treeState:a.treeState}},u.requestID=BigInt(r.id),u.claimSubjectProfileNonce=BigInt(i.credentialSubjectProfileNonce),u.profileNonce=BigInt(i.authProfileNonce),u.skipClaimRevocationCheck=i.skipRevocation;let l=o[0];l.values=[16,0].includes(l.operator)?[]:l.values,u.query=l,u.currentTimeStamp=Ct(new Date),u.proofType=c,u.linkNonce=i.linkNonce??BigInt(0),u.verifierID=i.verifierDid?ve.idFromDID(i.verifierDid):void 0,u.nullifierSessionID=r.params?.nullifierSessionId?BigInt(r.params?.nullifierSessionId?.toString()):BigInt(0);let d=lp(t);u.isBJJAuthEnabled=d?0:1,u.challenge=BigInt(i.challenge??0);let h=await this._stateStorage.getGISTProof(s.bigInt()),f=mh(h);if(u.gistProof=f,u.isBJJAuthEnabled===1){let m=await this.prepareAuthBJJCredential(t),b=await this.newCircuitClaimData({credential:m.credential,credentialCoreClaim:m.coreClaim}),w=await this._identityWallet.signChallenge(u.challenge,m.credential);u.authClaim=b.claim,u.authClaimIncMtp=b.proof,u.authClaimNonRevMtp=m.nonRevProof.proof,u.treeState=b.treeState,u.signature=w}return this.checkOperatorSupport(r.circuitId,l.operator),u.inputsMarshal()};linkedMultiQuery10PrepareInputs=async({preparedCredential:e,params:t,proofReq:r,circuitQueries:i})=>{let o=await this.newCircuitClaimData(e);o.nonRevProof=Hu(e.revStatus);let s=new id;return s.linkNonce=t.linkNonce??BigInt(0),s.claim=o.claim,s.query=i,i.forEach(a=>{this.checkOperatorSupport(r.circuitId,a.operator)}),i.forEach(a=>{a.values=[16,0].includes(a.operator)?[]:a.values}),s.inputsMarshal()};transformV2QueryOperator(e){return e===16||e===0?1:e}checkOperatorSupport(e,t){if(!gh[e].supportedOperations.includes(t))throw new Error(`operator ${$1(t)} is not supported by ${e}`)}};var NRe=1440*60*1e3;async function t8(n,e,t,r,i,o,s){let a=ve.parseFromId(r.issuerId);if(!(!n.allowedIssuers||n.allowedIssuers?.some(f=>f==="*"||f===a.string())))throw new Error("issuer is not in allowed list");if(!n.type)throw new Error("query type is missing");let u=await Nr.getTypeIDFromContext(JSON.stringify(t),n.type,{documentLoader:o});if(Yl(Me.encode(u)).bigInt()!==r.schemaHash.bigInt())throw new Error("schema that was used is not equal to requested in query");if(!n.skipClaimRevocationCheck&&r.isRevocationChecked===0)throw new Error("check revocation is required");Kee(i,e);let d=NRe;if(s?.acceptedProofGenerationDelay&&(d=s.acceptedProofGenerationDelay),Date.now()-ra(Number(r.timestamp)).getTime()>d)throw new Error("generated proof is outdated")}function Kee(n,e){let t=gh[n];if(e.length>t.maxQueriesCount)throw new Error(`circuit ${n} supports only ${gh[n].maxQueriesCount} queries`)}function n8(n,e){if(!gh[n].supportedOperations.includes(e))throw new Error(`circuit ${n} not support ${$1(e)} operator`)}function sF(n,e){if(n.operator!=fn.$noop){if(n.merklized===1){if(n.claimPathNotExists===1)throw new Error("proof doesn't contains target query key");if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}function aF(n,e){if(n.operator!=0){if(n.operator===11&&!n.merklized)throw new Error("$exists operator is not supported for non-merklized credential");if(n.merklized===1){if(n.claimPathKey!==e.claimPathKey)throw new Error("proof was generated for another path")}else if(n.slotIndex!==e.slotIndex)throw new Error("wrong claim slot was used in claim")}}async function cF(n,e){if(e.operator!==1)throw new Error("empty credentialSubject request available only for equal operation");for(let i=1;i<e.value.length;i++)if(e.value[i]!==0n)throw new Error("empty credentialSubject request not available for array of values");let r=await Nr.newPath([qe.CREDENTIAL_SUBJECT_PATH]).mtEntry();if(e.claimPathKey!==r)throw new Error("proof doesn't contain credentialSubject in claimPathKey")}async function r8(n,e){if(e.operator!==n.operator)throw new Error("operator that was used is not equal to request");if(e.operator!==0){for(let t=0;t<e.value.length;t++)if(e.value[t]!==n.values[t]){if(e.value[t]===0n&&n.values[t]===void 0)continue;throw new Error("comparison value that was used is not equal to requested in query")}}}async function uF(n,e,t,r){if(await sI(n.fieldName,t,r)!==e.value[0])throw new Error("value that was used is not equal to requested in query");if(e.operator!==1)throw new Error("operator for selective disclosure must be $eq");for(let o=1;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("selective disclosure not available for array of values")}async function lF(n,e,t,r){if(await sI(n.fieldName,t,r)!==e.operatorOutput)throw new Error("operator output should be equal to disclosed value");if(e.operator!==16)throw new Error("operator for selective disclosure must be $sd");for(let o=0;o<e.value.length;o++)if(e.value[o]!==0n)throw new Error("public signal values must be zero")}async function dF(n){if(n.operator!==0)throw new Error("empty credentialSubject request available only for $noop operation");for(let e=1;e<n.value.length;e++)if(n.value[e]!==0n)throw new Error("empty credentialSubject request not available for array of values")}var sI=async(n,e,t)=>{if(!e)throw new Error("verifiablePresentation is required for selective disclosure request");let r,i=JSON.stringify(e);try{r=await Cu.merklizeJSONLD(i,{documentLoader:t})}catch{throw new Error("can't merklize verifiablePresentation")}let o;try{let c=`verifiableCredential.credentialSubject.${n}`;o=await Nr.fromDocument(null,i,c,{documentLoader:t})}catch{throw new Error(`can't build path to '${n}' key`)}let s,a;try{({proof:s,value:a}=await r.proof(o))}catch{throw new Error(`can't get value by path '${n}'`)}if(!a)throw new Error(`can't get merkle value for field '${n}'`);if(!s.existence)throw new Error(`path [${o.parts}] doesn't exist in verifiablePresentation document`);return await a.mtEntry()};function URe(n){let e=Array(n.length).fill("uint256");return BigInt(nn.keccak256(nn.solidityPacked(e,n)))&BigInt("0x0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")}function GRe(n,e){return(BigInt(nn.keccak256(nn.solidityPacked(["bytes","address"],[n,e])))&BigInt("0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"))+BigInt("0x0001000000000000000000000000000000000000000000000000000000000000")}function KRe(n,e,t){return BigInt(nn.keccak256(nn.solidityPacked(["uint256[]","uint256[]","address"],[n,e,t])))}function HRe(n,e,t,r,i,o){let s=Yr(n,64),a=On.spongeHashX(s,6);return On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(o),a])}function fF(n,e,t,r,i,o,s,a,c,u){let l=Yr(n,jS),d=On.spongeHashX(l,6),h=On.hash([e.bigInt(),BigInt(t),BigInt(r),BigInt(i),BigInt(s),d]);return On.hash([h,BigInt(o),BigInt(a),BigInt(c),BigInt(u),0n])}var JRe=new Error("user state is not valid"),i8=0n,aI=class{constructor(e,t){this._documentLoader=e;this._stateStorage=t}async verify(e,t){let r=`${e.split("-")[0]}Verify`,i=this[r];if(!i)throw new Error(`public signals verifier for ${e} not found`);return i(t)}credentialAtomicQueryMTPV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new rE;if(a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o))),!a.userID)throw new Error("user id is not presented in proof public signals");if(!a.requestID)throw new Error("requestId is not presented in proof public signals");let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQueryMTPV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerClaimIdenState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQuerySigV2Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s})=>{let a=new aE;a=a.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let c={issuerId:a.issuerID,schemaHash:a.claimSchema,slotIndex:a.slotIndex,operator:a.operator,value:a.value,timestamp:a.timestamp,merklized:a.merklized,claimPathKey:a.claimPathKey,claimPathNotExists:a.claimPathNotExists,valueArraySize:a.getValueArrSize(),isRevocationChecked:a.isRevocationChecked};return await this.checkQueryV2Circuits("credentialAtomicQuerySigV2",e,c,s,t),await this.checkStateExistenceForId(a.issuerID,a.issuerAuthState),a.isRevocationChecked!==0&&await this.checkRevocationState(a.issuerID,a.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,a.userID,a.requestID),a};credentialAtomicQueryV3Verify=async({query:e,verifiablePresentation:t,sender:r,challenge:i,pubSignals:o,opts:s,params:a})=>{let c=new uE;c=c.pubSignalsUnmarshal(Me.encode(JSON.stringify(o)));let u={issuerId:c.issuerID,schemaHash:c.claimSchema,slotIndex:c.slotIndex,operator:c.operator,value:c.value,timestamp:c.timestamp,merklized:c.merklized,claimPathKey:c.claimPathKey,valueArraySize:c.getValueArrSize(),operatorOutput:c.operatorOutput,isRevocationChecked:c.isRevocationChecked};if(!e.type)throw new Error("proof query type is undefined");let l=this._documentLoader??Ho(),d;try{d=(await l(e.context??"")).document}catch{throw new Error("can't load schema for request query")}let h=await iI(e.type,JSON.stringify(d),e.credentialSubject,{documentLoader:l}),f="credentialAtomicQueryV3-beta.1";await t8(e,h,d,u,f,this._documentLoader,s);let m=h[0];if(n8(f,u.operator),m.operator===16)try{await lF(m,u,t,l)}catch(K){throw new Error(`failed to validate selective disclosure: ${K.message}`)}else if(!m.fieldName&&m.operator==0)try{await dF(u)}catch(K){throw new Error(`failed to validate operators: ${K.message}`)}else try{await r8(m,u)}catch(K){throw new Error(`failed to validate operators: ${K.message}`)}aF(u,m);let{proofType:b,verifierID:w,nullifier:S,nullifierSessionID:T,linkID:G}=c;switch(e.proofType){case"BJJSignature2021":if(b!==1)throw new Error("wrong proof type for BJJSignature");break;case"Iden3SparseMerkleTreeProof":if(b!==2)throw new Error("wrong proof type for Iden3SparseMerkleTreeProof");break;default:}let U=BigInt(a?.nullifierSessionId??0);if(U!==0n){if(BigInt(S??0)===0n)throw new Error("nullifier should be provided for nullification and should not be 0");let K=a?.verifierDid;if(!K)throw new Error("verifierDid is required");let M=ve.idFromDID(K);if(w.bigInt()!=M.bigInt())throw new Error("wrong verifier is used for nullification");if(T!==U)throw new Error(`wrong verifier session id is used for nullification, expected ${U}, got ${T}`)}else if(T!==0n)throw new Error("Nullifier id is generated but wasn't requested");if(!e.groupId&&G!==0n)throw new Error("proof contains link id, but group id is not provided");if(e.groupId&&G===0n)throw new Error("proof doesn't contain link id, but group id is provided");return await this.checkStateExistenceForId(c.issuerID,c.issuerState),c.isRevocationChecked!==0&&await this.checkRevocationState(c.issuerID,c.issuerClaimNonRevState,s),this.verifyIdOwnership(r,i,c.userID,c.requestID),c};authV2Verify=async({sender:e,challenge:t,pubSignals:r,opts:i})=>{let o=new Xs;o=o.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let s=await this.checkGlobalState(o.GISTRoot,o.userID),a=Wr.DEFAULT_AUTH_VERIFY_DELAY;if(i?.acceptedStateTransitionDelay&&(a=i.acceptedStateTransitionDelay),!s.latest&&Date.now()-ra(Number(s.transitionTimestamp)).getTime()>a)throw new Error("global state is outdated");return this.verifyIdOwnership(e,t,o.userID,o.challenge),new kn};linkedMultiQuery10Verify=async({query:e,verifiablePresentation:t,pubSignals:r})=>{let i=new gE;i=i.pubSignalsUnmarshal(Me.encode(JSON.stringify(r)));let o,s={documentLoader:this._documentLoader};try{o=(await s.documentLoader(e.context||"")).document}catch{throw new Error("can't load schema for request query")}let a=JSON.stringify(o),c=e.credentialSubject,u=await Nr.getTypeIDFromContext(a,e.type||"",s),l=Yl(Me.encode(u)),d=await iI(e.type||"",a,c,s),h=[],f=d[0]?.merklizedSchema?1:0;for(let w=0;w<id.queryCount;w++){let S=d[w],T=S?.values??[],G=T.length,U=fF(T,l,S?.slotIndex??0,S?.operator??0,S?.claimPathKey.toString()??0,G,f,0,0,0);h.push({queryHash:U,queryMeta:S})}let m=(w,S)=>w.queryHash<S.queryHash?-1:w.queryHash>S.queryHash?1:0,b=i.circuitQueryHash.map((w,S)=>({queryHash:w,operatorOutput:i.operatorOutput[S]}));b.sort(m),h.sort(m);for(let w=0;w<id.queryCount;w++){if(h[w].queryHash!=b[w].queryHash)throw new Error("query hashes do not match");if(h[w].queryMeta?.operator===16&&await sI(h[w].queryMeta.fieldName,t,this._documentLoader)!=b[w].operatorOutput)throw new Error("disclosed value is not in the proof outputs")}return i};verifyIdOwnership=(e,t,r,i)=>{if(ve.idFromDID(ve.parse(e)).string()!==r.string())throw new Error(`sender id is not used for proof creation, expected ${e}, user from public signals: ${r.string()}`);if(t!==i)throw new Error(`challenge is not used for proof creation, expected ${t}, challenge from public signals: ${i} `)};async checkQueryV2Circuits(e,t,r,i,o){if(!t.type)throw new Error("proof query type is undefined");let s=this._documentLoader??Ho(),a;try{a=(await s(t.context??"")).document}catch{throw new Error("can't load schema for request query")}let c=await iI(t.type,JSON.stringify(a),t.credentialSubject,{documentLoader:s});await t8(t,c,a,r,e,this._documentLoader,i);let u=c[0];if(n8(e,r.operator),u.operator===16)try{await uF(u,r,o,s)}catch(l){throw new Error(`failed to validate selective disclosure: ${l.message}`)}else if(!u.fieldName&&u.operator==0)try{await cF(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}else try{await r8(u,r)}catch(l){throw new Error(`failed to validate operators: ${l.message}`)}sF(r,u)}async resolve(e,t){let r=e.bigInt(),i=ve.parseFromId(e),o=nu(i,t),s;try{s=await this._stateStorage.getStateInfoByIdAndState(r,t)}catch(a){if(AO(a)){if(o)return{latest:!0,transitionTimestamp:0};throw new Error("State is not genesis and not registered in the smart contract")}throw a}if(!s.id||s.id.toString()!==r.toString())throw new Error("state was recorded for another identity");if(!s.state||s.state.toString()!==t.toString()){if(!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===i8.toString())throw new Error("no information about state transition");return{latest:!1,transitionTimestamp:s.replacedAtTimestamp.toString()}}return{latest:!s.replacedAtTimestamp||s.replacedAtTimestamp.toString()===i8.toString(),transitionTimestamp:s.replacedAtTimestamp?.toString()??0}}async rootResolve(e,t){let r;try{r=await this._stateStorage.getGISTRootInfo(e,t)}catch(i){throw xO(i)?new Error("GIST root does not exist in the smart contract"):i}if(r.root.toString()!==e.toString())throw new Error("gist info contains invalid state");if(r.replacedByRoot.toString()!==i8.toString()){if(r.replacedAtTimestamp.toString()===i8.toString())throw new Error("state was replaced, but replaced time unknown");return{latest:!1,transitionTimestamp:r.replacedAtTimestamp.toString()}}return{latest:!0,transitionTimestamp:0}}checkStateExistenceForId=async(e,t)=>{await this.resolve(e,t.bigInt())};checkGlobalState=async(e,t)=>this.rootResolve(e.bigInt(),t.bigInt());checkRevocationStateForId=async(e,t)=>await this.resolve(e,t.bigInt());checkRevocationState=async(e,t,r)=>{let i=await this.checkRevocationStateForId(e,t),o=r?.acceptedStateTransitionDelay??Wr.DEFAULT_PROOF_VERIFY_DELAY;if(!i.latest&&Date.now()-ra(Number(i.transitionTimestamp)).getTime()>o)throw new Error("issuer state is outdated")}};var hF=class{constructor(e,t,r,i,o){this._identityWallet=e;this._credentialWallet=t;this._stateStorage=i;this._prover=o?.prover??new oI(r),this._ldOptions={...o,documentLoader:o?.documentLoader??T0(o)},this._inputsGenerator=new Z0(e,t,i),this._pubSignalsVerifier=new aI(o?.documentLoader??T0(o),i)}_prover;_ldOptions;_inputsGenerator;_pubSignalsVerifier;async verifyProof(e,t){return this._prover.verify(e,t)}async verifyZKPResponse(e,t){if(!await this._prover.verify(e,e.circuitId))throw Error(`Proof with circuit id ${e.circuitId} and request id ${e.id} is not valid`);let i={pubSignals:e.pub_signals,query:t.query,verifiablePresentation:e.vp,sender:t.sender,challenge:BigInt(e.id),opts:t.opts,params:t.params};return{linkID:(await this._pubSignalsVerifier.verify(e.circuitId,i)).linkID}}async generateProof(e,t,r){r||(r={skipRevocation:!1,challenge:0n});let i={cred:r.credential,revStatus:r.credentialRevocationStatus};if(r.credential||(i=await this.findCredentialByProofQuery(t,e.query)),r.credential&&!r.credentialRevocationStatus&&!r.skipRevocation){let j=await this._credentialWallet.getRevocationStatusFromCredential(r.credential);i={cred:r.credential,revStatus:j}}if(!i.cred)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+` ${JSON.stringify(e.query)}`);let o=await this._identityWallet.getCoreClaimFromCredential(i.cred),{nonce:s,genesisDID:a}=await this._identityWallet.getGenesisDIDMetadata(t),c={credential:i.cred,credentialCoreClaim:o,revStatus:i.revStatus},u=ve.parse(c.credential.credentialSubject.id),{nonce:l,genesisDID:d}=await this._identityWallet.getGenesisDIDMetadata(u);if(d.string()!==a.string())throw new Error(qe.ERRORS.PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH);let h=_C(e.query.credentialSubject);if(!h.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST);let f=c.credentialCoreClaim.getMerklizedPosition(),m;f!==jn.None&&(m=await c.credential.merklize(this._ldOptions));let b=e.query.context,w=e.query.groupId,S=await this.loadLdContext(b),T=e.query.type,G=[],U=[];for(let j of h){let Y=await $C(j,lt.decode(S),T,this._ldOptions);G.push(Y);let Q=await this.toCircuitsQuery(c.credential,Y,m);U.push(Q)}let K=await this.generateInputs(c,a,e,{...r,authProfileNonce:s,credentialSubjectProfileNonce:l,linkNonce:w?r.linkNonce:0n},U),M=G.filter(j=>j.operator===16),A;M.length&&(A=VT(b,T,c.credential,M));let{proof:D,pub_signals:z}=await this._prover.generate(K,e.circuitId);return{id:e.id,circuitId:e.circuitId,vp:A,proof:D,pub_signals:z}}async generateAuthProof(e,t,r){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error("CircuitId is not supported");r||(r={challenge:0n});let i=r.challenge?vt.intToBytes(r.challenge).reverse():new Uint8Array(32),o=await this.generateAuthInputs(i,t,e),s=await this._prover.generate(o,e);return{circuitId:e,proof:s.proof,pub_signals:s.pub_signals}}async transitState(e,t,r,i,o){return this._identityWallet.transitState(e,t,r,o,this._prover)}async generateInputs(e,t,r,i,o){return this._inputsGenerator.generateInputs({preparedCredential:e,identifier:t,proofReq:r,params:i,circuitQueries:o})}async toCircuitsQuery(e,t,r){if(t.merklizedSchema&&!r)throw new Error("merklized root position is set to None for merklized schema");if(!t.merklizedSchema&&r)throw new Error("merklized root position is not set to None for non-merklized schema");let i=new eE;if(i.slotIndex=t.slotIndex,i.operator=t.operator,i.values=t.values,t.merklizedSchema&&r){let{proof:o,value:s}=await r.proof(t.path);i.valueProof=new jr,i.valueProof.mtp=o,i.valueProof.path=t.claimPathKey;let a=await s?.mtEntry()??0n;if(i.valueProof.value=a,!t.fieldName)return i.values=[a],i}if(t.operator===16){let[o,...s]=t.fieldName.split("."),a=e.credentialSubject[o];for(let c of s)a=a[c];if(typeof a>"u")throw new Error(`credential doesn't contain value for field ${t.fieldName}`);i.values=await e8(a,t.datatype)}return i}async loadLdContext(e){let t=Ho(this._ldOptions),r;try{r=(await t(e)).document}catch{throw new Error(`can't load ld context from url ${e}`)}return Me.encode(JSON.stringify(r))}async generateAuthV2Inputs(e,t,r){if(r!=="authV2")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=mh(l),h=new k0;return h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthInputs(e,t,r){if(r!=="authV2"&&r!=="authV3"&&r!=="authV3-8-32")throw new Error("CircuitId is not supported");let{nonce:i,genesisDID:o}=await this._identityWallet.getGenesisDIDMetadata(t),s=vt.bytesToInt(e.reverse()),a=await this._inputsGenerator.prepareAuthBJJCredential(o),c=await this._identityWallet.signChallenge(s,a.credential),u=ve.idFromDID(o),l=await this._stateStorage.getGISTProof(u.bigInt()),d=mh(l),h=new yE;return r==="authV3-8-32"&&(h.mtLevel=8,h.mtLevelOnChain=32),h.genesisID=u,h.profileNonce=BigInt(i),h.authClaim=a.coreClaim,h.authClaimIncMtp=a.incProof.proof,h.authClaimNonRevMtp=a.nonRevProof.proof,h.treeState=a.incProof.treeState,h.signature=c,h.challenge=s,h.gistProof=d,h.inputsMarshal()}async generateAuthV2Proof(e,t){let r=await this.generateAuthInputs(e,t,"authV2");return await this._prover.generate(r,"authV2")}async verifyState(e,t,r={acceptedStateTransitionDelay:Wr.DEFAULT_AUTH_VERIFY_DELAY}){if(e!=="authV2"&&e!=="authV3"&&e!=="authV3-8-32")throw new Error(`CircuitId is not supported ${e}`);let i,o;if(e==="authV2"){let a=new Xs().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}else{let a=new M0().pubSignalsUnmarshal(Me.encode(JSON.stringify(t)));i=a.GISTRoot.bigInt(),o=a.userID.bigInt()}let s=await this._stateStorage.getGISTRootInfo(i,o);if(s.root!==i)throw new Error("gist info contains invalid state");if(s.replacedByRoot!==0n){if(s.replacedAtTimestamp===0n)throw new Error("state was replaced, but replaced time unknown");if(Date.now()-ra(Number(s.replacedAtTimestamp)).getTime()>(r?.acceptedStateTransitionDelay??Wr.DEFAULT_AUTH_VERIFY_DELAY))throw new Error("global state is outdated")}return!0}async findCredentialByProofQuery(e,t){let r=await this._identityWallet.findOwnedCredentialsByDID(e,t);if(!r.length)throw new Error(qe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE);return t.skipClaimRevocationCheck?{cred:r[0],revStatus:void 0}:await this._credentialWallet.findNonRevokedCredential(r)}};var pF=class{constructor(e,t,r,i){this._kms=e;this._storage=t;this._credentialWallet=r;this._opts=i;this._credentialStatusPublisherRegistry=this.getCredentialStatusPublisherRegistry(i),this._inputsGenerator=new Z0(this,r,t.states),this._transactionService=new _s(t.states.getRpcProvider())}_credentialStatusPublisherRegistry;_inputsGenerator;_transactionService;get credentialWallet(){return this._credentialWallet}getCredentialStatusPublisherRegistry(e){if(e?.credentialStatusPublisherRegistry)return this._opts?.credentialStatusPublisherRegistry;{let t=new nI,r={publish:()=>Promise.resolve()};return t.register("Iden3ReverseSparseMerkleTreeProof",new W0),t.register("SparseMerkleTreeProof",r),t.register("Iden3commRevocationStatusV1.0",r),t}}async createAuthCoreClaim(e,t){let r=await this._kms.createKeyFromSeed("BJJ",t),i=await this._kms.publicKey(r),o=Vu.newFromHex(i),s=$o.authSchemaHash,a=Mr.newClaim(s,za.withIndexDataInts(o.p[0],o.p[1]),za.withRevocationNonce(BigInt(0)));return a.setRevocationNonce(BigInt(e)),{authClaim:a,pubKey:o}}async createAuthBJJCredential(e,t,r,i,o){let s=r.getExpirationDate(),a=s?Ct(s):0,c={credentialSchema:qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL,type:qe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,credentialSubject:{x:t.p[0].toString(),y:t.p[1].toString()},subjectPosition:HP(r.getIdPosition()),version:0,expiration:a,revocationOpts:{nonce:Number(r.getRevocationNonce()),id:o.id.replace(/\/$/,""),type:o.type,issuerState:i.hex()}},u=await this._credentialWallet.getAllAuthBJJCredentials(e),l=new Ur;if(u.length===0){let d=JSON.parse(qe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSON);try{l=this._credentialWallet.createCredential(e,c,d)}catch(h){throw new Error(`Error create w3c credential ${h.message}`)}}else l=await this.issueCredential(e,c);return l}async createIdentity(e){let t=e.seed?XP(Pn.encode(Qu(e.seed)),qP):Ft();e.seed=e.seed??Gc(32),await this._storage.mt.createIdentityMerkleTrees(t);let r=e.revocationOpts.nonce??0,{authClaim:i,pubKey:o}=await this.createAuthCoreClaim(r,e.seed),{hi:s,hv:a}=i.hiHv();await this._storage.mt.addToMerkleTree(t,0,s,a);let c=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),u=await c.root(),l=Eh([u.bigInt(),Ne.bigInt(),Ne.bigInt()]),d=Jc(e.method||Ni.Iden3,e.blockchain||Ht.Polygon,e.networkId||Jt.Amoy),h=$e.idGenesisFromIdenState(d,l.bigInt()),f=ve.parseFromId(h);await this._storage.mt.bindMerkleTreeToNewIdentifier(t,f.string());let m={revocationRoot:Ne,claimsRoot:u,state:l,rootOfRoots:Ne};await this._storage.identity.getIdentity(f.string())||await this._storage.identity.saveIdentity({did:f.string(),state:l,isStatePublished:!1,isStateGenesis:!0});let w=await this._credentialWallet.findByQuery({credentialSubject:{x:{$eq:o.p[0].toString()},y:{$eq:o.p[1].toString()}},allowedIssuers:[f.string()]});if(w.length===1&&w[0].credentialStatus.type===e.revocationOpts.type)return{did:f,credential:w[0]};for(let K=0;K<w.length;K++)await this._credentialWallet.remove(w[K].id);let S=await this.createAuthBJJCredential(f,o,i,l,e.revocationOpts),T=i.hIndex(),{proof:G}=await c.generateProof(T,u),U=new mc({mtp:G,issuerData:{id:f,state:{rootOfRoots:m.rootOfRoots,revocationTreeRoot:m.revocationRoot,claimsTreeRoot:u,value:l}},coreClaim:i});return S.proof=[U],e.revocationOpts.genesisPublishingDisabled||await this.publishRevocationInfoByCredentialStatusType(f,e.revocationOpts.type,{rhsUrl:e.revocationOpts.id,onChain:e.revocationOpts.onChain}),await this._credentialWallet.save(S),{did:f,credential:S}}async createEthereumBasedIdentity(e){e.seed=e.seed??Gc(32),e.createBjjCredential=e.createBjjCredential??!0;let t,r=e.ethSigner;if(e.createBjjCredential&&!r)throw new Error(qe.ERRORS.ID_WALLET_SIGNER_IS_REQUIRED);let i=Ne,o=Jc(e.method||Ni.Iden3,e.blockchain||Ht.Polygon,e.networkId||Jt.Amoy),s=await this._kms.createKeyFromSeed("Secp256k1",e.seed),a=(await this._kms.publicKey(s)).slice(2),c=e4(o,a);if(await this._storage.mt.createIdentityMerkleTrees(c.string()),await this._storage.identity.saveIdentity({did:c.string(),state:i,isStatePublished:!1,isStateGenesis:!0}),e.createBjjCredential&&r){let u={revocationRoot:Ne,claimsRoot:Ne,state:i,rootOfRoots:Ne};t=await this.addBJJAuthCredential(c,u,!0,r,e)}return{did:c,credential:t}}async getGenesisDIDMetadata(e){let t=await this._storage.identity.getIdentity(e.string());if(t)return{nonce:0,genesisDID:ve.parse(t.did)};let r=await this._storage.identity.getProfileById(e.string());if(!r)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND);return{nonce:r.nonce,genesisDID:ve.parse(r.genesisIdentifier)}}async createProfile(e,t,r,i){let o=JP(e,t),s=Array.isArray(i),a=s?i:i?.tags,{didDocument:c,encryptionKeyOps:u}=s?{}:i??{},l=await this._storage.identity.getProfilesByGenesisIdentifier(e.string());if((await this._storage.identity.getProfilesByVerifier(r,a)).length)throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS);if(l.find(m=>m.nonce==t))throw new Error(qe.ERRORS.ID_WALLET_PROFILE_ALREADY_EXISTS);let f=c;if(u?.provider){let m=new vE(u.provider,{alias:u.alias});if(!f)f=(await new xE(o.string()).addVerificationMethod(m,iC)).build();else{let b=await m.build(o.string()),w=[f["@context"]].flat().filter(S=>typeof S=="string");f={...f,verificationMethod:[...f.verificationMethod??[],b],"@context":[...new Set([...w,iC])]}}}return await this._storage.identity.saveProfile({id:o.string(),nonce:t,genesisIdentifier:e.string(),verifier:r,tags:a,did_doc:f}),o}async getProfilesByDID(e){return this._storage.identity.getProfilesByGenesisIdentifier(e.string())}async generateKey(e){return await this._kms.createKeyFromSeed(e,Gc(32))}async getProfileByVerifier(e){return this._storage.identity.getProfileByVerifier(e)}async getProfilesByVerifier(e,t){return this._storage.identity.getProfilesByVerifier(e,t)}async getDIDTreeModel(e){let t=e.string(),r=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,0),i=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,1),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(t,2);return{state:Eh([(await r.root()).bigInt(),(await i.root()).bigInt(),(await o.root()).bigInt()]),claimsTree:r,revocationTree:i,rootsTree:o}}async generateCredentialMtp(e,t,r){let i=await this.getCoreClaimFromCredential(t);return this.generateCoreClaimMtp(e,i,r)}async generateCoreClaimMtp(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t.hIndex(),r?r.claimsRoot:s);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async generateNonRevocationMtp(e,t,r){let o=(await this.getCoreClaimFromCredential(t)).getRevocationNonce();return this.generateNonRevocationMtpWithNonce(e,o,r)}async generateNonRevocationMtpWithNonce(e,t,r){let i=await this.getDIDTreeModel(e),o=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),1),s=await i.claimsTree.root(),a=await i.rootsTree.root(),c=await i.revocationTree.root(),{proof:u}=await o.generateProof(t,r?r.revocationRoot:c);return{proof:u,treeState:r??{state:i.state,claimsRoot:s,rootOfRoots:a,revocationRoot:c}}}async sign(e,t){let r=Jv(t),i=On.hashBytes(e),o=await this._kms.sign(r,vt.intToBytes(i));return Ld.newFromCompressed(o)}async signChallenge(e,t){let r=Jv(t),i=await this._kms.sign(r,vt.intToBytes(e));return Ld.newFromCompressed(i)}async issueCredential(e,t,r){t.revocationOpts.id=t.revocationOpts.id.replace(/\/$/,"");let i,o=r?.documentLoader??T0(r);try{i=(await o(t.credentialSchema)).document}catch{throw new Error(`can't load credential schema ${t.credentialSchema}`)}let s=i,a=new Ur,c=await this.getDIDTreeModel(e);t.revocationOpts.issuerState=c.state.hex(),t.revocationOpts.nonce=typeof t.revocationOpts.nonce=="number"?t.revocationOpts.nonce:new DataView(Gc(16).buffer).getUint32(0,!1),t.subjectPosition=t.subjectPosition??"index";try{a=this._credentialWallet.createCredential(e,t,s);let T=Me.encode(JSON.stringify(a)),G=Me.encode(JSON.stringify(i));await new _1().validate(T,G)}catch(T){throw new Error(`Error create w3c credential ${T.message}`)}let{authCredential:u}=await this.getActualAuthCredential(e),l={revNonce:t.revocationOpts.nonce,subjectPosition:t.subjectPosition,merklizedRootPosition:t.merklizedRootPosition??"",updatable:!1,version:0,merklizeOpts:{...r,documentLoader:o}},d=await a.toCoreClaim(l),{hi:h,hv:f}=d.hiHv(),m=On.hash([h,f]),b=await this.signChallenge(m,u);if(!u.proof)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF);let w=u.getIden3SparseMerkleTreeProof();if(!w)throw new Error(qe.ERRORS.ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF);let S=new wf({issuerData:{id:e,state:w.issuerData.state,authCoreClaim:w.coreClaim,mtp:w.mtp,credentialStatus:u.credentialStatus},coreClaim:d,signature:b});return a.proof=[S],a}async getActualAuthCredential(e,t){let r=await this._credentialWallet.getAllAuthBJJCredentials(e);for(let i=0;i<r.length;i++){let o=await this.generateCredentialMtp(e,r[i],t);if(!o.proof.existence)continue;let s=await this.generateNonRevocationMtp(e,r[i],t);if(!s.proof.existence)return{authCredential:r[i],incProof:o,nonRevProof:s}}throw new Error(qe.ERRORS.NO_AUTH_CRED_FOUND)}async revokeCredential(e,t){let r=await this.getDIDTreeModel(e),i=await this.getCoreClaimFromCredential(t);if(!i)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF);let o=i.getRevocationNonce();return await r.revocationTree.add(o,BigInt(0)),Number(BigInt.asUintN(64,o))}async addCredentialsToMerkleTree(e,t){let r=await this.getDIDTreeModel(t),i=await r.claimsTree.root(),o=await r.rootsTree.root(),s=await r.revocationTree.root(),a={state:r.state,claimsRoot:i,revocationRoot:s,rootOfRoots:o};for(let d=0;d<e.length;d++){let f=e[d].getCoreClaimFromProof("BJJSignature2021");if(!f)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);await this._storage.mt.addToMerkleTree(t.string(),0,f.hIndex(),f.hValue())}let u=await(await this.getDIDTreeModel(t)).claimsTree.root();await this._storage.mt.addToMerkleTree(t.string(),2,u.bigInt(),BigInt(0));let l=await this.getDIDTreeModel(t);return i=await l.claimsTree.root(),o=await l.rootsTree.root(),s=await l.revocationTree.root(),{credentials:e,newTreeState:{state:l.state,claimsRoot:i,rootOfRoots:o,revocationRoot:s},oldTreeState:a}}async generateIden3SparseMerkleTreeProof(e,t,r,i,o,s,a){for(let c=0;c<t.length;c++){let u=t[c],l=u.getCoreClaimFromProof("BJJSignature2021")||await u.toCoreClaim(a);if(!l)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF);let d=await this.generateCoreClaimMtp(e,l,s),h=new mc({mtp:d.proof,issuerData:{id:e,state:{claimsTreeRoot:d.treeState.claimsRoot,revocationTreeRoot:d.treeState.revocationRoot,rootOfRoots:d.treeState.rootOfRoots,value:d.treeState.state,txId:r,blockNumber:i,blockTimestamp:o}},coreClaim:l});Array.isArray(t[c].proof)?t[c].proof.push(h):t[c].proof=t[c].proof?[t[c].proof,h]:[h]}return t}async publishSpecificStateToRHS(e,t,r){await ZC(e.state,e,t,r)}async publishStateToRHS(e,t,r){let i=await this.getDIDTreeModel(e);await ZC(i.state,{revocationTree:i.revocationTree,claimsTree:i.claimsTree,state:i.state,rootsTree:i.rootsTree},t,r)}async publishRevocationInfoByCredentialStatusType(e,t,r){let i=this._credentialStatusPublisherRegistry.get(t);if(!i)throw new Error(`there is no registered publisher to save hash is not registered for ${t} is not registered`);let o=[],s=r?.treeModel??await this.getDIDTreeModel(e);if(o=await XC(r?.revokedNonces??[],{revocationTree:s.revocationTree,claimsTree:s.claimsTree,state:s.state,rootsTree:s.rootsTree},s.state),!o.length)return;let a=i.map(c=>c.publish({nodes:o,...r,credentialStatusType:t,issuerDID:e}));await Promise.all(a)}async getCoreClaimFromCredential(e){let t=e.getCoreClaimFromProof("BJJSignature2021"),r=e.getCoreClaimFromProof("Iden3SparseMerkleTreeProof");if(r&&t&&r.hex()!==t.hex())throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_MISMATCH);if(!r&&!t)throw new Error(qe.ERRORS.ID_WALLET_CORE_CLAIM_IS_NOT_SET);return r??t}async findOwnedCredentialsByDID(e,t){let r=await this._credentialWallet.findByQuery(t);if(!r.length)throw new Error(qe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY);let{genesisDID:i}=await this.getGenesisDIDMetadata(e),o=await this.getProfilesByDID(i);return r.filter(s=>{let a=s.credentialSubject.id;return a==i.string()||o.some(c=>c.id===a)})}async updateIdentityState(e,t,r){let i=await this.getDIDTreeModel(e);await this._storage.identity.saveIdentity({did:e.string(),state:r?.state??i.state,isStatePublished:t,isStateGenesis:!1})}async transitState(e,t,r,i,o){let s=await this.getDIDTreeModel(e),a=await s.claimsTree.root(),c=await s.rootsTree.root(),l={revocationRoot:await s.revocationTree.root(),claimsRoot:a,state:s.state,rootOfRoots:c},d=ve.idFromDID(e),h,f=lp(e),m;if(f){let b=t.state,w=l.state,S={userId:d,oldUserState:b,newUserState:w,isOldStateGenesis:r,methodId:BigInt(1),methodParams:"0x"};m=await this._storage.states.publishStateGeneric(i,S)}else{if(!o)throw new Error(qe.ERRORS.ID_WALLET_PROVER_IS_REQUIRED);let b=await this._inputsGenerator.prepareAuthBJJCredential(e,t),w=T8.hash([t.state.bigInt(),l.state.bigInt()]),S=await this.signChallenge(w,b.credential),T=new pE;T.id=d,T.signature=S,T.isOldStateGenesis=r;let G=await this.generateCredentialMtp(e,b.credential,l);T.newTreeState=G.treeState,T.authClaimNewStateIncProof=G.proof,T.oldTreeState=t,T.authClaim={claim:b.coreClaim,incProof:b.incProof,nonRevProof:b.nonRevProof};let U=T.inputsMarshal();h=await o.generate(U,"stateTransition"),m=await this._storage.states.publishState(h,i)}return await this.updateIdentityState(e,!0,l),m}async getAuthBJJCredential(e,t,{nonce:r,seed:i,id:o,type:s}){let{authClaim:a,pubKey:c}=await this.createAuthCoreClaim(r,i),{hi:u,hv:l}=a.hiHv();await this._storage.mt.addToMerkleTree(e.string(),0,u,l);let d=await this._storage.mt.getMerkleTreeByIdentifierAndType(e.string(),0),h=Eh([(await d.root()).bigInt(),t.revocationRoot.bigInt(),t.rootOfRoots.bigInt()]);return this.createAuthBJJCredential(e,c,a,h,{id:o,type:s})}async addBJJAuthCredential(e,t,r,i,o,s){o.seed=o.seed??Gc(32),o.revocationOpts.nonce=o.revocationOpts.nonce??(r?0:o.revocationOpts.nonce??new DataView(Gc(12).buffer).getUint32(0));let a=await this.getAuthBJJCredential(e,t,{nonce:o.revocationOpts.nonce,seed:o.seed,id:o.revocationOpts.id,type:o.revocationOpts.type}),c=async()=>{let{receipt:d,block:h}=await this._transactionService.getTransactionReceiptAndBlock(u),f=await this.generateIden3SparseMerkleTreeProof(e,[a],u,d?.blockNumber,h?.timestamp,void 0,{revNonce:o.revocationOpts.nonce??0,subjectPosition:"",merklizedRootPosition:"",updatable:!1,version:0,merklizeOpts:{documentLoader:T0()}});return await this._credentialWallet.saveAll(f),await this.publishRevocationInfoByCredentialStatusType(e,o.revocationOpts.type,{rhsUrl:o.revocationOpts.id,onChain:o.revocationOpts.onChain}),f[0]},u="",l=2;do try{u=await this.transitState(e,t,r,i,s);break}catch(d){console.warn(`Error while transiting state, retrying state transition, attempt: ${l}`,d)}while(--l);if(!u){let d=JSON.stringify({claimsRoot:t.claimsRoot.hex(),revocationRoot:t.revocationRoot.hex(),rootOfRoots:t.rootOfRoots.hex(),state:t.state.hex(),isOldStateGenesis:r,credentialId:a.id,did:e.string()},null,2);throw await this._credentialWallet.save(a),new Error(`Error publishing state, info to publish: ${d}`)}return c()}};return b8(qRe);})();
|
|
436
436
|
/*! Bundled license information:
|
|
437
437
|
|
|
438
438
|
ieee754/index.js:
|