Skip to content

Commit

Permalink
rearrange loading details from states, to ensure that proof is genera…
Browse files Browse the repository at this point in the history
…ting by specific hash and block
  • Loading branch information
lukachi committed Oct 19, 2023
1 parent 4e54a9b commit a6e3222
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 23 deletions.
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/rarimo/rarime.git"
},
"source": {
"shasum": "kAv4cCANL3K5Sat0M/M6J1m+adjce26OUOBep1nvdY8=",
"shasum": "H9V8BMMelGIrVGMl4KZMCosylPmB8vH2Au1JMo4jBt4=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
11 changes: 9 additions & 2 deletions packages/snap/src/helpers/credential-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,15 @@ export const getPreparedCredential = async (credential: W3CCredential) => {
};
};

export const loadDataByUrl = async (url: string) => {
const response = await fetch(url);
export const loadDataByUrl = async (
url: string,
endianSwappedCoreStateHash?: string,
) => {
const response = await fetch(
endianSwappedCoreStateHash
? `${url}?state=${endianSwappedCoreStateHash}`
: url,
);

if (!response.ok) {
const message = `An error has occured: ${response.status}`;
Expand Down
24 changes: 22 additions & 2 deletions packages/snap/src/helpers/proof-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/prefer-for-of */
import { Hex, Signature } from '@iden3/js-crypto';
import { Claim, DID, MerklizedRootPosition } from '@iden3/js-iden3-core';
import {
Claim,
DID,
fromLittleEndian,
MerklizedRootPosition,
} from '@iden3/js-iden3-core';
import {
Hash,
NodeAux,
Expand Down Expand Up @@ -151,9 +156,20 @@ export const buildTreeState = (
rootOfRoots: newHashFromHex(rootOfRoots),
});

export const convertEndianSwappedCoreStateHashHex = (hash: string) => {
const convertedStateHash = fromLittleEndian(
Hex.decodeString(hash.slice(2)),
).toString(16);

return convertedStateHash?.length < 64
? `0x0${convertedStateHash}`
: `0x${convertedStateHash}`;
};

export const newCircuitClaimData = async (
credential: W3CCredential,
coreClaim: Claim,
coreStateHash: string,
): Promise<CircuitClaim> => {
const circuitClaim = new CircuitClaim();
circuitClaim.claim = coreClaim;
Expand All @@ -162,7 +178,10 @@ export const newCircuitClaimData = async (
const smtProof = getIden3SparseMerkleTreeProof(credential.proof!);

if (smtProof) {
const data = await loadDataByUrl(smtProof.id);
const data = await loadDataByUrl(
smtProof.id,
convertEndianSwappedCoreStateHashHex(coreStateHash),
);

circuitClaim.incProof = {
proof: data.mtp,
Expand All @@ -182,6 +201,7 @@ export const newCircuitClaimData = async (
const signature = Signature.newFromCompressed(decodedSignature);
const issuerAuthClaimIncMtp = await loadDataByUrl(
sigProof.issuerData.updateUrl,
convertEndianSwappedCoreStateHashHex(coreStateHash),
);
const rs: RevocationStatus = await getRevocationStatus(
sigProof.issuerData.credentialStatus!,
Expand Down
28 changes: 18 additions & 10 deletions packages/snap/src/helpers/state-v2-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,22 @@ export const getGISTProof = async ({
rpcUrl,
contractAddress,
userId,
rootHash,
}: {
rpcUrl: string;
contractAddress: string;
userId: string;
rootHash?: string;
}): Promise<StateProof> => {
const rawProvider = new providers.JsonRpcProvider(rpcUrl, 'any');

const contractInstance = StateV2__factory.connect(
contractAddress,
rawProvider,
);
const data = await contractInstance.getGISTProof(userId);
const data = rootHash
? await contractInstance.getGISTProofByRoot(userId, rootHash)
: await contractInstance.getGISTProof(userId);

return {
root: BigInt(data.root.toString()),
Expand Down Expand Up @@ -131,8 +135,15 @@ type UpdateStateDetails = {
proof: string;
};

export const getCoreOperationByIndex = async (index: string) => {
return loadDataFromRarimoCore<OperationResponse>(
`/rarimo/rarimo-core/rarimocore/operation/${index}`,
);
};

export const getUpdateStateDetails = async (
state: StateInfo,
operation: OperationResponse,
): Promise<UpdateStateDetails> => {
let operationProof;
do {
Expand All @@ -142,17 +153,13 @@ export const getUpdateStateDetails = async (
);
} catch (e) {
if (e instanceof FetcherError && e.response.status === 400) {
await new Promise((resolve) => setTimeout(resolve, 30000));
await new Promise((resolve) => setTimeout(resolve, 30_000));
} else {
throw e;
}
}
} while (!operationProof);

const operationResponse = await loadDataFromRarimoCore<OperationResponse>(
`/rarimo/rarimo-core/rarimocore/operation/${state.lastUpdateOperationIndex}`,
);

const decodedPath = operationProof?.path?.map((el: string) =>
utils.arrayify(el),
);
Expand All @@ -170,10 +177,10 @@ export const getUpdateStateDetails = async (
);

return {
stateRootHash: operationResponse.operation.details.stateRootHash,
stateRootHash: operation.operation.details.stateRootHash,
gistRootDataStruct: {
root: operationResponse.operation.details.GISTHash,
createdAtTimestamp: Number(operationResponse.operation.details.timestamp),
root: operation.operation.details.GISTHash,
createdAtTimestamp: Number(operation.operation.details.timestamp),
},
proof,
};
Expand All @@ -183,10 +190,11 @@ export const getUpdateStateTx = async (
accountId: string,
chainInfo: ChainInfo,
state: StateInfo,
operation: OperationResponse,
updateStateDetails?: UpdateStateDetails,
): Promise<TransactionRequest> => {
const { stateRootHash, gistRootDataStruct, proof } =
updateStateDetails ?? (await getUpdateStateDetails(state));
updateStateDetails ?? (await getUpdateStateDetails(state, operation));

const contractInterface = LightweightStateV2__factory.createInterface();

Expand Down
31 changes: 24 additions & 7 deletions packages/snap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
checkIfStateSynced,
exportKeysAndCredentials,
findCredentialsByQuery,
getCoreOperationByIndex,
getHostname,
getProviderChainInfo,
getUpdateStateDetails,
Expand Down Expand Up @@ -205,13 +206,8 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
const identity = await Identity.create(identityStorage.privateKeyHex);

const zkpGen = new ZkpGen(identity, params, credentials[0]);
const zkpProof = await zkpGen.generateProof();

if (!isOnChainProof) {
return { zkpProof };
}

let updateStateTx;
// ================ LOAD STATE DETAILS =====================

const chainInfo = await getProviderChainInfo();

Expand All @@ -228,13 +224,34 @@ export const onRpcRequest: OnRpcRequestHandler = async ({
stateData.state.createdAtBlock,
);

const updateStateDetails = await getUpdateStateDetails(stateData.state);
const operation = await getCoreOperationByIndex(
stateData.state.lastUpdateOperationIndex,
);

// ================== USE STATE DETAILS TO GEN PROOF =====================

const zkpProof = await zkpGen.generateProof(
stateData.state.hash,
operation.operation.details.GISTHash,
);

if (!isOnChainProof) {
return { zkpProof };
}

const updateStateDetails = await getUpdateStateDetails(
stateData.state,
operation,
);

let updateStateTx;

if (!isSynced) {
updateStateTx = await getUpdateStateTx(
accountAddress!,
chainInfo,
stateData.state,
operation,
updateStateDetails,
);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/snap/src/zkp-gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,15 @@ export class ZkpGen {
this.proofRequest = proofRequest;
}

async generateProof() {
async generateProof(coreStateHash: string, operationGistHash: string) {
const preparedCredential = await getPreparedCredential(
this.verifiableCredential,
);

this.circuitClaimData = await newCircuitClaimData(
preparedCredential.credential,
preparedCredential.credentialCoreClaim,
coreStateHash,
);

this.query = await toCircuitsQuery(
Expand Down Expand Up @@ -128,6 +129,7 @@ export class ZkpGen {
rpcUrl: getRarimoEvmRpcUrl(providerChainInfo.id),
contractAddress: getRarimoStateContractAddress(providerChainInfo.id),
userId: this.identity.identityIdBigIntString,
rootHash: operationGistHash,
});
this.gistProof = toGISTProof(gistInfo);

Expand Down

0 comments on commit a6e3222

Please sign in to comment.