Skip to content

Commit 8d158ac

Browse files
authored
Merge pull request #90 from 0xPolygonID/bump
Fix for queries of string values
2 parents 43c5237 + 4cd6b00 commit 8d158ac

File tree

9 files changed

+159
-31
lines changed

9 files changed

+159
-31
lines changed

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@0xpolygonid/js-sdk",
3-
"version": "1.0.0-beta.11",
3+
"version": "1.0.0-beta.12",
44
"description": "SDK to work with Polygon ID",
55
"main": "dist/cjs/index.js",
66
"module": "dist/esm_esbuild/index.js",
@@ -22,8 +22,8 @@
2222
"doc:build": "npm run doc:extract && npm run doc:documenter",
2323
"doc:watch:website": "ts-node ./scripts/doc-watch.ts",
2424
"tsc:declaration:watch": "tsc --watch --module commonjs --emitDeclarationOnly",
25-
"test": "mocha --require ts-node/register tests/**/*.ts -t 60000",
26-
"test:watch": "mocha -p --require ts-node/register tests/**/*.ts -t 60000 --watch",
25+
"test": "mocha --require ts-node/register tests/**/*.ts -t 120000",
26+
"test:watch": "mocha -p --require ts-node/register tests/**/*.ts -t 120000 --watch",
2727
"lint": "eslint --fix --ext .js,.ts src/**",
2828
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"",
2929
"deps:check": "madge --circular --extensions ts ./"

src/identity/identity-wallet.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,9 @@ export class IdentityWallet implements IIdentityWallet {
269269
async createIdentity(
270270
opts: IdentityCreationOptions
271271
): Promise<{ did: DID; credential: W3CCredential }> {
272-
const tmpIdentifier = opts.seed ? uuid.v5(new sha256js().update(opts.seed).digest('hex'), uuid.NIL) : uuid.v4();
272+
const tmpIdentifier = opts.seed
273+
? uuid.v5(new sha256js().update(opts.seed).digest('hex'), uuid.NIL)
274+
: uuid.v4();
273275

274276
opts.method = opts.method ?? DidMethod.Iden3;
275277
opts.blockchain = opts.blockchain ?? Blockchain.Polygon;

src/proof/proof-service.ts

+45-17
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,13 @@ import {
3939
import { toClaimNonRevStatus, toGISTProof } from './common';
4040
import { NativeProver } from './prover';
4141

42-
import { DocumentLoader, Options, Path, getDocumentLoader } from '@iden3/js-jsonld-merklization';
42+
import {
43+
DocumentLoader,
44+
Merklizer,
45+
Options,
46+
Path,
47+
getDocumentLoader
48+
} from '@iden3/js-jsonld-merklization';
4349
import { ZKProof } from '@iden3/js-jwz';
4450
import { Signer } from 'ethers';
4551
import { ZeroKnowledgeProofRequest, ZeroKnowledgeProofResponse } from '../iden3comm';
@@ -62,6 +68,7 @@ interface PreparedCredential {
6268
export interface QueryWithFieldName {
6369
query: Query;
6470
fieldName: string;
71+
rawValue?: unknown;
6572
isSelectiveDisclosure?: boolean;
6673
}
6774

@@ -639,7 +646,7 @@ export class ProofService implements IProofService {
639646
}
640647

641648
let path: Path = new Path();
642-
if (!!parsedQuery.fieldName) {
649+
if (parsedQuery.fieldName) {
643650
path = await Path.getContextPathKey(
644651
JSON.stringify(schema),
645652
credential.type[1],
@@ -650,6 +657,7 @@ export class ProofService implements IProofService {
650657
path.prepend(['https://www.w3.org/2018/credentials#credentialSubject']);
651658

652659
const mk = await credential.merklize(opts);
660+
653661
const { proof, value: mtValue } = await mk.proof(path);
654662

655663
const pathKey = await path.mtEntry();
@@ -665,7 +673,7 @@ export class ProofService implements IProofService {
665673
} else {
666674
parsedQuery.query.slotIndex = 5; // value data slot b
667675
}
668-
if (!parsedQuery.fieldName){
676+
if (!parsedQuery.fieldName) {
669677
const resultQuery = parsedQuery.query;
670678
resultQuery.operator = QueryOperators.$eq;
671679
resultQuery.values = [mtEntry];
@@ -684,6 +692,14 @@ export class ProofService implements IProofService {
684692
resultQuery.values = [mtEntry];
685693
return { query: resultQuery, vp };
686694
}
695+
if (parsedQuery.rawValue === null || parsedQuery.rawValue === undefined) {
696+
throw new Error('value is not presented in the query');
697+
}
698+
const ldType = await mk.jsonLDType(path);
699+
parsedQuery.query.values = await this.transformQueryValueToBigInts(
700+
parsedQuery.rawValue,
701+
ldType
702+
);
687703

688704
return { query: parsedQuery.query };
689705
}
@@ -711,19 +727,27 @@ export class ProofService implements IProofService {
711727
parsedQuery.fieldName,
712728
byteEncoder.encode(JSON.stringify(schema))
713729
);
730+
const { vp, mzValue, dataType } = await verifiablePresentationFromCred(
731+
credential,
732+
query,
733+
parsedQuery.fieldName,
734+
opts
735+
);
714736

715737
if (parsedQuery.isSelectiveDisclosure) {
716-
const { vp, mzValue } = await verifiablePresentationFromCred(
717-
credential,
718-
query,
719-
parsedQuery.fieldName,
720-
opts
721-
);
722738
const resultQuery = parsedQuery.query;
723739
resultQuery.operator = QueryOperators.$eq;
724740
resultQuery.values = [await mzValue.mtEntry()];
725741
return { query: resultQuery, vp };
726742
}
743+
if (parsedQuery.rawValue === null || parsedQuery.rawValue === undefined) {
744+
throw new Error('value is not presented in the query');
745+
}
746+
747+
parsedQuery.query.values = await this.transformQueryValueToBigInts(
748+
parsedQuery.rawValue,
749+
dataType
750+
);
727751

728752
return { query: parsedQuery.query };
729753
}
@@ -756,24 +780,28 @@ export class ProofService implements IProofService {
756780
}
757781

758782
let operator = 0;
759-
const values: bigint[] = new Array<bigint>(64).fill(BigInt(0));
760783
const [key, value] = fieldReqEntries[0];
761784
if (!QueryOperators[key]) {
762785
throw new Error(`operator is not supported by lib`);
763786
}
764787
operator = QueryOperators[key];
788+
789+
query.operator = operator;
790+
791+
return { query, fieldName, rawValue: value };
792+
}
793+
794+
async transformQueryValueToBigInts(value: unknown, ldType: string): Promise<bigint[]> {
795+
const values: bigint[] = new Array<bigint>(64).fill(BigInt(0));
796+
765797
if (Array.isArray(value)) {
766798
for (let index = 0; index < value.length; index++) {
767-
values[index] = BigInt(value[index]);
799+
values[index] = await Merklizer.hashValue(ldType, value);
768800
}
769801
} else {
770-
values[0] = BigInt(value);
802+
values[0] = await Merklizer.hashValue(ldType, value);
771803
}
772-
773-
query.operator = operator;
774-
query.values = values;
775-
776-
return { query, fieldName };
804+
return values;
777805
}
778806

779807
/** {@inheritdoc IProofService.generateAuthV2Inputs} */

src/storage/indexed-db/merkletree.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ export class MerkleTreeIndexedDBStorage implements IMerkleTreeStorage {
5555
};
5656
const meta = await get(identifier, this._merkleTreeMetaStore);
5757
if (meta) {
58-
throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
58+
throw new Error(
59+
`Present merkle tree meta information in the store for current identifier ${identifier}`
60+
);
5961
}
6062
const treesMeta = createMetaInfo();
6163
await set(identifier, treesMeta, this._merkleTreeMetaStore);

src/storage/local-storage/merkletree.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,10 @@ export class MerkleTreeLocalStorage implements IMerkleTreeStorage {
4949
if (meta) {
5050
const metaInfo: IdentityMerkleTreeMetaInformation[] = JSON.parse(meta);
5151
const presentMetaForIdentifier = metaInfo.find((m) => m.treeId === `${identifier}+${m.type}`);
52-
if(presentMetaForIdentifier) {
53-
throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
52+
if (presentMetaForIdentifier) {
53+
throw new Error(
54+
`Present merkle tree meta information in the store for current identifier ${identifier}`
55+
);
5456
}
5557
const identityMetaInfo = metaInfo.filter((m) => m.identifier === identifier);
5658
if (identityMetaInfo.length > 0) {

src/storage/memory/merkletree.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,10 @@ export class InMemoryMerkleTreeStorage implements IMerkleTreeStorage {
5252
if (!identifier) {
5353
identifier = `${uuid.v4()}`;
5454
}
55-
if(this._data[identifier]) {
56-
throw new Error(`Present merkle tree meta information in the store for current identifier ${identifier}`);
55+
if (this._data[identifier]) {
56+
throw new Error(
57+
`Present merkle tree meta information in the store for current identifier ${identifier}`
58+
);
5759
}
5860
this._data[identifier] = [];
5961

tests/handlers/auth.test.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,9 @@ describe('auth', () => {
172172
credWallet = new CredentialWallet(dataStorage, resolvers);
173173
idWallet = new IdentityWallet(kms, dataStorage, credWallet);
174174

175-
proofService = new ProofService(idWallet, credWallet, circuitStorage, mockStateStorage,{ipfsGatewayURL:"https://ipfs.io"});
175+
proofService = new ProofService(idWallet, credWallet, circuitStorage, mockStateStorage, {
176+
ipfsGatewayURL: 'https://ipfs.io'
177+
});
176178
packageMgr = await getPackageMgr(
177179
await circuitStorage.loadCircuitData(CircuitId.AuthV2),
178180
proofService.generateAuthV2Inputs.bind(proofService),
@@ -200,7 +202,7 @@ describe('auth', () => {
200202
method: DidMethod.Iden3,
201203
blockchain: Blockchain.Polygon,
202204
networkId: NetworkId.Mumbai,
203-
seed: seedPhrase,
205+
seed: seedPhraseIssuer,
204206
revocationOpts: {
205207
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
206208
id: rhsUrl
@@ -261,9 +263,11 @@ describe('auth', () => {
261263
from: issuerDID.id.string()
262264
};
263265

266+
console.log(JSON.stringify(issuerCred));
264267
const msgBytes = byteEncoder.encode(JSON.stringify(authReq));
265268
const authRes = await authHandler.handleAuthorizationRequestForGenesisDID(userDID, msgBytes);
266269

270+
267271
const tokenStr = authRes.token;
268272
console.log(tokenStr);
269273
expect(tokenStr).to.be.a('string');

tests/proofs/sig.test.ts

+89-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ describe('sig proofs', () => {
119119
idWallet = new IdentityWallet(kms, dataStorage, credWallet);
120120

121121
proofService = new ProofService(idWallet, credWallet, circuitStorage, mockStateStorage, {
122-
ipfsGatewayURL: 'ipfs.io'
122+
ipfsGatewayURL: 'https://ipfs.io'
123123
});
124124
});
125125

@@ -284,4 +284,92 @@ describe('sig proofs', () => {
284284
CircuitId.AtomicQuerySigV2
285285
);
286286
});
287+
288+
it('sigv2-ipfs-string-eq', async () => {
289+
const req = {
290+
id: '0d8e91e5-5686-49b5-85e3-2b35538c6a03',
291+
typ: 'application/iden3comm-plain-json',
292+
type: 'https://iden3-communication.io/authorization/1.0/request',
293+
thid: '0d8e91e5-5686-49b5-85e3-2b35538c6a03',
294+
body: {
295+
callbackUrl: 'https://verifier-v2.polygonid.me/api/callback?sessionId=25269',
296+
reason: 'test flow',
297+
scope: [
298+
{
299+
id: 1,
300+
circuitId: 'credentialAtomicQuerySigV2',
301+
query: {
302+
allowedIssuers: ['*'],
303+
context: 'ipfs://QmZ1zsLspwnjifxsncqDkB7EHb2pnaRnBPc5kqQcVxW5rV',
304+
credentialSubject: {
305+
stringTest: {
306+
$eq: 'test'
307+
}
308+
},
309+
type: 'TestString'
310+
}
311+
}
312+
]
313+
},
314+
from: 'did:polygonid:polygon:mumbai:2qLPqvayNQz9TA2r5VPxUugoF18teGU583zJ859wfy'
315+
};
316+
317+
const seedPhraseIssuer: Uint8Array = byteEncoder.encode('seedseedseedseedseedseedseedseed');
318+
const seedPhrase: Uint8Array = byteEncoder.encode('seedseedseedseedseedseedseeduser');
319+
320+
const { did: userDID } = await idWallet.createIdentity({
321+
method: DidMethod.Iden3,
322+
blockchain: Blockchain.Polygon,
323+
networkId: NetworkId.Mumbai,
324+
seed: seedPhrase,
325+
revocationOpts: {
326+
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
327+
id: rhsUrl
328+
}
329+
});
330+
331+
const { did: issuerDID } = await idWallet.createIdentity({
332+
method: DidMethod.Iden3,
333+
blockchain: Blockchain.Polygon,
334+
networkId: NetworkId.Mumbai,
335+
seed: seedPhraseIssuer,
336+
revocationOpts: {
337+
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
338+
id: rhsUrl
339+
}
340+
});
341+
const claimReq: CredentialRequest = {
342+
credentialSchema: 'ipfs://Qmb1Q5jLETkUkhswCVX52ntTCNQnRm3NyyGf1NZG98u5cv',
343+
type: 'TestString',
344+
credentialSubject: {
345+
id: userDID.toString(),
346+
stringTest: 'test'
347+
},
348+
expiration: 1693526400,
349+
revocationOpts: {
350+
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
351+
id: rhsUrl
352+
}
353+
};
354+
const issuerCred = await idWallet.issueCredential(issuerDID, claimReq, {
355+
ipfsGatewayURL: 'https://ipfs.io'
356+
});
357+
358+
await credWallet.save(issuerCred);
359+
360+
const creds = await credWallet.findByQuery(req.body.scope[0].query);
361+
expect(creds.length).to.not.equal(0);
362+
363+
const credsForMyUserDID = await credWallet.filterByCredentialSubject(creds, userDID);
364+
expect(creds.length).to.equal(1);
365+
366+
const { proof, vp } = await proofService.generateProof(
367+
req.body.scope[0],
368+
userDID,
369+
credsForMyUserDID[0]
370+
);
371+
console.log(proof);
372+
373+
expect(vp).to.be.undefined;
374+
});
287375
});

0 commit comments

Comments
 (0)