Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
daveroga committed Apr 3, 2024
1 parent a68a6dd commit d6740c1
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 25 deletions.
16 changes: 2 additions & 14 deletions src/identity/identity-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,13 @@ import {
ClaimOptions,
DID,
DidMethod,
genesisFromEthAddress,
getUnixTimestamp,
Id,
NetworkId,
SchemaHash
} from '@iden3/js-iden3-core';
import { poseidon, PublicKey, sha256, Signature, Hex, getRandomBytes } from '@iden3/js-crypto';
import { Hash, hashElems, ZERO_HASH } from '@iden3/js-merkletree';

import { generateProfileDID, subjectPositionIndex } from './common';
import * as uuid from 'uuid';
import { JSONSchema, JsonSchemaValidator, cacheLoader } from '../schema-processor';
Expand Down Expand Up @@ -44,15 +42,14 @@ import {
TreesModel
} from '../credentials';
import { TreeState } from '../circuits';
import { byteEncoder } from '../utils';
import { buildDIDFromEthPubKey, byteEncoder } from '../utils';
import { Options } from '@iden3/js-jsonld-merklization';
import { TransactionReceipt } from 'ethers';
import {
CredentialStatusPublisherRegistry,
Iden3SmtRhsCredentialStatusPublisher
} from '../credentials/status/credential-status-publisher';
import { ProofService } from '../proof';
import { keccak256 } from 'js-sha3';

/**
* DID creation options
Expand Down Expand Up @@ -636,16 +633,7 @@ export class IdentityWallet implements IIdentityWallet {

const keyIdEth = await this._kms.createKeyFromSeed(KmsKeyType.Secp256k1, opts.seed);
const pubKeyHexEth = (await this._kms.publicKey(keyIdEth)).slice(2); // 04 + x + y (uncompressed key)
// Use Keccak-256 hash function to get public key hash
const hashOfPublicKey = keccak256(Buffer.from(pubKeyHexEth, 'hex'));
// Convert hash to buffer
const ethAddressBuffer = Buffer.from(hashOfPublicKey, 'hex');
// Ethereum Address is '0x' concatenated with last 20 bytes
// of the public key hash
const ethAddr = ethAddressBuffer.slice(-20);
const genesis = genesisFromEthAddress(ethAddr);
const identifier = new Id(didType, genesis);
const did = DID.parseFromId(identifier);
const did = buildDIDFromEthPubKey(didType, pubKeyHexEth);

await this._storage.mt.createIdentityMerkleTrees(did.string());

Expand Down
5 changes: 3 additions & 2 deletions src/storage/blockchain/state.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { RootInfo, StateProof } from './../entities/state';
import { ZKProof } from '@iden3/js-jwz';
import { IStateStorage, UserStateTransitionInfo } from '../interfaces/state';
import { Contract, ContractTransaction, JsonRpcProvider, Signer, TransactionRequest } from 'ethers';
import { Contract, JsonRpcProvider, Signer, TransactionRequest } from 'ethers';
import { StateInfo } from '../entities/state';
import { StateTransitionPubSignals } from '../../circuits';
import { byteEncoder } from '../../utils';
Expand Down Expand Up @@ -165,7 +165,8 @@ export class EthStateStorage implements IStateStorage {
signer: Signer,
userStateTranstionInfo: UserStateTransitionInfo
): Promise<string> {
const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTranstionInfo;
const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } =
userStateTranstionInfo;
const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
const contract = stateContract.connect(signer) as Contract;
const feeData = await provider.getFeeData();
Expand Down
14 changes: 14 additions & 0 deletions src/utils/did-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Hex } from '@iden3/js-crypto';
import { Id, buildDIDType, genesisFromEthAddress, DID } from '@iden3/js-iden3-core';
import { Hash } from '@iden3/js-merkletree';
import { DIDResolutionResult, VerificationMethod } from 'did-resolver';
import { keccak256 } from 'js-sha3';

/**
* Checks if state is genesis state
Expand Down Expand Up @@ -83,3 +84,16 @@ export const resolveDIDDocumentAuth = async (
(i) => i.type === 'Iden3StateInfo2023'
);
};

export const buildDIDFromEthPubKey = (didType: Uint8Array, pubKeyEth: string): DID => {
// Use Keccak-256 hash function to get public key hash
const hashOfPublicKey = keccak256(Buffer.from(pubKeyEth, 'hex'));
// Convert hash to buffer
const ethAddressBuffer = Buffer.from(hashOfPublicKey, 'hex');
// Ethereum Address is '0x' concatenated with last 20 bytes
// of the public key hash
const ethAddr = ethAddressBuffer.slice(-20);
const genesis = genesisFromEthAddress(ethAddr);
const identifier = new Id(didType, genesis);
return DID.parseFromId(identifier);
};
29 changes: 24 additions & 5 deletions tests/handlers/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ import {
Profile,
InMemoryMerkleTreeStorage,
W3CCredential,
Sec256k1Provider
Sec256k1Provider,
StateInfo
} from '../../src';
import { Token } from '@iden3/js-jwz';
import { Blockchain, DID, DidMethod, NetworkId } from '@iden3/js-iden3-core';
Expand Down Expand Up @@ -565,8 +566,26 @@ describe('auth', () => {
from: didIssuer.string()
};

// Ethereum identities should have a previous state in state storage. We mock it here.
const previousGetLatestStateById = MOCK_STATE_STORAGE.getLatestStateById;
MOCK_STATE_STORAGE.getLatestStateById = async (id: bigint): Promise<StateInfo> => {
return {
id,
state: res.oldTreeState.state.bigInt(),
replacedByState: 0n,
createdAtTimestamp: 1712062738n,
replacedAtTimestamp: 0n,
createdAtBlock: 5384981n,
replacedAtBlock: 0n
};
};

const msgBytes = byteEncoder.encode(JSON.stringify(authReq));
const authRes = await authHandler.handleAuthorizationRequest(userDID, msgBytes);

// Restore the mock state storage
MOCK_STATE_STORAGE.getLatestStateById = previousGetLatestStateById;

// console.log(JSON.stringify(authRes.authResponse));
const tokenStr = authRes.token;
// console.log(tokenStr);
Expand All @@ -580,7 +599,7 @@ describe('auth', () => {
const stateEthConfig = defaultEthConnectionConfig;
stateEthConfig.url = RPC_URL;
stateEthConfig.contractAddress = STATE_CONTRACT;
stateEthConfig.chainId = 80001;
stateEthConfig.chainId = 80002; // Amoy

const memoryKeyStore = new InMemoryPrivateKeyStore();
const bjjProvider = new BjjProvider(KmsKeyType.BabyJubJub, memoryKeyStore);
Expand Down Expand Up @@ -625,7 +644,7 @@ describe('auth', () => {
const { did: didUser, credential: userAuthCredential } = await idWallet.createIdentity({
method: DidMethod.PolygonId,
blockchain: Blockchain.Polygon,
networkId: NetworkId.Mumbai,
networkId: NetworkId.Amoy,
seed: SEED_USER,
revocationOpts: {
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
Expand All @@ -643,15 +662,15 @@ describe('auth', () => {
const { did: didIssuer, credential: issuerAuthCredential } = await idWallet.createIdentity({
method: DidMethod.PolygonId,
blockchain: Blockchain.Polygon,
networkId: NetworkId.Mumbai,
networkId: NetworkId.Amoy,
seed: Buffer.from(WALLET_KEY, 'hex'),
revocationOpts: {
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
id: RHS_URL
},
keyType: KmsKeyType.Secp256k1,
ethSigner,
proofService: proofService
proofService
});
expect(issuerAuthCredential).not.to.be.undefined;

Expand Down
27 changes: 24 additions & 3 deletions tests/identity/id.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable no-console */
import path from 'path';
import {
IdentityWallet,
byteEncoder,
Expand All @@ -10,15 +11,18 @@ import {
CredentialStatusResolverRegistry,
RHSResolver,
CredentialStatusType,
KmsKeyType
KmsKeyType,
ProofService,
FSCircuitStorage
} from '../../src';
import {
MOCK_STATE_STORAGE,
SEED_USER,
createIdentity,
RHS_URL,
getInMemoryDataStorage,
registerKeyProvidersInMemoryKMS
registerKeyProvidersInMemoryKMS,
IPFS_URL
} from '../helpers';
import { expect } from 'chai';

Expand Down Expand Up @@ -170,7 +174,24 @@ describe('identity', () => {
});

it('createIdentity Secp256k1', async () => {
const { did, credential } = await createIdentity(idWallet, { keyType: KmsKeyType.Secp256k1 });
const circuitStorage = new FSCircuitStorage({
dirname: path.join(__dirname, '../proofs/testdata')
});

const proofService = new ProofService(
idWallet,
credWallet,
circuitStorage,
dataStorage.states,
{
ipfsNodeURL: IPFS_URL
}
);

const { did, credential } = await createIdentity(idWallet, {
keyType: KmsKeyType.Secp256k1,
proofService
});

expect(did.string()).to.equal(
'did:iden3:polygon:amoy:x6x5sor7zpxsu478u36QvEgaRUfPjmzqFo5PHHzbM'
Expand Down
16 changes: 15 additions & 1 deletion tests/utils/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect } from 'chai';
import { JSONObject, mergeObjects } from '../../src';
import { buildDIDFromEthPubKey, JSONObject, mergeObjects } from '../../src';
import { Blockchain, buildDIDType, DidMethod, NetworkId } from '@iden3/js-iden3-core';

describe('merge credential subjects to create query', () => {
it('should merge two valid JSONObjects correctly', () => {
Expand Down Expand Up @@ -149,3 +150,16 @@ describe('merge credential subjects to create query', () => {
}
});
});

describe('build did from ethereum public key', () => {
it('should build did from ethereum public key correctly', async () => {
const pubKeyHexEth =
'8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5';
const didType = buildDIDType(DidMethod.Iden3, Blockchain.Polygon, NetworkId.Amoy);
const did = buildDIDFromEthPubKey(didType, pubKeyHexEth);

expect(did.string()).to.equal(
'did:iden3:polygon:amoy:x6x5sor7zpycB7z7Q9348dXJxZ9s5b9AgmPeSccZz'
);
});
});

0 comments on commit d6740c1

Please sign in to comment.