Skip to content

Commit d6740c1

Browse files
committed
update tests
1 parent a68a6dd commit d6740c1

File tree

6 files changed

+82
-25
lines changed

6 files changed

+82
-25
lines changed

src/identity/identity-wallet.ts

+2-14
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,13 @@ import {
77
ClaimOptions,
88
DID,
99
DidMethod,
10-
genesisFromEthAddress,
1110
getUnixTimestamp,
1211
Id,
1312
NetworkId,
1413
SchemaHash
1514
} from '@iden3/js-iden3-core';
1615
import { poseidon, PublicKey, sha256, Signature, Hex, getRandomBytes } from '@iden3/js-crypto';
1716
import { Hash, hashElems, ZERO_HASH } from '@iden3/js-merkletree';
18-
1917
import { generateProfileDID, subjectPositionIndex } from './common';
2018
import * as uuid from 'uuid';
2119
import { JSONSchema, JsonSchemaValidator, cacheLoader } from '../schema-processor';
@@ -44,15 +42,14 @@ import {
4442
TreesModel
4543
} from '../credentials';
4644
import { TreeState } from '../circuits';
47-
import { byteEncoder } from '../utils';
45+
import { buildDIDFromEthPubKey, byteEncoder } from '../utils';
4846
import { Options } from '@iden3/js-jsonld-merklization';
4947
import { TransactionReceipt } from 'ethers';
5048
import {
5149
CredentialStatusPublisherRegistry,
5250
Iden3SmtRhsCredentialStatusPublisher
5351
} from '../credentials/status/credential-status-publisher';
5452
import { ProofService } from '../proof';
55-
import { keccak256 } from 'js-sha3';
5653

5754
/**
5855
* DID creation options
@@ -636,16 +633,7 @@ export class IdentityWallet implements IIdentityWallet {
636633

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

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

src/storage/blockchain/state.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { RootInfo, StateProof } from './../entities/state';
22
import { ZKProof } from '@iden3/js-jwz';
33
import { IStateStorage, UserStateTransitionInfo } from '../interfaces/state';
4-
import { Contract, ContractTransaction, JsonRpcProvider, Signer, TransactionRequest } from 'ethers';
4+
import { Contract, JsonRpcProvider, Signer, TransactionRequest } from 'ethers';
55
import { StateInfo } from '../entities/state';
66
import { StateTransitionPubSignals } from '../../circuits';
77
import { byteEncoder } from '../../utils';
@@ -165,7 +165,8 @@ export class EthStateStorage implements IStateStorage {
165165
signer: Signer,
166166
userStateTranstionInfo: UserStateTransitionInfo
167167
): Promise<string> {
168-
const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } = userStateTranstionInfo;
168+
const { userId, oldUserState, newUserState, isOldStateGenesis, methodId, methodParams } =
169+
userStateTranstionInfo;
169170
const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
170171
const contract = stateContract.connect(signer) as Contract;
171172
const feeData = await provider.getFeeData();

src/utils/did-helper.ts

+14
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Hex } from '@iden3/js-crypto';
22
import { Id, buildDIDType, genesisFromEthAddress, DID } from '@iden3/js-iden3-core';
33
import { Hash } from '@iden3/js-merkletree';
44
import { DIDResolutionResult, VerificationMethod } from 'did-resolver';
5+
import { keccak256 } from 'js-sha3';
56

67
/**
78
* Checks if state is genesis state
@@ -83,3 +84,16 @@ export const resolveDIDDocumentAuth = async (
8384
(i) => i.type === 'Iden3StateInfo2023'
8485
);
8586
};
87+
88+
export const buildDIDFromEthPubKey = (didType: Uint8Array, pubKeyEth: string): DID => {
89+
// Use Keccak-256 hash function to get public key hash
90+
const hashOfPublicKey = keccak256(Buffer.from(pubKeyEth, 'hex'));
91+
// Convert hash to buffer
92+
const ethAddressBuffer = Buffer.from(hashOfPublicKey, 'hex');
93+
// Ethereum Address is '0x' concatenated with last 20 bytes
94+
// of the public key hash
95+
const ethAddr = ethAddressBuffer.slice(-20);
96+
const genesis = genesisFromEthAddress(ethAddr);
97+
const identifier = new Id(didType, genesis);
98+
return DID.parseFromId(identifier);
99+
};

tests/handlers/auth.test.ts

+24-5
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ import {
3737
Profile,
3838
InMemoryMerkleTreeStorage,
3939
W3CCredential,
40-
Sec256k1Provider
40+
Sec256k1Provider,
41+
StateInfo
4142
} from '../../src';
4243
import { Token } from '@iden3/js-jwz';
4344
import { Blockchain, DID, DidMethod, NetworkId } from '@iden3/js-iden3-core';
@@ -565,8 +566,26 @@ describe('auth', () => {
565566
from: didIssuer.string()
566567
};
567568

569+
// Ethereum identities should have a previous state in state storage. We mock it here.
570+
const previousGetLatestStateById = MOCK_STATE_STORAGE.getLatestStateById;
571+
MOCK_STATE_STORAGE.getLatestStateById = async (id: bigint): Promise<StateInfo> => {
572+
return {
573+
id,
574+
state: res.oldTreeState.state.bigInt(),
575+
replacedByState: 0n,
576+
createdAtTimestamp: 1712062738n,
577+
replacedAtTimestamp: 0n,
578+
createdAtBlock: 5384981n,
579+
replacedAtBlock: 0n
580+
};
581+
};
582+
568583
const msgBytes = byteEncoder.encode(JSON.stringify(authReq));
569584
const authRes = await authHandler.handleAuthorizationRequest(userDID, msgBytes);
585+
586+
// Restore the mock state storage
587+
MOCK_STATE_STORAGE.getLatestStateById = previousGetLatestStateById;
588+
570589
// console.log(JSON.stringify(authRes.authResponse));
571590
const tokenStr = authRes.token;
572591
// console.log(tokenStr);
@@ -580,7 +599,7 @@ describe('auth', () => {
580599
const stateEthConfig = defaultEthConnectionConfig;
581600
stateEthConfig.url = RPC_URL;
582601
stateEthConfig.contractAddress = STATE_CONTRACT;
583-
stateEthConfig.chainId = 80001;
602+
stateEthConfig.chainId = 80002; // Amoy
584603

585604
const memoryKeyStore = new InMemoryPrivateKeyStore();
586605
const bjjProvider = new BjjProvider(KmsKeyType.BabyJubJub, memoryKeyStore);
@@ -625,7 +644,7 @@ describe('auth', () => {
625644
const { did: didUser, credential: userAuthCredential } = await idWallet.createIdentity({
626645
method: DidMethod.PolygonId,
627646
blockchain: Blockchain.Polygon,
628-
networkId: NetworkId.Mumbai,
647+
networkId: NetworkId.Amoy,
629648
seed: SEED_USER,
630649
revocationOpts: {
631650
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
@@ -643,15 +662,15 @@ describe('auth', () => {
643662
const { did: didIssuer, credential: issuerAuthCredential } = await idWallet.createIdentity({
644663
method: DidMethod.PolygonId,
645664
blockchain: Blockchain.Polygon,
646-
networkId: NetworkId.Mumbai,
665+
networkId: NetworkId.Amoy,
647666
seed: Buffer.from(WALLET_KEY, 'hex'),
648667
revocationOpts: {
649668
type: CredentialStatusType.Iden3ReverseSparseMerkleTreeProof,
650669
id: RHS_URL
651670
},
652671
keyType: KmsKeyType.Secp256k1,
653672
ethSigner,
654-
proofService: proofService
673+
proofService
655674
});
656675
expect(issuerAuthCredential).not.to.be.undefined;
657676

tests/identity/id.test.ts

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/* eslint-disable no-console */
2+
import path from 'path';
23
import {
34
IdentityWallet,
45
byteEncoder,
@@ -10,15 +11,18 @@ import {
1011
CredentialStatusResolverRegistry,
1112
RHSResolver,
1213
CredentialStatusType,
13-
KmsKeyType
14+
KmsKeyType,
15+
ProofService,
16+
FSCircuitStorage
1417
} from '../../src';
1518
import {
1619
MOCK_STATE_STORAGE,
1720
SEED_USER,
1821
createIdentity,
1922
RHS_URL,
2023
getInMemoryDataStorage,
21-
registerKeyProvidersInMemoryKMS
24+
registerKeyProvidersInMemoryKMS,
25+
IPFS_URL
2226
} from '../helpers';
2327
import { expect } from 'chai';
2428

@@ -170,7 +174,24 @@ describe('identity', () => {
170174
});
171175

172176
it('createIdentity Secp256k1', async () => {
173-
const { did, credential } = await createIdentity(idWallet, { keyType: KmsKeyType.Secp256k1 });
177+
const circuitStorage = new FSCircuitStorage({
178+
dirname: path.join(__dirname, '../proofs/testdata')
179+
});
180+
181+
const proofService = new ProofService(
182+
idWallet,
183+
credWallet,
184+
circuitStorage,
185+
dataStorage.states,
186+
{
187+
ipfsNodeURL: IPFS_URL
188+
}
189+
);
190+
191+
const { did, credential } = await createIdentity(idWallet, {
192+
keyType: KmsKeyType.Secp256k1,
193+
proofService
194+
});
174195

175196
expect(did.string()).to.equal(
176197
'did:iden3:polygon:amoy:x6x5sor7zpxsu478u36QvEgaRUfPjmzqFo5PHHzbM'

tests/utils/utils.test.ts

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { expect } from 'chai';
2-
import { JSONObject, mergeObjects } from '../../src';
2+
import { buildDIDFromEthPubKey, JSONObject, mergeObjects } from '../../src';
3+
import { Blockchain, buildDIDType, DidMethod, NetworkId } from '@iden3/js-iden3-core';
34

45
describe('merge credential subjects to create query', () => {
56
it('should merge two valid JSONObjects correctly', () => {
@@ -149,3 +150,16 @@ describe('merge credential subjects to create query', () => {
149150
}
150151
});
151152
});
153+
154+
describe('build did from ethereum public key', () => {
155+
it('should build did from ethereum public key correctly', async () => {
156+
const pubKeyHexEth =
157+
'8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5';
158+
const didType = buildDIDType(DidMethod.Iden3, Blockchain.Polygon, NetworkId.Amoy);
159+
const did = buildDIDFromEthPubKey(didType, pubKeyHexEth);
160+
161+
expect(did.string()).to.equal(
162+
'did:iden3:polygon:amoy:x6x5sor7zpycB7z7Q9348dXJxZ9s5b9AgmPeSccZz'
163+
);
164+
});
165+
});

0 commit comments

Comments
 (0)