Skip to content

Commit

Permalink
test(verifier-client): import ApiClient dynamically
Browse files Browse the repository at this point in the history
- Import `ApiClient` from connector packages dynamically.
- Make `getVerifier` and `getValidatorApiClient` methods async to allow
    use of dynamic ESM import in the future.
- Make connector dependencies of verifier-client optional. User must manually
    install connector package they use to satisfy an optional peer dependency.
    Connectors are still needed for building (i.e. devDependencies).
- Cleanup dependencies of verifier-client
- Use async verifier factory methods in tests and sample apps.

Depends on #2904

Signed-off-by: Michal Bajer <[email protected]>
  • Loading branch information
outSH committed Dec 6, 2023
1 parent c7a8fa5 commit 4671297
Show file tree
Hide file tree
Showing 17 changed files with 274 additions and 242 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,13 @@ function sendRequest(

const args = { args: arg_request };

verifierFactory
.getVerifier("3PfTJw8g")
.sendSyncRequest(contract, method, args)
.then((result) => {
return resolve(result as ISendRequestResultV1<Array<string>>);
});
const verifier = await verifierFactory.getVerifier(
"3PfTJw8g",
"legacy-socketio",
);
verifier.sendSyncRequest(contract, method, args).then((result) => {
return resolve(result as ISendRequestResultV1<Array<string>>);
});
} catch (err) {
logger.error(err);
return reject(err);
Expand Down
1 change: 0 additions & 1 deletion examples/cactus-example-electricity-trade/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"@hyperledger/cactus-plugin-keychain-memory": "2.0.0-alpha.2",
"@hyperledger/cactus-plugin-ledger-connector-ethereum": "2.0.0-alpha.2",
"@hyperledger/cactus-plugin-ledger-connector-sawtooth": "2.0.0-alpha.2",
"@hyperledger/cactus-verifier-client": "2.0.0-alpha.2",
"@types/node": "14.18.54",
"body-parser": "1.20.2",
"cookie-parser": "1.4.6",
Expand Down
9 changes: 6 additions & 3 deletions examples/cactus-example-tcs-huawei/BalanceManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class BalanceManagement {
}

getBalance(account: string): Promise<unknown> {
return new Promise((resolve, reject) => {
return new Promise(async (resolve, reject) => {
// for LedgerOperation
// const execData = {"referedAddress": account};
// const ledgerOperation: LedgerOperation = new LedgerOperation("getNumericBalance", "", execData);
Expand All @@ -48,8 +48,11 @@ export class BalanceManagement {
// const method = "default";
// const args = {"method": {type: "web3Eth", command: "getBalance"}, "args": {"args": [account]}};

this.verifierFactory
.getVerifier("84jUisrs")
const verifier = await this.verifierFactory.getVerifier(
"84jUisrs",
"legacy-socketio",
);
verifier
.sendSyncRequest(contract, method, args)
.then((result) => {
const res1 = result as ISendRequestResultV1<string>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,18 +81,20 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase {
const options = {
filterKey: config.electricityTradeInfo.tcsHuawei.filterKey,
};
const verifierTcs = routesVerifierFactory.getVerifier(
useValidator["validatorID"][0],
);
verifierTcs.startMonitor(
"BusinessLogicTcsElectricityTrade",
options,
routesTransactionManagement,
);
routesVerifierFactory
.getVerifier(useValidator["validatorID"][0])
.then((verifierTcs) => {
verifierTcs.startMonitor(
"BusinessLogicTcsElectricityTrade",
options,
routesTransactionManagement,
);
});

logger.debug("getVerifierTcs");
}

remittanceTransaction(transactionSubset: object) {
async remittanceTransaction(transactionSubset: object) {
logger.debug(
`called remittanceTransaction(), accountInfo = ${json2str(
transactionSubset,
Expand Down Expand Up @@ -128,7 +130,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase {
routesTransactionManagement.getValidatorToUse(this.businessLogicID),
);
// const verifierEthereum = routesTransactionManagement.getVerifier(useValidator['validatorID'][1]);
const verifierEthereum = routesVerifierFactory.getVerifier(
const verifierEthereum = await routesVerifierFactory.getVerifier(
useValidator["validatorID"][1],
);
verifierEthereum.startMonitor(
Expand Down
91 changes: 45 additions & 46 deletions examples/cactus-example-tcs-huawei/TransactionEthereum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,56 +98,55 @@ function getNewNonce(fromAddress: string): Promise<{ txnCountHex: string }> {
const args = { args: { args: [fromAddress] } };

logger.debug(`##getNewNonce(A): call validator#getNonce()`);
xVerifierFactory
.getVerifier("84jUisrs")
.sendSyncRequest(contract, method, args)
.then((result) => {
// logger.debug(`##getNewNonce(A): result: ${JSON.stringify(result)}`);

const res1 = result as ISendRequestResultV1<{
readonly nonce: number;
readonly nonceHex: string;
}>;

let txnCount: number = res1.data.nonce;
let txnCountHex: string = res1.data.nonceHex;

const latestNonce = getLatestNonce(fromAddress);
// logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`);
if (txnCount <= latestNonce) {
// nonce correction
txnCount = latestNonce + 1;
logger.debug(
`##getNewNonce(C): Adjust txnCount, fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`,
);

const method = { type: "function", command: "toHex" };
const args = { args: { args: [txnCount] } };

logger.debug(`##getNewNonce(D): call validator#toHex()`);
xVerifierFactory
.getVerifier("84jUisrs")
.sendSyncRequest(contract, method, args)
.then((result) => {
const res2 = result as ISendRequestResultV1<{
readonly hexStr: string;
}>;
txnCountHex = res2.data.hexStr;
logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`);

// logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`);
setLatestNonce(fromAddress, txnCount);

return resolve({ txnCountHex: txnCountHex });
});
} else {
const verifier = await this.verifierFactory.getVerifier(
"84jUisrs",
"legacy-socketio",
);

verifier.sendSyncRequest(contract, method, args).then((result) => {
// logger.debug(`##getNewNonce(A): result: ${JSON.stringify(result)}`);

const res1 = result as ISendRequestResultV1<{
readonly nonce: number;
readonly nonceHex: string;
}>;

let txnCount: number = res1.data.nonce;
let txnCountHex: string = res1.data.nonceHex;

const latestNonce = getLatestNonce(fromAddress);
// logger.debug(`##getNewNonce(B): fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`);
if (txnCount <= latestNonce) {
// nonce correction
txnCount = latestNonce + 1;
logger.debug(
`##getNewNonce(C): Adjust txnCount, fromAddress: ${fromAddress}, txnCount: ${txnCount}, latestNonce: ${latestNonce}`,
);

const method = { type: "function", command: "toHex" };
const args = { args: { args: [txnCount] } };

logger.debug(`##getNewNonce(D): call validator#toHex()`);
verifier.sendSyncRequest(contract, method, args).then((result) => {
const res2 = result as ISendRequestResultV1<{
readonly hexStr: string;
}>;
txnCountHex = res2.data.hexStr;
logger.debug(`##getNewNonce(E): txnCountHex: ${txnCountHex}`);

// logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`);
setLatestNonce(fromAddress, txnCount);

logger.debug(`##getNewNonce(G): txnCountHex: ${txnCountHex}`);
return resolve({ txnCountHex: txnCountHex });
}
});
});
} else {
// logger.debug(`##getNewNonce(F) _nonce: ${txnCount}, latestNonce: ${latestNonce}`);
setLatestNonce(fromAddress, txnCount);

logger.debug(`##getNewNonce(G): txnCountHex: ${txnCountHex}`);
return resolve({ txnCountHex: txnCountHex });
}
});
} catch (err) {
logger.error(err);
return reject(err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ describe("Verifier integration with besu connector tests", () => {
});

const listenOptions: IListenOptions = {
hostname: "localhost",
hostname: "127.0.0.1",
port: 0,
server,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,14 @@ describe("Verifier integration with ethereum connector tests", () => {
// Helper Functions
//////////////////////////////////

function monitorAndGetBlock(
async function monitorAndGetBlock(
options: Record<string, unknown> = {},
): Promise<LedgerEvent<WatchBlocksV1Progress>> {
const appId = "testMonitor";
const sut = await globalVerifierFactory.getVerifier(ethereumValidatorId);

return new Promise<LedgerEvent<WatchBlocksV1Progress>>(
(resolve, reject) => {
const appId = "testMonitor";
const sut = globalVerifierFactory.getVerifier(ethereumValidatorId);

const monitor: IVerifierEventListener<WatchBlocksV1Progress> = {
onEvent(ledgerEvent: LedgerEvent<WatchBlocksV1Progress>): void {
try {
Expand Down Expand Up @@ -222,8 +222,8 @@ describe("Verifier integration with ethereum connector tests", () => {
// Tests
//////////////////////////////////

test("Verifier of EthereumApiClient is created by VerifierFactory", () => {
const sut = globalVerifierFactory.getVerifier(ethereumValidatorId);
test("Verifier of EthereumApiClient is created by VerifierFactory", async () => {
const sut = await globalVerifierFactory.getVerifier(ethereumValidatorId);
expect(sut.ledgerApi.className).toEqual("EthereumApiClient");
});

Expand All @@ -236,7 +236,7 @@ describe("Verifier integration with ethereum connector tests", () => {

beforeAll(async () => {
// Setup verifier
verifier = globalVerifierFactory.getVerifier(
verifier = await globalVerifierFactory.getVerifier(
ethereumValidatorId,
"ETH_1X",
);
Expand Down Expand Up @@ -508,9 +508,13 @@ describe("Verifier integration with ethereum connector tests", () => {
const method = { type: "web3Eth", command: "getBalance" };
const args = { args: [WHALE_ACCOUNT_ADDRESS] };

const results = (await globalVerifierFactory
.getVerifier(ethereumValidatorId)
.sendSyncRequest(contract, method, args)) as ISendRequestResultV1<string>;
const verifier =
await globalVerifierFactory.getVerifier(ethereumValidatorId);
const results = (await verifier.sendSyncRequest(
contract,
method,
args,
)) as ISendRequestResultV1<string>;
expect(results.status).toEqual(200);
expect(results.data.length).toBeGreaterThan(0);
});
Expand All @@ -525,7 +529,8 @@ describe("Verifier integration with ethereum connector tests", () => {
const correctArgs: any = {
args: [WHALE_ACCOUNT_ADDRESS],
};
const verifier = globalVerifierFactory.getVerifier(ethereumValidatorId);
const verifier =
await globalVerifierFactory.getVerifier(ethereumValidatorId);

// Sanity check if correct parameters work
const resultCorrect = (await verifier.sendSyncRequest(
Expand Down Expand Up @@ -565,9 +570,9 @@ describe("Verifier integration with ethereum connector tests", () => {
const args = {};

try {
await globalVerifierFactory
.getVerifier(ethereumValidatorId)
.sendSyncRequest(contract, method, args);
const verifier =
await globalVerifierFactory.getVerifier(ethereumValidatorId);
await verifier.sendSyncRequest(contract, method, args);
fail("Expected sendSyncRequest call to fail but it succeeded.");
} catch (error) {
console.log("sendSyncRequest failed as expected");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,14 @@ describe("Verifier integration with quorum connector tests", () => {
// Helper Functions
//////////////////////////////////

function monitorAndGetBlock(
async function monitorAndGetBlock(
options: Record<string, unknown> = {},
): Promise<LedgerEvent<WatchBlocksV1Progress>> {
const appId = "testMonitor";
const sut = await globalVerifierFactory.getVerifier(quorumValidatorId);

return new Promise<LedgerEvent<WatchBlocksV1Progress>>(
(resolve, reject) => {
const appId = "testMonitor";
const sut = globalVerifierFactory.getVerifier(quorumValidatorId);

const monitor: IVerifierEventListener<WatchBlocksV1Progress> = {
onEvent(ledgerEvent: LedgerEvent<WatchBlocksV1Progress>): void {
try {
Expand Down Expand Up @@ -241,8 +241,8 @@ describe("Verifier integration with quorum connector tests", () => {
// Tests
//////////////////////////////////

test("Verifier of QuorumApiClient is created by VerifierFactory", () => {
const sut = globalVerifierFactory.getVerifier(quorumValidatorId);
test("Verifier of QuorumApiClient is created by VerifierFactory", async () => {
const sut = await globalVerifierFactory.getVerifier(quorumValidatorId);
expect(sut.ledgerApi.className).toEqual("QuorumApiClient");
});

Expand All @@ -255,7 +255,7 @@ describe("Verifier integration with quorum connector tests", () => {

beforeAll(async () => {
// Setup verifier
verifier = globalVerifierFactory.getVerifier(
verifier = await globalVerifierFactory.getVerifier(
quorumValidatorId,
"QUORUM_2X",
);
Expand Down Expand Up @@ -543,11 +543,12 @@ describe("Verifier integration with quorum connector tests", () => {
const method = { type: "web3Eth", command: "getBalance" };
const args = { args: [connectionProfile.quorum.member2.accountAddress] };

const results = (await globalVerifierFactory
.getVerifier(quorumValidatorId)
.sendSyncRequest(contract, method, args)) as ISendRequestResultV1<
Array<unknown>
>;
const verifier = await globalVerifierFactory.getVerifier(quorumValidatorId);
const results = (await verifier.sendSyncRequest(
contract,
method,
args,
)) as ISendRequestResultV1<Array<unknown>>;
expect(results.status).toEqual(200);
expect(results.data.length).toBeGreaterThan(0);
});
Expand All @@ -562,7 +563,7 @@ describe("Verifier integration with quorum connector tests", () => {
const correctArgs: Record<string, unknown> = {
args: [connectionProfile.quorum.member2.accountAddress],
};
const verifier = globalVerifierFactory.getVerifier(quorumValidatorId);
const verifier = await globalVerifierFactory.getVerifier(quorumValidatorId);

// Sanity check if correct parameters work
const resultCorrect = (await verifier.sendSyncRequest(
Expand Down Expand Up @@ -601,13 +602,12 @@ describe("Verifier integration with quorum connector tests", () => {
const method = { type: "web3Eth", command: "foo" };
const args = {};

const results = (await globalVerifierFactory
.getVerifier(quorumValidatorId)
.sendSyncRequest(
contract,
method,
args,
)) as ISendRequestResultV1<unknown>;
const verifier = await globalVerifierFactory.getVerifier(quorumValidatorId);
const results = (await verifier.sendSyncRequest(
contract,
method,
args,
)) as ISendRequestResultV1<unknown>;

expect(results).toBeTruthy();
expect(results.status).toEqual(504);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ async function setupEnvironment(): Promise<void> {
sutLogLevel,
);

verifier = verifierFactory.getVerifier(ethereumValidatorId, "ETH_1X");
verifier = await verifierFactory.getVerifier(ethereumValidatorId, "ETH_1X");

// Clear the stress log file
writeFileSync(STRESS_LOG_FILENAME, "");
Expand Down
4 changes: 3 additions & 1 deletion packages/cactus-verifier-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ This package provides `Verifier` and `VerifierFactory` components that can be us
## VerifierFactory
- Used to create single verifier per ledger based on pre-defined configuration.
- See [verifier-factory.test.ts](../cactus-verifier-client/src/test/typescript/unit/verifier-factory.test.ts) for unit tests.
- **In order to use `VerifierFactory` or `getValidatorApiClient` you must manually install the connector package that provides given ledger ApiClient!**
- Example: if your project uses ethereum and corda validators, you must install `cactus-plugin-ledger-connector-ethereum` and `cactus-plugin-ledger-connector-corda `. See table above for validator to package mapping.

### Usage
``` typescript
Expand Down Expand Up @@ -53,7 +55,7 @@ const verifierFactory = new VerifierFactory(ledgerPluginInfo);

// Get ApiClient to validator with ID "myBesuValidatorId"
// Second argument will determine type of returned Verifier (BesuApiClient in this case)
const myBesu: Verifier<BesuApiClient> = sut.getVerifier("myBesuValidatorId", "BESU_1X"))
const myBesu: Verifier<BesuApiClient> = await sut.getVerifier("myBesuValidatorId", "BESU_1X"))

// Second argument can be ignored for backward-compatibility
// It will return Verifier<(union of all supported ApiClients)>
Expand Down
Loading

0 comments on commit 4671297

Please sign in to comment.