Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use augmented and generated types #1703

Merged
merged 30 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
02c0d2e
types generated with parachain-metadata
0xverin May 16, 2023
62078af
change gen-type
0xverin May 16, 2023
6baea67
tsconfig.json
0xverin May 16, 2023
01c6829
add env
0xverin May 16, 2023
cb4ebbc
upgrade typegen && re-generate
0xverin May 16, 2023
88946b5
fix package conflict
0xverin May 16, 2023
750d4fa
fix types
0xverin May 16, 2023
f844315
remove comments
0xverin May 16, 2023
d8d5a0e
fix ci
0xverin May 17, 2023
939e871
upgradte polkadot<api types>
0xverin May 17, 2023
317b8ab
upgrade @polkador/kering
0xverin May 17, 2023
2b583d6
add sidechain-types
0xverin May 18, 2023
1e00b98
add @polkadot/types/lookup
0xverin May 22, 2023
de37126
Merge branch 'dev' into 1673-use-generated-types
0xverin May 22, 2023
9324355
fix createType
0xverin May 24, 2023
5ed93e0
Merge branch 'dev' into 1673-use-generated-types
0xverin May 24, 2023
4355e7b
remove toHex()
0xverin May 24, 2023
5e7662f
fix ci & fix type
0xverin May 24, 2023
bb39b1e
Merge branch 'dev' into 1673-use-generated-types
0xverin May 25, 2023
18c8e50
refactor identity&validation types
0xverin May 31, 2023
3dc50f0
Merge branch 'dev' into 1673-use-generated-types
0xverin May 31, 2023
e78a07a
fix checkIdgraph
0xverin May 31, 2023
ad8e9cc
remove WorkerRpcReturnValue
0xverin May 31, 2023
8e3ea50
fix ci & format
0xverin May 31, 2023
b082d30
modified as type
0xverin May 31, 2023
472d4ca
modified Assertion type
0xverin May 31, 2023
f85448a
refactor assert
0xverin Jun 1, 2023
bda99a7
fix vc ci
0xverin Jun 1, 2023
514f003
add storage query sleep
0xverin Jun 1, 2023
6631fc0
Merge branch 'dev' into 1673-use-generated-types
0xverin Jun 7, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions tee-worker/ts-tests/batch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ describeLitentry('Test Batch Utility', 0, (context) => {
//query here in the hope that the status remains unchanged after verify error identity
step('batch test:check IDGraph after verifyIdentity', async function () {
for (let index = 0; index < identities.length; index++) {
const identity_hex = context.api.createType('LitentryIdentity', identities[index]).toHex();
const identity_hex = context.sidechainRegistry
.createType('LitentryPrimitivesIdentity', identities[index])
.toHex();
const resp_id_graph = await checkIDGraph(
context,
'IdentityManagement',
Expand Down Expand Up @@ -192,7 +194,9 @@ describeLitentry('Test Batch Utility', 0, (context) => {
//query here in the hope that the status remains unchanged after removes error identity
step('check IDGraph after removeIdentity', async function () {
for (let index = 0; index < identities.length; index++) {
const identity_hex = context.api.createType('LitentryIdentity', identities[index]).toHex();
const identity_hex = context.sidechainRegistry
.createType('LitentryPrimitivesIdentity', identities[index])
.toHex();

const resp_id_graph = await checkIDGraph(
context,
Expand Down
10 changes: 5 additions & 5 deletions tee-worker/ts-tests/bulk_identity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import {
} from './common/utils';
import { KeyringPair } from '@polkadot/keyring/types';
import { ethers } from 'ethers';
import { LitentryIdentity, LitentryValidationData } from './common/type-definitions';
import { LitentryIdentity, LitentryValidationData, BatchCall } from './common/type-definitions';
import { handleIdentityEvents } from './common/utils';
import { assert } from 'chai';
import { listenEvent, multiAccountTxSender } from './common/transactions';
import { u8aToHex } from '@polkadot/util';
import { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';

import { Call } from '@polkadot/types/interfaces/types';
import { Vec } from '@polkadot/types';
//Explain how to use this test, which has two important parameters:
//1.The "number" parameter in describeLitentry represents the number of accounts generated, including Substrate wallets and Ethereum wallets.If you want to use a large number of accounts for testing, you can modify this parameter.
//2.Each time the test code is executed, new wallet account will be used.
Expand All @@ -36,13 +36,13 @@ describeLitentry('multiple accounts test', 10, async (context) => {
});
});
step('send test token to each account', async () => {
const txs: SubmittableExtrinsic<ApiTypes>[] = [];
const txs: BatchCall = [];
for (let i = 0; i < substraetSigners.length; i++) {
//1 token
const tx = context.api.tx.balances.transfer(substraetSigners[i].address, '1000000000000');
txs.push(tx);
}
await context.api.tx.utility.batch(txs).signAndSend(context.substrateWallet.alice);
await context.api.tx.utility.batch(txs as Vec<Call>).signAndSend(context.substrateWallet.alice);
await listenEvent(context.api, 'balances', ['Transfer'], txs.length, [
u8aToHex(context.substrateWallet.alice.addressRaw),
]);
Expand Down
22 changes: 9 additions & 13 deletions tee-worker/ts-tests/bulk_vc.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { step } from 'mocha-steps';
import { checkVc, describeLitentry, encryptWithTeeShieldingKey } from './common/utils';
import { KeyringPair } from '@polkadot/keyring/types';
import { ethers } from 'ethers';
import { u8aToHex } from '@polkadot/util';
import { Assertion, IndexingNetwork, TransactionSubmit } from './common/type-definitions';
import { u8aToHex, hexToU8a } from '@polkadot/util';
import { Assertion, BatchCall, IndexingNetwork, TransactionSubmit } from './common/type-definitions';
import { handleVcEvents } from './common/utils';
import { blake2AsHex } from '@polkadot/util-crypto';
import { assert } from 'chai';
import { HexString } from '@polkadot/util/types';
import { listenEvent, multiAccountTxSender } from './common/transactions';
import { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
// import { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import { Call } from '@polkadot/types/interfaces/types';
import { Vec } from '@polkadot/types';
const assertion = <Assertion>{
A1: 'A1',
A2: ['A2'],
Expand All @@ -28,35 +29,30 @@ const assertion = <Assertion>{
describeLitentry('multiple accounts test', 10, async (context) => {
const aesKey = '0x22fc82db5b606998ad45099b7978b5b4f9dd4ea6017e57370ac56141caaabd12';
var substrateSigners: KeyringPair[] = [];
var ethereumSigners: ethers.Wallet[] = [];
var vcIndexList: HexString[] = [];
// If want to test other assertions with multiple accounts,just need to make changes here.
let assertion_type = assertion.A1;
step('init', async () => {
substrateSigners = context.web3Signers.map((web3Signer) => {
return web3Signer.substrateWallet;
});
ethereumSigners = context.web3Signers.map((web3Signer) => {
return web3Signer.ethereumWallet;
});
});
step('send test token to each account', async () => {
const txs: SubmittableExtrinsic<ApiTypes>[] = [];

const txs: BatchCall = [];
for (let i = 0; i < substrateSigners.length; i++) {
//1 token
const tx = context.api.tx.balances.transfer(substrateSigners[i].address, '1000000000000');

txs.push(tx);
}
await context.api.tx.utility.batch(txs).signAndSend(context.substrateWallet.alice);
await context.api.tx.utility.batch(txs as Vec<Call>).signAndSend(context.substrateWallet.alice);
await listenEvent(context.api, 'balances', ['Transfer'], txs.length, [
u8aToHex(context.substrateWallet.alice.addressRaw),
]);
});
//test with multiple accounts
step('test set usershieldingkey with multiple accounts', async () => {
const ciphertext = encryptWithTeeShieldingKey(context.teeShieldingKey, aesKey).toString('hex');
const ciphertext = encryptWithTeeShieldingKey(context.teeShieldingKey, hexToU8a(aesKey)).toString('hex');
let txs: TransactionSubmit[] = [];
for (let i = 0; i < substrateSigners.length; i++) {
const tx = context.api.tx.identityManagement.setUserShieldingKey(context.mrEnclave, `0x${ciphertext}`);
Expand All @@ -72,7 +68,7 @@ describeLitentry('multiple accounts test', 10, async (context) => {
step('test requestVc with multiple accounts', async () => {
let txs: TransactionSubmit[] = [];
for (let i = 0; i < substrateSigners.length; i++) {
const tx = context.api.tx.vcManagement.requestVc(context.mrEnclave, assertion_type);
const tx = context.api.tx.vcManagement.requestVc(context.mrEnclave, assertion_type!);
0xverin marked this conversation as resolved.
Show resolved Hide resolved
const nonce = (await context.api.rpc.system.accountNextIndex(substrateSigners[i].address)).toNumber();
txs.push({ tx, nonce });
}
Expand Down
23 changes: 12 additions & 11 deletions tee-worker/ts-tests/common/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import type { Bytes } from '@polkadot/types-codec';
import { hexToU8a, compactStripLength, u8aToString } from '@polkadot/util';
import WebSocketAsPromised from 'websocket-as-promised';
import { HexString } from '@polkadot/util/types';
import { RequestBody } from './type-definitions';
import { WorkerRpcReturnValue } from '../interfaces/identity';

import { RequestBody } from '../common/type-definitions';
import { WorkerRpcReturnValue } from '../parachain-interfaces/identity/types';
// send RPC request
export async function sendRequest(
wsClient: WebSocketAsPromised,
Expand All @@ -15,14 +14,13 @@ export async function sendRequest(
): Promise<WorkerRpcReturnValue> {
const rawRes = await wsClient.sendRequest(request, { requestId: 1, timeout: 6000 });
const res: WorkerRpcReturnValue = api.createType('WorkerRpcReturnValue', rawRes.result) as any;

if (res.status.isError) {
console.log('Rpc response error: ' + decodeRpcBytesAsString(res.value));
}

// unfortunately, the res.value only contains the hash of top
if (res.status.isTrustedOperationStatus && res.status.asTrustedOperationStatus.isInvalid) {
console.log('Rpc trusted operation execution failed, hash: ', res.value.toHex());
console.log('Rpc trusted operation execution failed, hash: ', res.value);
}

return res;
Expand All @@ -35,13 +33,16 @@ export function decodeRpcBytesAsString(value: Bytes): string {
return u8aToString(compactStripLength(hexToU8a(value.toHex()))[1]);
}

export async function getMetadata(wsClient: WebSocketAsPromised, api: ApiPromise): Promise<Metadata> {
export async function getSidechainMetadata(
wsClient: WebSocketAsPromised,
api: ApiPromise
): Promise<{ metaData: Metadata; sidechainRegistry: TypeRegistry }> {
let request = { jsonrpc: '2.0', method: 'state_getMetadata', params: [], id: 1 };
let res = await sendRequest(wsClient, request, api);
const registry = new TypeRegistry();
const metadata = new Metadata(registry, res.value);
registry.setMetadata(metadata);
return metadata;
let respJSON = await sendRequest(wsClient, request, api);
const sidechainRegistry = new TypeRegistry();
const metaData = new Metadata(sidechainRegistry, respJSON.value);
sidechainRegistry.setMetadata(metaData);
return { metaData, sidechainRegistry };
}

export async function getSideChainStorage(
Expand Down
39 changes: 26 additions & 13 deletions tee-worker/ts-tests/common/type-definitions.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,43 @@
import { ApiPromise, Keyring } from '@polkadot/api';
import { ApiPromise } from '@polkadot/api';
import { KeyObject } from 'crypto';
import { HexString } from '@polkadot/util/types';
import WebSocketAsPromised from 'websocket-as-promised';
import type { KeyringPair } from '@polkadot/keyring/types';
import { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
import { Metadata } from '@polkadot/types';
import { Metadata, Vec, TypeRegistry } from '@polkadot/types';
import { Wallet } from 'ethers';
import type { Assertion as GenericAssertion, DirectRequestStatus } from '../parachain-interfaces/identity/types';
import { default as teeTypes } from '../parachain-interfaces/identity/definitions';
import { AnyTuple, IMethod } from '@polkadot/types/types';
import { Call } from '@polkadot/types/interfaces';
import type {
SubstrateNetwork as SubNet,
Web2Network as Web2Net,
EvmNetwork as EvmNet,
} from '../interfaces/identity/types';
import { default as teeTypes } from '../interfaces/identity/definitions';

LitentryPrimitivesIdentitySubstrateNetwork,
LitentryPrimitivesIdentityEvmNetwork,
LitentryPrimitivesIdentityWeb2Network,
PalletIdentityManagementTeeIdentityContext,
} from '@polkadot/types/lookup';
export { teeTypes };

export type Web2Network = Web2Net['type'];
export type SubstrateNetwork = SubNet['type'];
export type EvmNetwork = EvmNet['type'];
export type Web2Network = LitentryPrimitivesIdentityWeb2Network['type'];
export type SubstrateNetwork = LitentryPrimitivesIdentitySubstrateNetwork['type'];
export type EvmNetwork = LitentryPrimitivesIdentityEvmNetwork['type'];
export type ParachainAssertion = GenericAssertion['type'];
export type WorkerRpcReturnString = {
vec: string;
};

export type BatchCall = Vec<Call> | (string | Uint8Array | IMethod<AnyTuple, any> | Call)[];
export type WorkerRpcReturnValue = {
value: `0x${string}`;
do_watch: boolean;
status: DirectRequestStatus;
};
0xverin marked this conversation as resolved.
Show resolved Hide resolved
export type EnclaveResult = {
mrEnclave: `0x${string}`;
shieldingKey: `0x${string}`;
vcPubkey: `0x${string}`;
sgxMetadata: {};
};

export type PubicKeyJson = {
n: Uint8Array;
e: Uint8Array;
Expand All @@ -45,6 +57,7 @@ export type IntegrationTestContext = {
ethersWallet: EthersWalletItem;
substrateWallet: SubstrateWalletItem;
metaData: Metadata;
sidechainRegistry: TypeRegistry;
web3Signers: Web3Wallets[];
};

Expand Down Expand Up @@ -136,7 +149,7 @@ export type Web3Network = {
export type IdentityGenericEvent = {
who: HexString;
identity: LitentryIdentity;
idGraph: [LitentryIdentity, IdentityContext][];
idGraph: [LitentryIdentity, PalletIdentityManagementTeeIdentityContext][];
challengeCode?: HexString;
};

Expand Down
43 changes: 33 additions & 10 deletions tee-worker/ts-tests/common/utils/assertion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,46 @@ import { hexToU8a, u8aToHex } from '@polkadot/util';
import Ajv from 'ajv';
import { assert, expect } from 'chai';
import * as ed from '@noble/ed25519';
import { EnclaveResult, IdentityGenericEvent, JsonSchema, LitentryIdentity } from '../type-definitions';
import {
EnclaveResult,
IdentityGenericEvent,
JsonSchema,
LitentryIdentity,
IntegrationTestContext,
} from '../type-definitions';
import { buildIdentityHelper } from './identity-helper';
import { isEqual, isArrayEqual } from './common';

export async function assertInitialIDGraphCreated(api: ApiPromise, signer: KeyringPair, event: IdentityGenericEvent) {
export async function assertInitialIDGraphCreated(
context: IntegrationTestContext,
signer: KeyringPair,
event: IdentityGenericEvent
) {
assert.equal(event.who, u8aToHex(signer.addressRaw));
assert.equal(event.idGraph.length, 1);
// check identity in idgraph
const expected_identity = api.createType(
'LitentryIdentity',
await buildIdentityHelper(u8aToHex(signer.addressRaw), 'LitentryRococo', 'Substrate')
const expected_identity = context.sidechainRegistry.createType(
'LitentryPrimitivesIdentity',
await buildIdentityHelper(
u8aToHex(signer.addressRaw),
process.env.NODE_ENV === 'local' ? 'TestNet' : 'LitentryRococo',
'Substrate'
)
) as LitentryIdentity;

assert.isTrue(isEqual(event.idGraph[0][0], expected_identity));
// check identityContext in idgraph
assert.equal(event.idGraph[0][1].linking_request_block, 0);
assert.equal(event.idGraph[0][1].verification_request_block, 0);
assert.isTrue(event.idGraph[0][1].is_verified);
console.log(event.idGraph[0][1]);

const creationRequestBlock = event.idGraph[0][1].creationRequestBlock.isSome
? event.idGraph[0][1].creationRequestBlock.unwrap().toNumber()
: event.idGraph[0][1].creationRequestBlock;
const verificationRequestBlock = event.idGraph[0][1].verificationRequestBlock.isSome
? event.idGraph[0][1].verificationRequestBlock.unwrap().toNumber()
: event.idGraph[0][1].verificationRequestBlock;

assert.equal(creationRequestBlock, 0);
assert.equal(verificationRequestBlock, 0);
assert.isTrue(event.idGraph[0][1].isVerified);
}

export function assertIdentityVerified(signer: KeyringPair, eventDatas: IdentityGenericEvent[]) {
Expand All @@ -43,7 +66,7 @@ export function assertIdentityVerified(signer: KeyringPair, eventDatas: Identity
const data = eventDatas[eventDatas.length - 1];
for (let i = 0; i < eventDatas[eventDatas.length - 1].idGraph.length; i++) {
if (isEqual(data.idGraph[i][0], data.identity)) {
assert.isTrue(data.idGraph[i][1].is_verified, 'identity should be verified');
assert.isTrue(data.idGraph[i][1].isVerified, 'identity should be verified');
}
}
assert.equal(data?.who, u8aToHex(signer.addressRaw), 'check caller error');
Expand Down
6 changes: 3 additions & 3 deletions tee-worker/ts-tests/common/utils/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import WebSocketAsPromised from 'websocket-as-promised';
import WebSocket from 'ws';
import Options from 'websocket-as-promised/types/options';
import { KeyObject } from 'crypto';
import { getMetadata } from '../call';
import { getSidechainMetadata } from '../call';
import { getEthereumSigner, getSubstrateSigner } from '../helpers';
import { IntegrationTestContext, teeTypes, EnclaveResult, Web3Wallets } from '../type-definitions';

Expand Down Expand Up @@ -62,8 +62,7 @@ export async function initIntegrationTestContext(

const wsp = await initWorkerConnection(workerEndpoint);

const metaData = await getMetadata(wsp, api);

const { metaData, sidechainRegistry } = await getSidechainMetadata(wsp, api);
const web3Signers = await generateWeb3Wallets(walletsNumber);
const { mrEnclave, teeShieldingKey } = await getEnclave(api);
return <IntegrationTestContext>{
Expand All @@ -74,6 +73,7 @@ export async function initIntegrationTestContext(
ethersWallet,
substrateWallet,
metaData,
sidechainRegistry,
web3Signers,
};
}
Expand Down
Loading