diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/cbdc-bridging-app.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/cbdc-bridging-app.ts index 2e655a0f76..a5b8009516 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/cbdc-bridging-app.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/cbdc-bridging-app.ts @@ -17,14 +17,13 @@ import { } from "@hyperledger/cactus-cmd-api-server"; import { Configuration, - DefaultApi as OdapApi, IKeyPair, -} from "@hyperledger/cactus-plugin-satp-hermes"; + DefaultApi as SatpApi, +} from "@hyperledger/cactus-plugin-satp-hermes/"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import { CbdcBridgingAppDummyInfrastructure } from "./infrastructure/cbdc-bridging-app-dummy-infrastructure"; import { DefaultApi as FabricApi } from "@hyperledger/cactus-plugin-ledger-connector-fabric"; import { DefaultApi as BesuApi } from "@hyperledger/cactus-plugin-ledger-connector-besu"; -import { DefaultApi as IpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { FabricSatpGateway } from "./satp-extension/fabric-satp-gateway"; import { BesuSatpGateway } from "./satp-extension/besu-satp-gateway"; import CryptoMaterial from "../../crypto-material/crypto-material.json"; @@ -81,8 +80,6 @@ export class CbdcBridgingApp { const fabricPlugin = await this.infrastructure.createFabricLedgerConnector(); const besuPlugin = await this.infrastructure.createBesuLedgerConnector(); - const clientIpfsPlugin = await this.infrastructure.createIPFSConnector(); - const serverIpfsPlugin = await this.infrastructure.createIPFSConnector(); // Reserve the ports where the API Servers will run const httpApiA = await Servers.startOnPort( @@ -100,16 +97,14 @@ export class CbdcBridgingApp { const addressInfoB = httpApiB.address() as AddressInfo; const nodeApiHostB = `http://${this.options.apiHost}:${addressInfoB.port}`; - const fabricOdapGateway = await this.infrastructure.createClientGateway( + const fabricSatpGateway = await this.infrastructure.createClientGateway( nodeApiHostA, this.options.clientGatewayKeyPair, - `http://${this.options.apiHost}:${addressInfoA.port}`, ); - const besuOdapGateway = await this.infrastructure.createServerGateway( + const besuSatpGateway = await this.infrastructure.createServerGateway( nodeApiHostB, this.options.serverGatewayKeyPair, - `http://${this.options.apiHost}:${addressInfoB.port}`, ); const clientPluginRegistry = new PluginRegistry({ @@ -132,12 +127,10 @@ export class CbdcBridgingApp { }); clientPluginRegistry.add(fabricPlugin); - clientPluginRegistry.add(fabricOdapGateway); - clientPluginRegistry.add(clientIpfsPlugin); + clientPluginRegistry.add(fabricSatpGateway); serverPluginRegistry.add(besuPlugin); - serverPluginRegistry.add(serverIpfsPlugin); - serverPluginRegistry.add(besuOdapGateway); + serverPluginRegistry.add(besuSatpGateway); const apiServer1 = await this.startNode(httpApiA, clientPluginRegistry); const apiServer2 = await this.startNode(httpApiB, serverPluginRegistry); @@ -165,17 +158,16 @@ export class CbdcBridgingApp { return { apiServer1, apiServer2, - fabricGatewayApi: new OdapApi( + fabricGatewayApi: new SatpApi( new Configuration({ basePath: nodeApiHostA }), ), - besuGatewayApi: new OdapApi( + besuGatewayApi: new SatpApi( new Configuration({ basePath: nodeApiHostB }), ), - ipfsApiClient: new IpfsApi(new Configuration({ basePath: nodeApiHostA })), fabricApiClient, besuApiClient, - fabricOdapGateway, - besuOdapGateway, + fabricSatpGateway, + besuSatpGateway, }; } @@ -231,11 +223,10 @@ export class CbdcBridgingApp { export interface IStartInfo { readonly apiServer1: ApiServer; readonly apiServer2: ApiServer; - readonly fabricGatewayApi: OdapApi; - readonly besuGatewayApi: OdapApi; - readonly ipfsApiClient: IpfsApi; + readonly fabricGatewayApi: SatpApi; + readonly besuGatewayApi: SatpApi; readonly besuApiClient: BesuApi; readonly fabricApiClient: FabricApi; - readonly fabricOdapGateway: FabricSatpGateway; - readonly besuOdapGateway: BesuSatpGateway; + readonly fabricSatpGateway: FabricSatpGateway; + readonly besuSatpGateway: BesuSatpGateway; } diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/infrastructure/cbdc-bridging-app-dummy-infrastructure.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/infrastructure/cbdc-bridging-app-dummy-infrastructure.ts index de315545c9..9ea61010d4 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/infrastructure/cbdc-bridging-app-dummy-infrastructure.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/infrastructure/cbdc-bridging-app-dummy-infrastructure.ts @@ -13,7 +13,6 @@ import { DEFAULT_FABRIC_2_AIO_IMAGE_NAME, DEFAULT_FABRIC_2_AIO_IMAGE_VERSION, FabricTestLedgerV1, - GoIpfsTestContainer, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import { @@ -35,7 +34,6 @@ import { InvokeContractV1Request as BesuInvokeContractV1Request, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { PluginRegistry } from "@hyperledger/cactus-core"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import AssetReferenceContractJson from "../../../solidity/asset-reference-contract/AssetReferenceContract.json"; import CBDCcontractJson from "../../../solidity/cbdc-erc-20/CBDCcontract.json"; import { IKeyPair } from "@hyperledger/cactus-plugin-satp-hermes"; @@ -43,6 +41,8 @@ import { FabricSatpGateway } from "../satp-extension/fabric-satp-gateway"; import { BesuSatpGateway } from "../satp-extension/besu-satp-gateway"; import { PluginImportType } from "@hyperledger/cactus-core-api"; import CryptoMaterial from "../../../crypto-material/crypto-material.json"; +import { ClientHelper } from "../satp-extension/client-helper"; +import { ServerHelper } from "../satp-extension/server-helper"; export interface ICbdcBridgingAppDummyInfrastructureOptions { logLevel?: LogLevelDesc; @@ -56,9 +56,6 @@ export class CbdcBridgingAppDummyInfrastructure { private readonly besu: BesuTestLedger; private readonly fabric: FabricTestLedgerV1; - private readonly ipfs: GoIpfsTestContainer; - private readonly ipfsParentPath: string; - private readonly log: Logger; public get className(): string { @@ -78,8 +75,6 @@ export class CbdcBridgingAppDummyInfrastructure { const level = this.options.logLevel || "INFO"; const label = this.className; - this.ipfsParentPath = `/${uuidv4()}/${uuidv4()}/`; - this.log = LoggerProvider.getOrCreate({ level, label }); this.besu = new BesuTestLedger({ @@ -97,10 +92,6 @@ export class CbdcBridgingAppDummyInfrastructure { ]), logLevel: level || "DEBUG", }); - - this.ipfs = new GoIpfsTestContainer({ - logLevel: level || "DEBUG", - }); } public get org1Env(): NodeJS.ProcessEnv & DeploymentTargetOrgFabric2x { @@ -140,11 +131,7 @@ export class CbdcBridgingAppDummyInfrastructure { public async start(): Promise { try { this.log.info(`Starting dummy infrastructure...`); - await Promise.all([ - this.besu.start(), - this.fabric.start(), - this.ipfs.start(), - ]); + await Promise.all([this.besu.start(), this.fabric.start()]); this.log.info(`Started dummy infrastructure OK`); } catch (ex) { this.log.error(`Starting of dummy infrastructure crashed: `, ex); @@ -158,7 +145,6 @@ export class CbdcBridgingAppDummyInfrastructure { await Promise.all([ this.besu.stop().then(() => this.besu.destroy()), this.fabric.stop().then(() => this.fabric.destroy()), - this.ipfs.stop().then(() => this.ipfs.destroy()), ]); this.log.info(`Stopped OK`); } catch (ex) { @@ -285,26 +271,9 @@ export class CbdcBridgingAppDummyInfrastructure { return besuConnector; } - public async createIPFSConnector(): Promise { - this.log.info(`Creating Besu Connector...`); - - const kuboRpcClientModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcClientModule.create({ - url: await this.ipfs.getApiUrl(), - }); - - return new PluginObjectStoreIpfs({ - parentDir: this.ipfsParentPath, - logLevel: this.options.logLevel, - instanceId: uuidv4(), - ipfsClientOrOptions, - }); - } - public async createClientGateway( nodeApiHost: string, keyPair: IKeyPair, - ipfsPath: string, ): Promise { this.log.info(`Creating Source Gateway...`); const pluginSourceGateway = new FabricSatpGateway({ @@ -312,7 +281,6 @@ export class CbdcBridgingAppDummyInfrastructure { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: keyPair, - ipfsPath: ipfsPath, fabricPath: nodeApiHost, fabricSigningCredential: { keychainId: CryptoMaterial.keychains.keychain1.id, @@ -320,10 +288,12 @@ export class CbdcBridgingAppDummyInfrastructure { }, fabricChannelName: "mychannel", fabricContractName: "asset-reference-contract", + clientHelper: new ClientHelper(), + serverHelper: new ServerHelper({}), }); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginSourceGateway.remoteRepository?.reset(); return pluginSourceGateway; } @@ -331,7 +301,6 @@ export class CbdcBridgingAppDummyInfrastructure { public async createServerGateway( nodeApiHost: string, keyPair: IKeyPair, - ipfsPath: string, ): Promise { this.log.info(`Creating Recipient Gateway...`); const pluginRecipientGateway = new BesuSatpGateway({ @@ -339,7 +308,6 @@ export class CbdcBridgingAppDummyInfrastructure { dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: keyPair, - ipfsPath: ipfsPath, besuPath: nodeApiHost, besuWeb3SigningCredential: { ethAccount: CryptoMaterial.accounts["bridge"].ethAddress, @@ -348,10 +316,12 @@ export class CbdcBridgingAppDummyInfrastructure { }, besuContractName: AssetReferenceContractJson.contractName, besuKeychainId: CryptoMaterial.keychains.keychain2.id, + clientHelper: new ClientHelper(), + serverHelper: new ServerHelper({}), }); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginRecipientGateway.localRepository?.reset(); + await pluginRecipientGateway.remoteRepository?.reset(); return pluginRecipientGateway; } @@ -624,19 +594,28 @@ export class CbdcBridgingAppDummyInfrastructure { // does the same thing, it just waits 10 seconds for good measure so there // might not be a way for us to avoid doing this, but if there is a way we // absolutely should not have timeouts like this, anywhere... - await new Promise((resolve) => setTimeout(resolve, 10000)); - - await fabricApiClient.runTransactionV1({ - contractName, - channelName, - params: ["name1", "symbol1", "8"], - methodName: "Initialize", - invocationType: FabricContractInvocationType.Send, - signingCredential: { - keychainId: CryptoMaterial.keychains.keychain1.id, - keychainRef: "userA", - }, - }); + let retries_2 = 0; + while (retries_2 <= 5) { + await new Promise((resolve) => setTimeout(resolve, 10000)); + + await fabricApiClient + .runTransactionV1({ + contractName, + channelName, + params: ["name1", "symbol1", "8"], + methodName: "Initialize", + invocationType: FabricContractInvocationType.Send, + signingCredential: { + keychainId: CryptoMaterial.keychains.keychain1.id, + keychainRef: "userA", + }, + }) + .then(() => (retries_2 = 6)) + .catch(() => + console.log("trying to Initialize fabric contract again"), + ); + retries_2++; + } }) .catch(() => console.log("trying to deploy fabric contract again")); retries++; diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/besu-satp-gateway.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/besu-satp-gateway.ts index 30d11dac31..5c3c0eb574 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/besu-satp-gateway.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/besu-satp-gateway.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { Knex } from "knex"; import { Configuration } from "@hyperledger/cactus-core-api"; import { DefaultApi as BesuApi, @@ -8,32 +7,18 @@ import { InvokeContractV1Request as BesuInvokeContractV1Request, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { - IKeyPair, + IPluginSatpGatewayConstructorOptions, PluginSatpGateway, } from "@hyperledger/cactus-plugin-satp-hermes"; import { SessionDataRollbackActionsPerformedEnum } from "@hyperledger/cactus-plugin-satp-hermes"; -import { ClientHelper } from "./client-helper"; -import { ServerHelper } from "./server-helper"; - -export interface IBesuSatpGatewayConstructorOptions { - name: string; - dltIDs: string[]; - instanceId: string; - keyPair?: IKeyPair; - backupGatewaysAllowed?: string[]; - - ipfsPath?: string; - - besuPath?: string; +export interface IBesuSatpGatewayConstructorOptions + extends IPluginSatpGatewayConstructorOptions { besuContractName?: string; besuWeb3SigningCredential?: Web3SigningCredential; besuKeychainId?: string; - fabricAssetID?: string; - fabricAssetSize?: string; besuAssetID?: string; - - knexConfig?: Knex.Config; + besuPath?: string; } export class BesuSatpGateway extends PluginSatpGateway { @@ -50,8 +35,10 @@ export class BesuSatpGateway extends PluginSatpGateway { keyPair: options.keyPair, backupGatewaysAllowed: options.backupGatewaysAllowed, ipfsPath: options.ipfsPath, - clientHelper: new ClientHelper(), - serverHelper: new ServerHelper({}), + clientHelper: options.clientHelper, + serverHelper: options.serverHelper, + knexLocalConfig: options.knexLocalConfig, + knexRemoteConfig: options.knexRemoteConfig, }); if (options.besuPath != undefined) this.defineBesuConnection(options); diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/client-helper.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/client-helper.ts index eeca7772a5..0dec1036d9 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/client-helper.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/client-helper.ts @@ -4,7 +4,7 @@ import { TransferInitializationV1Request, ClientGatewayHelper, } from "@hyperledger/cactus-plugin-satp-hermes"; -import { OdapMessageType } from "@hyperledger/cactus-plugin-satp-hermes"; +import { SatpMessageType } from "@hyperledger/cactus-plugin-satp-hermes"; import { FabricSatpGateway } from "./fabric-satp-gateway"; import { BesuSatpGateway } from "./besu-satp-gateway"; @@ -44,14 +44,16 @@ export class ClientHelper extends ClientGatewayHelper { throw new Error(`${fnTag}, session data is not correctly initialized`); } - if (!gateway.supportedDltIDs.includes(sessionData.recipientGatewayDltSystem)) { + if ( + !gateway.supportedDltIDs.includes(sessionData.recipientGatewayDltSystem) + ) { throw new Error( `${fnTag}, recipient gateway dlt system is not supported by this gateway`, ); } const initializationRequestMessage: TransferInitializationV1Request = { - messageType: OdapMessageType.InitializationRequest, + messageType: SatpMessageType.InitializationRequest, sessionID: sessionData.id, version: sessionData.version, // developer urn @@ -132,7 +134,7 @@ export class ClientHelper extends ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase1TransferInitiationRequestV1(initializationRequestMessage), "TransferInitializationRequest", diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/fabric-satp-gateway.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/fabric-satp-gateway.ts index 1f94afd71b..1dd7f57e6d 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/fabric-satp-gateway.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/fabric-satp-gateway.ts @@ -1,35 +1,23 @@ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { Knex } from "knex"; import { Configuration } from "@hyperledger/cactus-core-api"; import { DefaultApi as FabricApi, - FabricContractInvocationType, FabricSigningCredential, + FabricContractInvocationType, RunTransactionRequest as FabricRunTransactionRequest, } from "@hyperledger/cactus-plugin-ledger-connector-fabric"; import { - IKeyPair, + IPluginSatpGatewayConstructorOptions, PluginSatpGateway, } from "@hyperledger/cactus-plugin-satp-hermes"; import { SessionDataRollbackActionsPerformedEnum } from "@hyperledger/cactus-plugin-satp-hermes"; -import { ClientHelper } from "./client-helper"; -import { ServerHelper } from "./server-helper"; - -export interface IFabricSatpGatewayConstructorOptions { - name: string; - dltIDs: string[]; - instanceId: string; - keyPair?: IKeyPair; - backupGatewaysAllowed?: string[]; - ipfsPath?: string; +export interface IFabricSatpGatewayConstructorOptions + extends IPluginSatpGatewayConstructorOptions { fabricPath?: string; - fabricSigningCredential?: FabricSigningCredential; fabricChannelName?: string; fabricContractName?: string; - - knexConfig?: Knex.Config; } export class FabricSatpGateway extends PluginSatpGateway { @@ -46,8 +34,10 @@ export class FabricSatpGateway extends PluginSatpGateway { keyPair: options.keyPair, backupGatewaysAllowed: options.backupGatewaysAllowed, ipfsPath: options.ipfsPath, - clientHelper: new ClientHelper(), - serverHelper: new ServerHelper({}), + clientHelper: options.clientHelper, + serverHelper: options.serverHelper, + knexLocalConfig: options.knexLocalConfig, + knexRemoteConfig: options.knexRemoteConfig, }); if (options.fabricPath != undefined) this.defineFabricConnection(options); diff --git a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/server-helper.ts b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/server-helper.ts index 90ebbe81f8..c6dee4d1e7 100644 --- a/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/server-helper.ts +++ b/examples/cactus-example-cbdc-bridging-backend/src/main/typescript/satp-extension/server-helper.ts @@ -4,10 +4,10 @@ import { TransferInitializationV1Request, } from "@hyperledger/cactus-plugin-satp-hermes"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, + ServerGatewayHelper, } from "@hyperledger/cactus-plugin-satp-hermes"; -import { ServerGatewayHelper } from "@hyperledger/cactus-plugin-satp-hermes"; import { FabricSatpGateway } from "./fabric-satp-gateway"; import { LogLevelDesc } from "@hyperledger/cactus-common"; @@ -51,7 +51,7 @@ export class ServerHelper extends ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.InitializationRequest) { + if (request.messageType != SatpMessageType.InitializationRequest) { throw new Error( `${fnTag}, wrong message type for TransferInitializationRequest`, ); diff --git a/examples/cactus-example-cbdc-bridging-frontend/Dockerfile b/examples/cactus-example-cbdc-bridging-frontend/Dockerfile index 305ba5c628..26fc549f70 100644 --- a/examples/cactus-example-cbdc-bridging-frontend/Dockerfile +++ b/examples/cactus-example-cbdc-bridging-frontend/Dockerfile @@ -6,7 +6,7 @@ WORKDIR /usr/src/app COPY package.json ./ -RUN npm install +RUN npm install --legacy-peer-deps COPY . . diff --git a/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/LockAsset.json b/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/LockAsset.json index 50be30cea5..8d4ba2c7f8 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/LockAsset.json +++ b/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/LockAsset.json @@ -95,18 +95,18 @@ "type": "function" } ], - "metadata": "{\"compiler\":{\"version\":\"0.8.7+commit.e28d00a7\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"size\",\"type\":\"uint256\"}],\"name\":\"createAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"deleteAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getAsset\",\"outputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"creator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"isLock\",\"type\":\"bool\"},{\"internalType\":\"uint256\",\"name\":\"size\",\"type\":\"uint256\"}],\"internalType\":\"struct Asset\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"lockAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"unLockAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"/Users/jasonwang/cactus-odap-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol\":\"LockAsset\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\"},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"/Users/jasonwang/cactus-odap-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol\":{\"keccak256\":\"0x878fc27f22785593c1b35005ecf333e1f93e6dcf932b3d6e2b24d6be790b996a\",\"urls\":[\"bzz-raw://d8be1567f5e11fb718d8849f4dc9b8a8e467135ecd04c5f796c938b7363daaf2\",\"dweb:/ipfs/QmQuteuiTygZxjDnLiq3GNgJNFmPSRqbE2Q9vm85WgVbox\"]}},\"version\":1}", + "metadata": "{\"compiler\":{\"version\":\"0.8.7+commit.e28d00a7\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"size\",\"type\":\"uint256\"}],\"name\":\"createAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"deleteAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"getAsset\",\"outputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"creator\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"isLock\",\"type\":\"bool\"},{\"internalType\":\"uint256\",\"name\":\"size\",\"type\":\"uint256\"}],\"internalType\":\"struct Asset\",\"name\":\"\",\"type\":\"tuple\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"lockAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"id\",\"type\":\"string\"}],\"name\":\"unLockAsset\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"/Users/jasonwang/cactus-satp-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol\":\"LockAsset\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\"},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"/Users/jasonwang/cactus-satp-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol\":{\"keccak256\":\"0x878fc27f22785593c1b35005ecf333e1f93e6dcf932b3d6e2b24d6be790b996a\",\"urls\":[\"bzz-raw://d8be1567f5e11fb718d8849f4dc9b8a8e467135ecd04c5f796c938b7363daaf2\",\"dweb:/ipfs/QmQuteuiTygZxjDnLiq3GNgJNFmPSRqbE2Q9vm85WgVbox\"]}},\"version\":1}", "bytecode": "608060405234801561001057600080fd5b50610475806100206000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c80635e82d0a61461005c578063cd5286d014610071578063db9cc410146100b5578063def60e0d146100c8578063e24aa37c146100db575b600080fd5b61006f61006a3660046103a1565b6100ee565b005b61008461007f3660046103a1565b610164565b6040805182516001600160a01b03168152602080840151151590820152918101519082015260600160405180910390f35b61006f6100c33660046103e3565b6101dc565b61006f6100d63660046103a1565b610266565b61006f6100e93660046103a1565b6102ad565b6000806000848460405161010392919061042f565b9081526020016040518091039020600101541190508061012257600080fd5b60016000848460405161013692919061042f565b9081526040519081900360200190208054911515600160a01b0260ff60a01b19909216919091179055505050565b60408051606081018252600080825260208201819052918101919091526000838360405161019392919061042f565b908152604080516020928190038301812060608201835280546001600160a01b0381168352600160a01b900460ff16151593820193909352600190920154908201529392505050565b600081116101e957600080fd5b80600084846040516101fc92919061042f565b908152602001604051809103902060010181905550336000848460405161022492919061042f565b90815260405190819003602001812080546001600160a01b03939093166001600160a01b0319909316929092179091556000908190610136908690869061042f565b6000806000848460405161027b92919061042f565b9081526020016040518091039020600101541190508061029a57600080fd5b600080848460405161013692919061042f565b600080600084846040516102c292919061042f565b908152602001604051809103902060010154119050806102e157600080fd5b60008084846040516102f492919061042f565b9081526040519081900360200190205460ff600160a01b9091041690508061031b57600080fd5b6000848460405161032d92919061042f565b90815260405190819003602001902080546001600160a81b0319168155600060019091015550505050565b60008083601f84011261036a57600080fd5b50813567ffffffffffffffff81111561038257600080fd5b60208301915083602082850101111561039a57600080fd5b9250929050565b600080602083850312156103b457600080fd5b823567ffffffffffffffff8111156103cb57600080fd5b6103d785828601610358565b90969095509350505050565b6000806000604084860312156103f857600080fd5b833567ffffffffffffffff81111561040f57600080fd5b61041b86828701610358565b909790965060209590950135949350505050565b818382376000910190815291905056fea26469706673582212203e656ee2af105d66466451b5ca09a2a5780b62c439dd43befb63a10687d2423b64736f6c63430008070033", "deployedBytecode": "608060405234801561001057600080fd5b50600436106100575760003560e01c80635e82d0a61461005c578063cd5286d014610071578063db9cc410146100b5578063def60e0d146100c8578063e24aa37c146100db575b600080fd5b61006f61006a3660046103a1565b6100ee565b005b61008461007f3660046103a1565b610164565b6040805182516001600160a01b03168152602080840151151590820152918101519082015260600160405180910390f35b61006f6100c33660046103e3565b6101dc565b61006f6100d63660046103a1565b610266565b61006f6100e93660046103a1565b6102ad565b6000806000848460405161010392919061042f565b9081526020016040518091039020600101541190508061012257600080fd5b60016000848460405161013692919061042f565b9081526040519081900360200190208054911515600160a01b0260ff60a01b19909216919091179055505050565b60408051606081018252600080825260208201819052918101919091526000838360405161019392919061042f565b908152604080516020928190038301812060608201835280546001600160a01b0381168352600160a01b900460ff16151593820193909352600190920154908201529392505050565b600081116101e957600080fd5b80600084846040516101fc92919061042f565b908152602001604051809103902060010181905550336000848460405161022492919061042f565b90815260405190819003602001812080546001600160a01b03939093166001600160a01b0319909316929092179091556000908190610136908690869061042f565b6000806000848460405161027b92919061042f565b9081526020016040518091039020600101541190508061029a57600080fd5b600080848460405161013692919061042f565b600080600084846040516102c292919061042f565b908152602001604051809103902060010154119050806102e157600080fd5b60008084846040516102f492919061042f565b9081526040519081900360200190205460ff600160a01b9091041690508061031b57600080fd5b6000848460405161032d92919061042f565b90815260405190819003602001902080546001600160a81b0319168155600060019091015550505050565b60008083601f84011261036a57600080fd5b50813567ffffffffffffffff81111561038257600080fd5b60208301915083602082850101111561039a57600080fd5b9250929050565b600080602083850312156103b457600080fd5b823567ffffffffffffffff8111156103cb57600080fd5b6103d785828601610358565b90969095509350505050565b6000806000604084860312156103f857600080fd5b833567ffffffffffffffff81111561040f57600080fd5b61041b86828701610358565b909790965060209590950135949350505050565b818382376000910190815291905056fea26469706673582212203e656ee2af105d66466451b5ca09a2a5780b62c439dd43befb63a10687d2423b64736f6c63430008070033", "sourceMap": "543:1053:0:-:0;;;;;;;;;;;;;;;;;;;", "deployedSourceMap": "543:1053:0:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;946:154;;;;;;:::i;:::-;;:::i;:::-;;798:105;;;;;;:::i;:::-;;:::i;:::-;;;;1753:13:1;;-1:-1:-1;;;;;1749:39:1;1731:58;;1859:4;1847:17;;;1841:24;1834:32;1827:40;1805:20;;;1798:70;1912:17;;;1906:24;1884:20;;;1877:54;1719:2;1704:18;798:105:0;;;;;;;607:188;;;;;;:::i;:::-;;:::i;1144:157::-;;;;;;:::i;:::-;;:::i;1304:289::-;;;;;;:::i;:::-;;:::i;946:154::-;999:16;1034:1;1018:6;1025:2;;1018:10;;;;;;;:::i;:::-;;;;;;;;;;;;;:15;;;:17;999:36;;1051:11;1043:20;;;;;;1091:4;1071:6;1078:2;;1071:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:24;;;;;-1:-1:-1;;;1071:24:0;-1:-1:-1;;;;1071:24:0;;;;;;;;;-1:-1:-1;;;946:154:0:o;798:105::-;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;888:6:0;895:2;;888:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;881:17;;;;;;;-1:-1:-1;;;;;881:17:0;;;;-1:-1:-1;;;881:17:0;;;;;;;;;;;;;;;;;;;;;;888:10;798:105;-1:-1:-1;;;798:105:0:o;607:188::-;687:1;682:4;:6;674:15;;;;;;714:4;697:6;704:2;;697:10;;;;;;;:::i;:::-;;;;;;;;;;;;;:15;;:21;;;;747:10;726:6;733:2;;726:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:31;;-1:-1:-1;;;;;726:31:0;;;;-1:-1:-1;;;;;;726:31:0;;;;;;;;;;:18;;;;765:10;;772:2;;;;765:10;:::i;1144:157::-;1199:16;1234:1;1218:6;1225:2;;1218:10;;;;;;;:::i;:::-;;;;;;;;;;;;;:15;;;:17;1199:36;;1251:11;1243:20;;;;;;1291:5;1271:6;1278:2;;1271:10;;;;;;;:::i;1304:289::-;1360:16;1395:1;1379:6;1386:2;;1379:10;;;;;;;:::i;:::-;;;;;;;;;;;;;:15;;;:17;1360:36;;1412:11;1404:20;;;;;;1495:18;1516:6;1523:2;;1516:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:17;;-1:-1:-1;;;1516:17:0;;;;;-1:-1:-1;1516:17:0;1541:22;;;;;;1578:6;1585:2;;1578:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;1571:17;;-1:-1:-1;;;;;;1571:17:0;;;1578:10;1571:17;;;;;-1:-1:-1;;;;1304:289:0:o;14:348:1:-;66:8;76:6;130:3;123:4;115:6;111:17;107:27;97:55;;148:1;145;138:12;97:55;-1:-1:-1;171:20:1;;214:18;203:30;;200:50;;;246:1;243;236:12;200:50;283:4;275:6;271:17;259:29;;335:3;328:4;319:6;311;307:19;303:30;300:39;297:59;;;352:1;349;342:12;297:59;14:348;;;;;:::o;367:411::-;438:6;446;499:2;487:9;478:7;474:23;470:32;467:52;;;515:1;512;505:12;467:52;555:9;542:23;588:18;580:6;577:30;574:50;;;620:1;617;610:12;574:50;659:59;710:7;701:6;690:9;686:22;659:59;:::i;:::-;737:8;;633:85;;-1:-1:-1;367:411:1;-1:-1:-1;;;;367:411:1:o;783:479::-;863:6;871;879;932:2;920:9;911:7;907:23;903:32;900:52;;;948:1;945;938:12;900:52;988:9;975:23;1021:18;1013:6;1010:30;1007:50;;;1053:1;1050;1043:12;1007:50;1092:59;1143:7;1134:6;1123:9;1119:22;1092:59;:::i;:::-;1170:8;;1066:85;;-1:-1:-1;1252:2:1;1237:18;;;;1224:32;;783:479;-1:-1:-1;;;;783:479:1:o;1267:273::-;1452:6;1444;1439:3;1426:33;1408:3;1478:16;;1503:13;;;1478:16;1267:273;-1:-1:-1;1267:273:1:o", - "sourcePath": "/Users/jasonwang/cactus-odap-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol", + "sourcePath": "/Users/jasonwang/cactus-satp-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol", "compiler": { "name": "solc", "version": "0.8.7+commit.e28d00a7" }, "ast": { - "absolutePath": "/Users/jasonwang/cactus-odap-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol", + "absolutePath": "/Users/jasonwang/cactus-satp-merge/packages/cactus-plugin-ledger-connector-besu/src/test/solidity/hello-world-contract/lock-asset.sol", "exportedSymbols": { "Asset": [ 8 diff --git a/packages/cactus-plugin-satp-hermes/knex/knexfile-remote.ts b/packages/cactus-plugin-satp-hermes/knex/knexfile-remote.ts new file mode 100644 index 0000000000..27e1209742 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/knex/knexfile-remote.ts @@ -0,0 +1,16 @@ +import path from "path"; +import { v4 as uuidv4 } from "uuid"; + +// default configuration for knex +module.exports = { + development: { + client: "sqlite3", + connection: { + filename: path.resolve(__dirname, ".dev-remote.sqlite3"), + }, + migrations: { + directory: path.resolve(__dirname, "migrations"), + }, + useNullAsDefault: true, + }, +}; \ No newline at end of file diff --git a/packages/cactus-plugin-satp-hermes/knex/migrations/20240130234303_create_remote_logs_table.js b/packages/cactus-plugin-satp-hermes/knex/migrations/20240130234303_create_remote_logs_table.js new file mode 100644 index 0000000000..4eac46af46 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/knex/migrations/20240130234303_create_remote_logs_table.js @@ -0,0 +1,13 @@ +exports.up = async (knex) => { + return await knex.schema.createTable("remote-logs", function (table) { + table.string("key").notNullable(); + table.string("hash").notNullable(); + table.string("signature").notNullable(); + table.string("signerPubKey").notNullable(); + table.primary("key") + }); + }; + + exports.down = async (knex) => { + return await knex.schema.dropTable("remote-logs"); + }; diff --git a/packages/cactus-plugin-satp-hermes/package.json b/packages/cactus-plugin-satp-hermes/package.json index e8df3e07a2..b6f54310c6 100644 --- a/packages/cactus-plugin-satp-hermes/package.json +++ b/packages/cactus-plugin-satp-hermes/package.json @@ -38,6 +38,7 @@ "dist/*" ], "scripts": { + "build:dev:backend:postbuild": "mkdir -p ./dist/lib/main/knex && cp -r ./knex/* ./dist/lib/main/knex", "codegen": "run-p 'codegen:*'", "codegen:openapi": "npm run generate-sdk", "generate-sdk": "run-p 'generate-sdk:*'", diff --git a/packages/cactus-plugin-satp-hermes/src/main/json/openapi.json b/packages/cactus-plugin-satp-hermes/src/main/json/openapi.json index e9494fc563..55b9ee1f3f 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/json/openapi.json +++ b/packages/cactus-plugin-satp-hermes/src/main/json/openapi.json @@ -1226,7 +1226,7 @@ }, "required": ["sessionID", "type", "operation"] }, - "OdapMessage": { + "SatpMessage": { "type": "object", "properties": { "SequenceNumber": { diff --git a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/.openapi-generator/FILES b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/.openapi-generator/FILES index be28f6e89f..4f5a990219 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/.openapi-generator/FILES +++ b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/.openapi-generator/FILES @@ -33,8 +33,6 @@ src/main/kotlin/org/openapitools/client/models/History.kt src/main/kotlin/org/openapitools/client/models/LocalLog.kt src/main/kotlin/org/openapitools/client/models/LockEvidenceV1Request.kt src/main/kotlin/org/openapitools/client/models/LockEvidenceV1Response.kt -src/main/kotlin/org/openapitools/client/models/OdapMessage.kt -src/main/kotlin/org/openapitools/client/models/OdapMessageActionResponse.kt src/main/kotlin/org/openapitools/client/models/PayloadProfile.kt src/main/kotlin/org/openapitools/client/models/RecoverSuccessV1Message.kt src/main/kotlin/org/openapitools/client/models/RecoverUpdateAckV1Message.kt @@ -42,6 +40,8 @@ src/main/kotlin/org/openapitools/client/models/RecoverUpdateV1Message.kt src/main/kotlin/org/openapitools/client/models/RecoverV1Message.kt src/main/kotlin/org/openapitools/client/models/RollbackAckV1Message.kt src/main/kotlin/org/openapitools/client/models/RollbackV1Message.kt +src/main/kotlin/org/openapitools/client/models/SatpMessage.kt +src/main/kotlin/org/openapitools/client/models/SatpMessageActionResponse.kt src/main/kotlin/org/openapitools/client/models/SessionData.kt src/main/kotlin/org/openapitools/client/models/TransferCommenceV1Request.kt src/main/kotlin/org/openapitools/client/models/TransferCommenceV1Response.kt diff --git a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/README.md b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/README.md index 7c7825dc52..d4a3519e92 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/README.md +++ b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/README.md @@ -79,8 +79,6 @@ Class | Method | HTTP request | Description - [org.openapitools.client.models.LocalLog](docs/LocalLog.md) - [org.openapitools.client.models.LockEvidenceV1Request](docs/LockEvidenceV1Request.md) - [org.openapitools.client.models.LockEvidenceV1Response](docs/LockEvidenceV1Response.md) - - [org.openapitools.client.models.OdapMessage](docs/OdapMessage.md) - - [org.openapitools.client.models.OdapMessageActionResponse](docs/OdapMessageActionResponse.md) - [org.openapitools.client.models.PayloadProfile](docs/PayloadProfile.md) - [org.openapitools.client.models.RecoverSuccessV1Message](docs/RecoverSuccessV1Message.md) - [org.openapitools.client.models.RecoverUpdateAckV1Message](docs/RecoverUpdateAckV1Message.md) @@ -88,6 +86,8 @@ Class | Method | HTTP request | Description - [org.openapitools.client.models.RecoverV1Message](docs/RecoverV1Message.md) - [org.openapitools.client.models.RollbackAckV1Message](docs/RollbackAckV1Message.md) - [org.openapitools.client.models.RollbackV1Message](docs/RollbackV1Message.md) + - [org.openapitools.client.models.SatpMessage](docs/SatpMessage.md) + - [org.openapitools.client.models.SatpMessageActionResponse](docs/SatpMessageActionResponse.md) - [org.openapitools.client.models.SessionData](docs/SessionData.md) - [org.openapitools.client.models.TransferCommenceV1Request](docs/TransferCommenceV1Request.md) - [org.openapitools.client.models.TransferCommenceV1Response](docs/TransferCommenceV1Response.md) diff --git a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessage.kt b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessage.kt similarity index 90% rename from packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessage.kt rename to packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessage.kt index e5e4137e3d..ac22e1499d 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessage.kt +++ b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessage.kt @@ -15,8 +15,8 @@ package org.openapitools.client.models -import org.openapitools.client.models.OdapMessageActionResponse import org.openapitools.client.models.PayloadProfile +import org.openapitools.client.models.SatpMessageActionResponse import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @@ -39,13 +39,13 @@ import com.squareup.moshi.JsonClass */ -data class OdapMessage ( +data class SatpMessage ( @Json(name = "SequenceNumber") val sequenceNumber: java.math.BigDecimal? = null, @Json(name = "Phase") - val phase: OdapMessage.Phase? = null, + val phase: SatpMessage.Phase? = null, @Json(name = "ResourceURL") val resourceURL: kotlin.String? = null, @@ -54,10 +54,10 @@ data class OdapMessage ( val developerURN: kotlin.String? = null, @Json(name = "ActionResponse") - val actionResponse: OdapMessageActionResponse? = null, + val actionResponse: SatpMessageActionResponse? = null, @Json(name = "CredentialProfile") - val credentialProfile: OdapMessage.CredentialProfile? = null, + val credentialProfile: SatpMessage.CredentialProfile? = null, @Json(name = "CredentialBlock") val credentialBlock: kotlin.collections.List? = null, diff --git a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessageActionResponse.kt b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessageActionResponse.kt similarity index 89% rename from packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessageActionResponse.kt rename to packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessageActionResponse.kt index a13d3464bd..a636e823f0 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/OdapMessageActionResponse.kt +++ b/packages/cactus-plugin-satp-hermes/src/main/kotlin/generated/openapi/kotlin-client/src/main/kotlin/org/openapitools/client/models/SatpMessageActionResponse.kt @@ -27,10 +27,10 @@ import com.squareup.moshi.JsonClass */ -data class OdapMessageActionResponse ( +data class SatpMessageActionResponse ( @Json(name = "ResponseCode") - val responseCode: OdapMessageActionResponse.ResponseCode? = null, + val responseCode: SatpMessageActionResponse.ResponseCode? = null, @Json(name = "Arguments") val arguments: kotlin.collections.List? = null diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/besu-satp-gateway.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/besu-satp-gateway.ts index 478d3e3819..248b1b494a 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/besu-satp-gateway.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/besu-satp-gateway.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { Knex } from "knex"; import { Configuration } from "@hyperledger/cactus-core-api"; import { SessionDataRollbackActionsPerformedEnum } from "../generated/openapi/typescript-axios"; import { @@ -8,25 +7,18 @@ import { EthContractInvocationType, InvokeContractV1Request as BesuInvokeContractV1Request, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; -import { IKeyPair, PluginSatpGateway } from "./plugin-satp-gateway"; -import { ClientGatewayHelper } from "./client/client-helper"; -import { ServerGatewayHelper } from "./server/server-helper"; - -export interface IBesuSatpGatewayConstructorOptions { - name: string; - dltIDs: string[]; - instanceId: string; - keyPair?: IKeyPair; - backupGatewaysAllowed?: string[]; - ipfsPath?: string; +import { + IPluginSatpGatewayConstructorOptions, + PluginSatpGateway, +} from "./plugin-satp-gateway"; + +export interface IBesuSatpGatewayConstructorOptions + extends IPluginSatpGatewayConstructorOptions { besuPath?: string; besuContractName?: string; besuWeb3SigningCredential?: Web3SigningCredential; besuKeychainId?: string; besuAssetID?: string; - knexConfig?: Knex.Config; - clientHelper: ClientGatewayHelper; - serverHelper: ServerGatewayHelper; } export class BesuSatpGateway extends PluginSatpGateway { @@ -45,7 +37,8 @@ export class BesuSatpGateway extends PluginSatpGateway { ipfsPath: options.ipfsPath, clientHelper: options.clientHelper, serverHelper: options.serverHelper, - knexConfig: options.knexConfig, + knexLocalConfig: options.knexLocalConfig, + knexRemoteConfig: options.knexRemoteConfig, }); if (options.besuPath != undefined) this.defineBesuConnection(options); diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/client/client-helper.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/client/client-helper.ts index e612c324b2..cd97907313 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/client/client-helper.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/client/client-helper.ts @@ -13,7 +13,7 @@ import { CommitFinalV1Response, TransferCompleteV1Request, } from "../../public-api"; -import { OdapMessageType, PluginSatpGateway } from "../plugin-satp-gateway"; +import { SatpMessageType, PluginSatpGateway } from "../plugin-satp-gateway"; export class ClientGatewayHelper { public static readonly CLASS_NAME = "ClientGatewayHelper"; @@ -66,14 +66,16 @@ export class ClientGatewayHelper { throw new Error(`${fnTag}, session data is not correctly initialized`); } - if (!gateway.supportedDltIDs.includes(sessionData.recipientGatewayDltSystem)) { + if ( + !gateway.supportedDltIDs.includes(sessionData.recipientGatewayDltSystem) + ) { throw new Error( `${fnTag}, recipient gateway dlt system is not supported by this gateway`, ); } const initializationRequestMessage: TransferInitializationV1Request = { - messageType: OdapMessageType.InitializationRequest, + messageType: SatpMessageType.InitializationRequest, sessionID: sessionData.id, version: sessionData.version, // developer urn @@ -131,7 +133,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase1TransferInitiationRequestV1(initializationRequestMessage), "TransferInitializationRequest", @@ -150,7 +152,7 @@ export class ClientGatewayHelper { throw new Error(`${fnTag}, session data is undefined`); } - if (response.messageType != OdapMessageType.InitializationResponse) { + if (response.messageType != SatpMessageType.InitializationResponse) { throw new Error( `${fnTag}, wrong message type for TransferInitializationResponse`, ); @@ -177,7 +179,9 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(response, sessionData.recipientGatewayPubkey)) { + if ( + !gateway.verifySignature(response, sessionData.recipientGatewayPubkey) + ) { throw new Error( `${fnTag}, TransferInitializationResponse message signature verification failed`, ); @@ -235,7 +239,7 @@ export class ClientGatewayHelper { ).toString(); const transferCommenceRequestMessage: TransferCommenceV1Request = { - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, // originatorPubkey: sessionData.originatorPubkey, // beneficiaryPubkey: sessionData.beneficiaryPubkey, originatorPubkey: "sessionData.originatorPubkey", @@ -282,7 +286,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase2TransferCommenceRequestV1(transferCommenceRequestMessage), "TransferCommenceRequest", @@ -301,7 +305,7 @@ export class ClientGatewayHelper { throw new Error(`${fnTag}, session data is undefined`); } - if (response.messageType != OdapMessageType.TransferCommenceResponse) { + if (response.messageType != SatpMessageType.TransferCommenceResponse) { throw new Error( `${fnTag}, wrong message type for TransferCommenceResponse`, ); @@ -334,7 +338,9 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(response, sessionData.recipientGatewayPubkey)) { + if ( + !gateway.verifySignature(response, sessionData.recipientGatewayPubkey) + ) { throw new Error( `${fnTag}, TransferCommenceResponse message signature verification failed`, ); @@ -380,7 +386,7 @@ export class ClientGatewayHelper { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceRequest, + messageType: SatpMessageType.LockEvidenceRequest, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, lockEvidenceClaim: sessionData.lockEvidenceClaim, @@ -422,7 +428,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase2LockEvidenceRequestV1(lockEvidenceRequestMessage), "LockEvidenceRequest", @@ -443,7 +449,7 @@ export class ClientGatewayHelper { ); } - if (response.messageType != OdapMessageType.LockEvidenceResponse) { + if (response.messageType != SatpMessageType.LockEvidenceResponse) { throw new Error(`${fnTag}, wrong message type for LockEvidenceResponse`); } @@ -474,7 +480,9 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(response, sessionData.recipientGatewayPubkey)) { + if ( + !gateway.verifySignature(response, sessionData.recipientGatewayPubkey) + ) { throw new Error( `${fnTag}, LockEvidenceResponse message signature verification failed`, ); @@ -518,7 +526,7 @@ export class ClientGatewayHelper { const commitPrepareRequestMessage: CommitPreparationV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitPreparationRequest, + messageType: SatpMessageType.CommitPreparationRequest, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, hashLockEvidenceAck: sessionData.lockEvidenceResponseMessageHash, @@ -556,7 +564,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase3CommitPreparationRequestV1(commitPrepareRequestMessage), "CommitPreparationRequest", @@ -577,7 +585,7 @@ export class ClientGatewayHelper { ); } - if (response.messageType != OdapMessageType.CommitPreparationResponse) { + if (response.messageType != SatpMessageType.CommitPreparationResponse) { throw new Error( `${fnTag}, wrong message type for CommitPreparationResponse`, ); @@ -609,7 +617,9 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(response, sessionData.recipientGatewayPubkey)) { + if ( + !gateway.verifySignature(response, sessionData.recipientGatewayPubkey) + ) { throw new Error( `${fnTag}, CommitPreparationResponse message signature verification failed`, ); @@ -655,7 +665,7 @@ export class ClientGatewayHelper { const commitFinalRequestMessage: CommitFinalV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalRequest, + messageType: SatpMessageType.CommitFinalRequest, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, commitFinalClaim: sessionData.commitFinalClaim, @@ -694,7 +704,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase3CommitFinalRequestV1(commitFinalRequestMessage), "CommitFinalRequest", @@ -715,7 +725,7 @@ export class ClientGatewayHelper { ); } - if (response.messageType != OdapMessageType.CommitFinalResponse) { + if (response.messageType != SatpMessageType.CommitFinalResponse) { throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); } @@ -747,15 +757,17 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(response, sessionData.recipientGatewayPubkey)) { + if ( + !gateway.verifySignature(response, sessionData.recipientGatewayPubkey) + ) { throw new Error( `${fnTag}, CommitFinalResponse message signature verification failed`, ); } const claimHash = SHA256(response.commitAcknowledgementClaim).toString(); - const retrievedClaim = await gateway.getLogFromIPFS( - PluginSatpGateway.getOdapLogKey(sessionID, "proof", "create"), + const retrievedClaim = await gateway.getLogFromRemote( + PluginSatpGateway.getSatpLogKey(sessionID, "proof", "create"), ); if (claimHash != retrievedClaim.hash) { @@ -764,7 +776,9 @@ export class ClientGatewayHelper { ); } - if (!gateway.verifySignature(retrievedClaim, response.serverIdentityPubkey)) { + if ( + !gateway.verifySignature(retrievedClaim, response.serverIdentityPubkey) + ) { throw new Error( `${fnTag}, Commit Acknowledgement Claim signature verification failed`, ); @@ -812,7 +826,7 @@ export class ClientGatewayHelper { const transferCompleteRequestMessage: TransferCompleteV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCompleteRequest, + messageType: SatpMessageType.TransferCompleteRequest, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, hashCommitFinalAck: sessionData.commitFinalResponseMessageHash, @@ -850,7 +864,7 @@ export class ClientGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.recipientBasePath, ).phase3TransferCompleteRequestV1(transferCompleteRequestMessage), "TransferCompleteRequest", diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/fabric-satp-gateway.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/fabric-satp-gateway.ts index 83b5dc0db3..05a4233ee1 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/fabric-satp-gateway.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/fabric-satp-gateway.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { Knex } from "knex"; import { Configuration } from "@hyperledger/cactus-core-api"; import { DefaultApi as FabricApi, @@ -7,25 +6,18 @@ import { FabricSigningCredential, RunTransactionRequest as FabricRunTransactionRequest, } from "@hyperledger/cactus-plugin-ledger-connector-fabric"; -import { IKeyPair, PluginSatpGateway } from "./plugin-satp-gateway"; +import { + IPluginSatpGatewayConstructorOptions, + PluginSatpGateway, +} from "./plugin-satp-gateway"; import { SessionDataRollbackActionsPerformedEnum } from "../generated/openapi/typescript-axios"; -import { ClientGatewayHelper } from "./client/client-helper"; -import { ServerGatewayHelper } from "./server/server-helper"; - -export interface IFabricSatpGatewayConstructorOptions { - name: string; - dltIDs: string[]; - instanceId: string; - keyPair?: IKeyPair; - backupGatewaysAllowed?: string[]; - ipfsPath?: string; + +export interface IFabricSatpGatewayConstructorOptions + extends IPluginSatpGatewayConstructorOptions { fabricPath?: string; fabricSigningCredential?: FabricSigningCredential; fabricChannelName?: string; fabricContractName?: string; - knexConfig?: Knex.Config; - clientHelper: ClientGatewayHelper; - serverHelper: ServerGatewayHelper; } export class FabricSatpGateway extends PluginSatpGateway { @@ -44,7 +36,8 @@ export class FabricSatpGateway extends PluginSatpGateway { ipfsPath: options.ipfsPath, clientHelper: options.clientHelper, serverHelper: options.serverHelper, - knexConfig: options.knexConfig, + knexLocalConfig: options.knexLocalConfig, + knexRemoteConfig: options.knexRemoteConfig, }); if (options.fabricPath != undefined) this.defineFabricConnection(options); diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/plugin-satp-gateway.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/plugin-satp-gateway.ts index f2a2773f0d..aa68b799a6 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/plugin-satp-gateway.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/plugin-satp-gateway.ts @@ -4,7 +4,7 @@ import type { Server as SecureServer } from "https"; import { Optional } from "typescript-optional"; import type { Express } from "express"; import { v4 as uuidV4 } from "uuid"; -import knex, { Knex } from "knex"; +import { Knex } from "knex"; import OAS from "../../json/openapi.json"; import { Secp256k1Keys, @@ -14,7 +14,6 @@ import { JsObjectSigner, IJsObjectSignerOptions, } from "@hyperledger/cactus-common"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { ICactusPlugin, IPluginWebService, @@ -23,7 +22,7 @@ import { } from "@hyperledger/cactus-core-api"; import { TransferInitializationV1Response, - DefaultApi as OdapApi, + DefaultApi as SatpApi, SessionData, ClientV1Request, TransferCommenceV1Request, @@ -90,8 +89,15 @@ import { } from "./recovery/rollback-ack"; import { ClientRequestEndpointV1 } from "../web-services/client-side/client-request-endpoint"; import { RollbackAckMessageEndpointV1 } from "../web-services/recovery/rollback-ack-message-endpoint"; +import { KnexLocalLogRepository as LocalLogRepository } from "./repository/knex-local-log-repository"; +import { IPFSRemoteLogRepository } from "./repository/ipfs-remote-log-repository"; +import { KnexRemoteLogRepository } from "./repository/knex-remote-log-repository"; +import { + ILocalLogRepository, + IRemoteLogRepository, +} from "./repository/interfaces/repository"; -export enum OdapMessageType { +export enum SatpMessageType { InitializationRequest = "urn:ietf:satp:msgtype:init-transfer-msg", InitializationResponse = "urn:ietf:satp:msgtype:init-transfer-ack-msg", TransferCommenceRequest = "urn:ietf:satp:msgtype:transfer-commence-msg", @@ -111,10 +117,14 @@ export interface IPluginSatpGatewayConstructorOptions { instanceId: string; keyPair?: IKeyPair; backupGatewaysAllowed?: string[]; - ipfsPath?: string; clientHelper: ClientGatewayHelper; serverHelper: ServerGatewayHelper; - knexConfig?: Knex.Config; + knexLocalConfig?: Knex.Config; + + // below are the two options to store remote logs. Either using a DB simulating a remote DB or using + // IPFS which ensures a different notion of accountability. If both are set, the IPFS will be used + knexRemoteConfig?: Knex.Config; + ipfsPath?: string; } export interface IKeyPair { publicKey: Uint8Array; @@ -128,10 +138,19 @@ export interface IRemoteLog { signerPubKey: string; } +export interface ILocalLog { + key?: string; + sessionID: string; + data?: string; + type: string; + operation: string; + timestamp?: string; +} + export abstract class PluginSatpGateway implements ICactusPlugin, IPluginWebService { - public static readonly CLASS_NAME = "OdapGateway"; + public static readonly CLASS_NAME = "SatpGateway"; private readonly instanceId: string; private readonly _log: Logger; @@ -139,13 +158,11 @@ export abstract class PluginSatpGateway private _pubKey: string; private _privKey: string; - public ipfsApi?: ObjectStoreIpfsApi; - - public database?: Knex; + public localRepository?: ILocalLogRepository; + public remoteRepository?: IRemoteLogRepository; private endpoints: IWebServiceEndpoint[] | undefined; - //map[]object, object refer to a state - //of a specific comminications + private _supportedDltIDs: string[]; private _backupGatewaysAllowed: string[]; @@ -185,26 +202,13 @@ export abstract class PluginSatpGateway this._clientHelper = options.clientHelper; this._serverHelper = options.serverHelper; - if (options.ipfsPath != undefined) this.defineIpfsConnection(options); - - this.defineKnexConnection(options.knexConfig); - } - - public defineKnexConnection(config: Knex.Config | undefined): void { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const configFile = require("../../../../knex/knexfile.ts")[ - process.env.ENVIRONMENT || "development" - ]; - - this.database = knex(config || configFile); - } + this.remoteRepository = new KnexRemoteLogRepository( + options.knexRemoteConfig, + ); + if (options.ipfsPath != undefined) + this.remoteRepository = new IPFSRemoteLogRepository(options.ipfsPath); - private defineIpfsConnection( - options: IPluginSatpGatewayConstructorOptions, - ): void { - const config = new Configuration({ basePath: options.ipfsPath }); - const apiClient = new ObjectStoreIpfsApi(config); - this.ipfsApi = apiClient; + this.localRepository = new LocalLogRepository(options.knexLocalConfig); } public get className(): string { @@ -377,16 +381,6 @@ export abstract class PluginSatpGateway return this._log; } - getDatabaseInstance(): Knex.QueryBuilder { - const fnTag = `${this.className}#getDatabaseInstance()`; - - if (this.database == undefined) { - throw new Error(`${fnTag}, database is undefined`); - } - - return this.database("logs"); - } - isClientGateway(sessionID: string): boolean { const fnTag = `${this.className}#isClientGateway()`; @@ -428,7 +422,7 @@ export abstract class PluginSatpGateway return Buffer.from(array).toString("hex"); } - static getOdapLogKey( + static getSatpLogKey( sessionID: string, type: string, operation: string, @@ -441,18 +435,11 @@ export abstract class PluginSatpGateway this.log.info(`${fnTag}, recovering open sessions...`); - if (this.database == undefined) { + if (this.localRepository?.database == undefined) { throw new Error(`${fnTag}, database is undefined`); } - const logs: LocalLog[] = await this.getDatabaseInstance() - .select( - this.database.raw( - "sessionId, key, data, type, operation, MAX(timestamp) as timestamp", - ), - ) - .whereNot({ type: "proof" }) - .groupBy("sessionID"); + const logs: LocalLog[] = await this.localRepository.readLogsNotProofs(); for (const log of logs) { const sessionID = log.sessionID; @@ -481,49 +468,40 @@ export abstract class PluginSatpGateway } } - async storeInDatabase(localLog: LocalLog) { + async storeInDatabase(LocalLog: ILocalLog) { const fnTag = `${this.className}#storeInDatabase()`; - this.log.info( - `${fnTag}, Storing locally log: ${JSON.stringify(localLog)}`, - ); + this.log.info(`${fnTag}, Storing locally log: ${JSON.stringify(LocalLog)}`); - await this.getDatabaseInstance().insert(localLog); + await this.localRepository?.create(LocalLog); } - async storeInIPFS(key: string, hash: string) { - const fnTag = `${this.className}#storeInIPFS()`; + async storeRemoteLog(key: string, hash: string) { + const fnTag = `${this.className}#storeRemoteLog()`; - if (this.ipfsApi == undefined) return; - - const ipfsLog: IRemoteLog = { + const remoteLog: IRemoteLog = { key: key, hash: hash, signature: "", signerPubKey: this.pubKey, }; - ipfsLog.signature = PluginSatpGateway.bufArray2HexStr( - await this.sign(JSON.stringify(ipfsLog)), + remoteLog.signature = PluginSatpGateway.bufArray2HexStr( + this.sign(JSON.stringify(remoteLog)), ); - const logBase64 = Buffer.from(JSON.stringify(ipfsLog)).toString("base64"); - - this.log.info(`${fnTag}, Storing in ipfs log: ${JSON.stringify(ipfsLog)}`); + this.log.info(`${fnTag}, Storing remote log: ${JSON.stringify(remoteLog)}`); - const response = await this.ipfsApi.setObjectV1({ - key: key, - value: logBase64, - }); + const response = await this.remoteRepository?.create(remoteLog); if (response.status < 200 && response.status > 299) { - throw new Error(`${fnTag}, error when logging to ipfs`); + throw new Error( + `${fnTag}, got response ${response.status} when logging to remote`, + ); } } async storeLog(localLog: LocalLog): Promise { - if (this.ipfsApi == undefined) return; - - localLog.key = PluginSatpGateway.getOdapLogKey( + localLog.key = PluginSatpGateway.getSatpLogKey( localLog.sessionID, localLog.type, localLog.operation, @@ -545,13 +523,13 @@ export abstract class PluginSatpGateway ]), ).toString(); - await this.storeInIPFS(localLog.key, hash); + await this.storeRemoteLog(localLog.key, hash); } - async storeProof(localLog: LocalLog): Promise { - if (this.ipfsApi == undefined || localLog.data == undefined) return; + async storeProof(localLog: ILocalLog): Promise { + if (localLog.data == undefined) return; - localLog.key = PluginSatpGateway.getOdapLogKey( + localLog.key = PluginSatpGateway.getSatpLogKey( localLog.sessionID, localLog.type, localLog.operation, @@ -562,21 +540,17 @@ export abstract class PluginSatpGateway const hash = SHA256(localLog.data).toString(); - await this.storeInIPFS(localLog.key, hash); + await this.storeRemoteLog(localLog.key, hash); } - async getLogFromDatabase(logKey: string): Promise { + async getLogFromDatabase(logKey: string): Promise { const fnTag = `${this.className}#getLogFromDatabase()`; this.log.info(`${fnTag}, retrieving log with key ${logKey}`); - return await this.getDatabaseInstance() - .where({ key: logKey }) - .first() - .then((row) => { - this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`); - - return row; - }); + return await this.localRepository?.readById(logKey).then((row) => { + this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`); + return row; + }); } async getLastLogFromDatabase( @@ -585,26 +559,20 @@ export abstract class PluginSatpGateway const fnTag = `${this.className}#getLastLog()`; this.log.info(`${fnTag}, retrieving last log from sessionID ${sessionID}`); - return await this.getDatabaseInstance() - .orderBy("timestamp", "desc") - .where({ sessionID: sessionID }) - .first() - .then((row) => { - this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`); - - return row; - }); + return await this.localRepository?.readLastestLog(sessionID).then((row) => { + this.log.info(`${fnTag}, retrieved log ${JSON.stringify(row)}`); + return row; + }); } async getLogsMoreRecentThanTimestamp( timestamp: string, - ): Promise { + ): Promise { const fnTag = `${this.className}#getLogsMoreRecentThanTimestamp()`; this.log.info(`${fnTag}, retrieving logs more recent than ${timestamp}`); - const logs: LocalLog[] = await this.getDatabaseInstance() - .where("timestamp", ">", timestamp) - .whereNot("type", "like", "%proof%"); + const logs: ILocalLog[] | undefined = + await this.localRepository?.readLogsMoreRecentThanTimestamp(timestamp); if (logs == undefined) { throw new Error(`${fnTag}, error when retrieving log from database`); @@ -615,43 +583,33 @@ export abstract class PluginSatpGateway return logs; } - async getLogFromIPFS(logKey: string): Promise { - const fnTag = `${this.className}#getOdapLogFromIPFS()`; + async getLogFromRemote(logKey: string): Promise { + const fnTag = `${this.className}#getSatpLogFromIPFS()`; this.log.info(`Retrieving log with key: <${logKey}>`); - if (this.ipfsApi == undefined) { - throw new Error(`${fnTag}, ipfs is not defined`); - } - - const response = await this.ipfsApi.getObjectV1({ - key: logKey, - }); - - if (response.status < 200 && response.status > 299) { - throw new Error(`${fnTag}, error when logging to ipfs`); - } + try { + const log = await this.remoteRepository?.readById(logKey); - const log: IRemoteLog = JSON.parse( - Buffer.from(response.data.value, "base64").toString(), - ); + if (log == undefined || log?.signature == undefined) { + throw new Error(`${fnTag}, the log or its signature is not defined`); + } - if (log == undefined || log.signature == undefined) { - throw new Error(`${fnTag}, the log or its signature is not defined`); - } + if (!this.verifySignature(log, log.signerPubKey)) { + throw new Error(`${fnTag}, received log with invalid signature`); + } - if (!this.verifySignature(log, log.signerPubKey)) { - throw new Error(`${fnTag}, received log with invalid signature`); + return log; + } catch { + throw new Error(`${fnTag}, error reading from remote log`); } - - return log; } - static getOdapAPI(basePath: string): OdapApi { - const config = new Configuration({ + static getSatpAPI(basePath: string): SatpApi { + const satpServerApiConfig = new Configuration({ basePath: basePath, }); - return new OdapApi(config); + return new SatpApi(satpServerApiConfig); } async deleteDatabaseEntries(sessionID: string) { @@ -659,11 +617,11 @@ export abstract class PluginSatpGateway `deleting logs from database associated with sessionID: ${sessionID}`, ); - await this.getDatabaseInstance().where({ sessionID: sessionID }).del(); + await this.localRepository?.deleteBySessionId(sessionID); } - async resumeOdapSession(sessionID: string, remote: boolean) { - const fnTag = `${this.className}#continueOdapSession()`; + async resumeSatpSession(sessionID: string, remote: boolean) { + const fnTag = `${this.className}#continueSatpSession()`; const sessionData = this.sessions.get(sessionID); if ( @@ -1061,7 +1019,7 @@ export abstract class PluginSatpGateway this.updateLastMessageReceivedTimestamp(request.sessionID); await checkValidRecoverSuccessMessage(request, this); - await this.resumeOdapSession(request.sessionID, true); + await this.resumeSatpSession(request.sessionID, true); } async onRollbackMessageReceived(request: RollbackV1Message): Promise { @@ -1091,8 +1049,8 @@ export abstract class PluginSatpGateway //this.deleteDatabaseEntries(request.sessionID); } - async runOdap(request: ClientV1Request): Promise { - const fnTag = `${this.className}#runOdap()`; + async runSatp(request: ClientV1Request): Promise { + const fnTag = `${this.className}#runSatp()`; this.log.info(`${fnTag}, start processing, time: ${Date.now()}`); this.log.info( `client gateway received ClientRequest: ${JSON.stringify(request)}`, diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-success.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-success.ts index 0a5920f6ea..ce7fde8f88 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-success.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-success.ts @@ -46,7 +46,7 @@ export async function sendRecoverSuccessMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -75,7 +75,7 @@ export async function checkValidRecoverSuccessMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } @@ -89,7 +89,7 @@ export async function checkValidRecoverSuccessMessage( ); } - // storeSessionData(response, odap); + // storeSessionData(response, satp); log.info(`RecoverSuccessMessage passed all checks.`); } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update-ack.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update-ack.ts index ce7a9a06c0..b6233120fb 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update-ack.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update-ack.ts @@ -49,7 +49,7 @@ export async function sendRecoverUpdateAckMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -78,7 +78,7 @@ export async function checkValidRecoverUpdateAckMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } @@ -91,7 +91,7 @@ export async function checkValidRecoverUpdateAckMessage( ); } - // storeSessionData(response, odap); + // storeSessionData(response, satp); log.info(`RecoverUpdateAckMessage passed all checks.`); } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update.ts index eb344cda8b..82c1d5e7ed 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover-update.ts @@ -5,7 +5,6 @@ import { import { LoggerProvider } from "@hyperledger/cactus-common"; import { PluginSatpGateway } from "../plugin-satp-gateway"; import { SHA256 } from "crypto-js"; -// import { SHA256 } from "crypto-js"; const log = LoggerProvider.getOrCreate({ level: "INFO", @@ -58,7 +57,7 @@ export async function sendRecoverUpdateMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -87,7 +86,7 @@ export async function checkValidRecoverUpdateMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } @@ -110,7 +109,7 @@ export async function checkValidRecoverUpdateMessage( log.info(`${fnTag}, received log: ${JSON.stringify(recLog)}`); - const ipfsLog = await gateway.getLogFromIPFS(recLog.key); + const ipfsLog = await gateway.getLogFromRemote(recLog.key); const hash = SHA256(JSON.stringify(recLog)).toString(); diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover.ts index 1b62b52a32..1a0d0d4194 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/recover.ts @@ -54,7 +54,7 @@ export async function sendRecoverMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -119,7 +119,7 @@ export async function checkValidRecoverMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback-ack.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback-ack.ts index 4b4f1683d5..b1126388fd 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback-ack.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback-ack.ts @@ -49,7 +49,7 @@ export async function sendRollbackAckMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -78,7 +78,7 @@ export async function checkValidRollbackAckMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback.ts index aedc57430a..75f9782a09 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/recovery/rollback.ts @@ -51,7 +51,7 @@ export async function sendRollbackMessage( await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( gateway.isClientGateway(sessionID) ? sessionData.recipientBasePath : sessionData.sourceBasePath, @@ -80,7 +80,7 @@ export async function checkValidRollbackMessage( throw new Error(`${fnTag}, session data is undefined`); } - // if (response.messageType != OdapMessageType.CommitFinalResponse) { + // if (response.messageType != SatpMessageType.CommitFinalResponse) { // throw new Error(`${fnTag}, wrong message type for CommitFinalResponse`); // } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/interfaces/repository.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/interfaces/repository.ts new file mode 100644 index 0000000000..9526328bf5 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/interfaces/repository.ts @@ -0,0 +1,28 @@ +import { IRemoteLog, ILocalLog } from "../../plugin-satp-gateway"; + +export interface IRepository { + readById(id: K): Promise; + create(entity: T): any; + destroy(): any; + reset(): any; +} + +export interface ILocalLogRepository extends IRepository { + database: any; + readById(id: string): Promise; + readLogsNotProofs(): Promise; + readLogsMoreRecentThanTimestamp(timestamp: string): Promise; + readLastestLog(sessionID: string): Promise; + create(log: ILocalLog): Promise; + deleteBySessionId(log: string): any; + destroy(): any; + reset(): any; +} + +export interface IRemoteLogRepository extends IRepository { + database: any; + readById(id: string): Promise; + create(log: IRemoteLog): any; + destroy(): any; + reset(): any; +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/ipfs-remote-log-repository.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/ipfs-remote-log-repository.ts new file mode 100644 index 0000000000..aafc69ef34 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/ipfs-remote-log-repository.ts @@ -0,0 +1,52 @@ +import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; +import { Configuration } from "@hyperledger/cactus-core-api"; +import { IRemoteLogRepository } from "./interfaces/repository"; +import { IRemoteLog } from "../plugin-satp-gateway"; + +export class IPFSRemoteLogRepository implements IRemoteLogRepository { + public static readonly CLASS_NAME = "IPFSRemoteLogRepository"; + readonly database: ObjectStoreIpfsApi; + + public constructor(ipfsPath: string) { + const config = new Configuration({ basePath: ipfsPath }); + const apiClient = new ObjectStoreIpfsApi(config); + this.database = apiClient; + } + + public get className(): string { + return IPFSRemoteLogRepository.CLASS_NAME; + } + + readById(logKey: string): Promise { + const fnTag = `${this.className}#readById()`; + + return this.database + .getObjectV1({ key: logKey }) + .then((response: any) => { + return JSON.parse( + Buffer.from(response.data.value, "base64").toString(), + ); + }) + .catch(() => { + throw new Error(`${fnTag}, error when logging to ipfs`); + }); + } + + create(log: IRemoteLog): any { + const fnTag = `${this.className}#create()`; + const logBase64 = Buffer.from(JSON.stringify(log)).toString("base64"); + + return this.database + .setObjectV1({ + key: log.key, + value: logBase64, + }) + .catch(() => { + throw new Error(`${fnTag}, error when logging to ipfs`); + }); + } + + async reset() {} + + async destroy() {} +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-local-log-repository.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-local-log-repository.ts new file mode 100644 index 0000000000..65c07b10de --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-local-log-repository.ts @@ -0,0 +1,65 @@ +import { ILocalLog } from "../plugin-satp-gateway"; +import { ILocalLogRepository } from "./interfaces/repository"; +import knex, { Knex } from "knex"; + +export class KnexLocalLogRepository implements ILocalLogRepository { + readonly database: Knex; + + public constructor(config: Knex.Config | undefined) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const configFile = require("../../../knex/knexfile.ts")[ + process.env.ENVIRONMENT || "development" + ]; + + this.database = knex(config || configFile); + } + + getLogsTable(): Knex.QueryBuilder { + return this.database("logs"); + } + + readById(logKey: string): Promise { + return this.getLogsTable().where({ key: logKey }).first(); + } + + readLastestLog(sessionID: string): Promise { + return this.getLogsTable() + .orderBy("timestamp", "desc") + .where({ sessionID: sessionID }) + .first(); + } + + readLogsMoreRecentThanTimestamp(timestamp: string): Promise { + return this.getLogsTable() + .where("timestamp", ">", timestamp) + .whereNot("type", "like", "%proof%"); + } + + create(log: ILocalLog): any { + return this.getLogsTable().insert(log); + } + + deleteBySessionId(sessionID: string): any { + return this.database().where({ sessionID: sessionID }).del(); + } + + readLogsNotProofs(): Promise { + return this.getLogsTable() + .select( + this.database.raw( + "sessionID, key, data, type, operation, MAX(timestamp) as timestamp", + ), + ) + .whereNot({ type: "proof" }) + .groupBy("sessionID"); + } + + async reset() { + await this.database.migrate.rollback(); + await this.database.migrate.latest(); + } + + async destroy() { + await this.database.destroy(); + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-remote-log-repository.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-remote-log-repository.ts new file mode 100644 index 0000000000..8d064da275 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/repository/knex-remote-log-repository.ts @@ -0,0 +1,40 @@ +import { IRemoteLogRepository } from "./interfaces/repository"; +import { IRemoteLog } from "../plugin-satp-gateway"; +import knex, { Knex } from "knex"; + +export class KnexRemoteLogRepository implements IRemoteLogRepository { + readonly database: Knex; + + // for now we will ignore the config because it needs to be static + // so that both gateways can have access to the same database + // simulating a remote log storage + public constructor(config: Knex.Config | undefined) { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const configFile = require("../../../knex/knexfile-remote.ts")[ + process.env.ENVIRONMENT || "development" + ]; + + this.database = knex(config || configFile); + } + + getLogsTable(): Knex.QueryBuilder { + return this.database("remote-logs"); + } + + readById(logKey: string): Promise { + return this.getLogsTable().where({ key: logKey }).first(); + } + + create(log: IRemoteLog): any { + return this.getLogsTable().insert(log); + } + + async reset() { + await this.database.migrate.rollback(); + await this.database.migrate.latest(); + } + + async destroy() { + await this.database.destroy(); + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/server/server-helper.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/server/server-helper.ts index 35f85630d0..4a9a547cb3 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/server/server-helper.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway/server/server-helper.ts @@ -14,7 +14,7 @@ import { CommitFinalV1Request, TransferCompleteV1Request, } from "../../public-api"; -import { OdapMessageType, PluginSatpGateway } from "../plugin-satp-gateway"; +import { SatpMessageType, PluginSatpGateway } from "../plugin-satp-gateway"; export class ServerGatewayHelper { public static readonly CLASS_NAME: string = "ServerGatewayHelper"; @@ -57,7 +57,7 @@ export class ServerGatewayHelper { } const transferInitializationResponse: TransferInitializationV1Response = { - messageType: OdapMessageType.InitializationResponse, + messageType: SatpMessageType.InitializationResponse, sessionID: sessionID, initialRequestMessageHash: sessionData.initializationRequestMessageHash, timeStamp: sessionData.initializationRequestMessageRcvTimeStamp, @@ -98,7 +98,7 @@ export class ServerGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.sourceBasePath, ).phase1TransferInitiationResponseV1(transferInitializationResponse), "TransferInitializationResponse", @@ -128,7 +128,7 @@ export class ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.InitializationRequest) { + if (request.messageType != SatpMessageType.InitializationRequest) { throw new Error( `${fnTag}, wrong message type for TransferInitializationRequest`, ); @@ -224,7 +224,7 @@ export class ServerGatewayHelper { const transferCommenceResponse: TransferCommenceV1Response = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceResponse, + messageType: SatpMessageType.TransferCommenceResponse, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, hashCommenceRequest: sessionData.transferCommenceMessageRequestHash, @@ -259,7 +259,7 @@ export class ServerGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.sourceBasePath, ).phase2TransferCommenceResponseV1(transferCommenceResponse), "TransferCommenceResponse", @@ -290,7 +290,7 @@ export class ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.TransferCommenceRequest) { + if (request.messageType != SatpMessageType.TransferCommenceRequest) { throw new Error( `${fnTag}, wrong message type for TransferCommenceRequest`, ); @@ -385,7 +385,7 @@ export class ServerGatewayHelper { const lockEvidenceResponseMessage: LockEvidenceV1Response = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceResponse, + messageType: SatpMessageType.LockEvidenceResponse, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, hashLockEvidenceRequest: sessionData.lockEvidenceRequestMessageHash, @@ -420,7 +420,7 @@ export class ServerGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.sourceBasePath, ).phase2LockEvidenceResponseV1(lockEvidenceResponseMessage), "LockEvidenceResponse", @@ -452,7 +452,7 @@ export class ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.LockEvidenceRequest) { + if (request.messageType != SatpMessageType.LockEvidenceRequest) { throw new Error(`${fnTag}, wrong message type for LockEvidenceRequest`); } @@ -497,8 +497,8 @@ export class ServerGatewayHelper { } const claimHash = SHA256(request.lockEvidenceClaim).toString(); - const retrievedClaim = await gateway.getLogFromIPFS( - PluginSatpGateway.getOdapLogKey(sessionID, "proof", "lock"), + const retrievedClaim = await gateway.getLogFromRemote( + PluginSatpGateway.getSatpLogKey(sessionID, "proof", "lock"), ); if (claimHash != retrievedClaim.hash) { @@ -507,7 +507,9 @@ export class ServerGatewayHelper { ); } - if (!gateway.verifySignature(retrievedClaim, request.clientIdentityPubkey)) { + if ( + !gateway.verifySignature(retrievedClaim, request.clientIdentityPubkey) + ) { throw new Error( `${fnTag}, LockEvidence Claim message signature verification failed`, ); @@ -561,7 +563,7 @@ export class ServerGatewayHelper { const commitPreparationResponseMessage: CommitPreparationV1Response = { sessionID: sessionID, - messageType: OdapMessageType.CommitPreparationResponse, + messageType: SatpMessageType.CommitPreparationResponse, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, hashCommitPrep: sessionData.commitPrepareRequestMessageHash, @@ -596,7 +598,7 @@ export class ServerGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.sourceBasePath, ).phase3CommitPreparationResponseV1(commitPreparationResponseMessage), "CommitPreparationResponse", @@ -623,7 +625,7 @@ export class ServerGatewayHelper { // We need to check somewhere if this phase is completed within the asset-lock duration. - if (request.messageType != OdapMessageType.CommitPreparationRequest) { + if (request.messageType != SatpMessageType.CommitPreparationRequest) { throw new Error( `${fnTag}, wrong message type for CommitPreparationRequest`, ); @@ -713,7 +715,7 @@ export class ServerGatewayHelper { const commitFinalResponseMessage: CommitFinalV1Response = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, clientIdentityPubkey: sessionData.sourceGatewayPubkey, serverIdentityPubkey: sessionData.recipientGatewayPubkey, commitAcknowledgementClaim: sessionData.commitAcknowledgementClaim, @@ -750,7 +752,7 @@ export class ServerGatewayHelper { await gateway.makeRequest( sessionID, - PluginSatpGateway.getOdapAPI( + PluginSatpGateway.getSatpAPI( sessionData.sourceBasePath, ).phase3CommitFinalResponseV1(commitFinalResponseMessage), "CommitFinalResponse", @@ -783,7 +785,7 @@ export class ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.CommitFinalRequest) { + if (request.messageType != SatpMessageType.CommitFinalRequest) { throw new Error(`${fnTag}, wrong message type for CommitFinalRequest`); } @@ -822,8 +824,9 @@ export class ServerGatewayHelper { // We need to check somewhere if this phase is completed within the asset-lock duration. const claimHash = SHA256(request.commitFinalClaim).toString(); - const retrievedClaim = await gateway.getLogFromIPFS( - PluginSatpGateway.getOdapLogKey(sessionID, "proof", "delete"), + + const retrievedClaim = await gateway.getLogFromRemote( + PluginSatpGateway.getSatpLogKey(sessionID, "proof", "delete"), ); if (claimHash != retrievedClaim.hash) { @@ -832,7 +835,9 @@ export class ServerGatewayHelper { ); } - if (!gateway.verifySignature(retrievedClaim, request.clientIdentityPubkey)) { + if ( + !gateway.verifySignature(retrievedClaim, request.clientIdentityPubkey) + ) { throw new Error( `${fnTag}, Commit Final Claim signature verification failed`, ); @@ -885,7 +890,7 @@ export class ServerGatewayHelper { data: JSON.stringify(sessionData), }); - if (request.messageType != OdapMessageType.TransferCompleteRequest) { + if (request.messageType != SatpMessageType.TransferCompleteRequest) { throw new Error( `${fnTag}, wrong message type for TransferCompleteRequest`, ); diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/openapi/typescript-axios/api.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/openapi/typescript-axios/api.ts index b01775c75b..a5340f6e35 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/openapi/typescript-axios/api.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/openapi/typescript-axios/api.ts @@ -739,128 +739,6 @@ export interface LockEvidenceV1Response { */ 'sequenceNumber': number; } -/** - * - * @export - * @interface OdapMessage - */ -export interface OdapMessage { - /** - * - * @type {number} - * @memberof OdapMessage - */ - 'SequenceNumber'?: number; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'Phase'?: OdapMessagePhaseEnum; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'ResourceURL'?: string; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'DeveloperURN'?: string; - /** - * - * @type {OdapMessageActionResponse} - * @memberof OdapMessage - */ - 'ActionResponse'?: OdapMessageActionResponse; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'CredentialProfile'?: OdapMessageCredentialProfileEnum; - /** - * - * @type {Array} - * @memberof OdapMessage - */ - 'CredentialBlock'?: Array; - /** - * - * @type {PayloadProfile} - * @memberof OdapMessage - */ - 'CredentialsProfile'?: PayloadProfile; - /** - * - * @type {object} - * @memberof OdapMessage - */ - 'ApplicationProfile'?: object; - /** - * - * @type {object} - * @memberof OdapMessage - */ - 'Payload'?: object; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'PayloadHash'?: string; - /** - * - * @type {string} - * @memberof OdapMessage - */ - 'MessageSignature'?: string; -} - -export const OdapMessagePhaseEnum = { - TransferInitialization: 'TransferInitialization', - LockEvidenceVerification: 'LockEvidenceVerification', - CommitmentEstablishment: 'CommitmentEstablishment' -} as const; - -export type OdapMessagePhaseEnum = typeof OdapMessagePhaseEnum[keyof typeof OdapMessagePhaseEnum]; -export const OdapMessageCredentialProfileEnum = { - Saml: 'SAML', - OAuth: 'OAuth', - X509: 'X509' -} as const; - -export type OdapMessageCredentialProfileEnum = typeof OdapMessageCredentialProfileEnum[keyof typeof OdapMessageCredentialProfileEnum]; - -/** - * - * @export - * @interface OdapMessageActionResponse - */ -export interface OdapMessageActionResponse { - /** - * - * @type {string} - * @memberof OdapMessageActionResponse - */ - 'ResponseCode'?: OdapMessageActionResponseResponseCodeEnum; - /** - * - * @type {Array} - * @memberof OdapMessageActionResponse - */ - 'Arguments'?: Array; -} - -export const OdapMessageActionResponseResponseCodeEnum = { - OK: '200', - RESOURCE_NOT_FOUND: '404' -} as const; - -export type OdapMessageActionResponseResponseCodeEnum = typeof OdapMessageActionResponseResponseCodeEnum[keyof typeof OdapMessageActionResponseResponseCodeEnum]; - /** * * @export @@ -1078,6 +956,128 @@ export interface RollbackV1Message { */ 'signature': string; } +/** + * + * @export + * @interface SatpMessage + */ +export interface SatpMessage { + /** + * + * @type {number} + * @memberof SatpMessage + */ + 'SequenceNumber'?: number; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'Phase'?: SatpMessagePhaseEnum; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'ResourceURL'?: string; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'DeveloperURN'?: string; + /** + * + * @type {SatpMessageActionResponse} + * @memberof SatpMessage + */ + 'ActionResponse'?: SatpMessageActionResponse; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'CredentialProfile'?: SatpMessageCredentialProfileEnum; + /** + * + * @type {Array} + * @memberof SatpMessage + */ + 'CredentialBlock'?: Array; + /** + * + * @type {PayloadProfile} + * @memberof SatpMessage + */ + 'CredentialsProfile'?: PayloadProfile; + /** + * + * @type {object} + * @memberof SatpMessage + */ + 'ApplicationProfile'?: object; + /** + * + * @type {object} + * @memberof SatpMessage + */ + 'Payload'?: object; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'PayloadHash'?: string; + /** + * + * @type {string} + * @memberof SatpMessage + */ + 'MessageSignature'?: string; +} + +export const SatpMessagePhaseEnum = { + TransferInitialization: 'TransferInitialization', + LockEvidenceVerification: 'LockEvidenceVerification', + CommitmentEstablishment: 'CommitmentEstablishment' +} as const; + +export type SatpMessagePhaseEnum = typeof SatpMessagePhaseEnum[keyof typeof SatpMessagePhaseEnum]; +export const SatpMessageCredentialProfileEnum = { + Saml: 'SAML', + OAuth: 'OAuth', + X509: 'X509' +} as const; + +export type SatpMessageCredentialProfileEnum = typeof SatpMessageCredentialProfileEnum[keyof typeof SatpMessageCredentialProfileEnum]; + +/** + * + * @export + * @interface SatpMessageActionResponse + */ +export interface SatpMessageActionResponse { + /** + * + * @type {string} + * @memberof SatpMessageActionResponse + */ + 'ResponseCode'?: SatpMessageActionResponseResponseCodeEnum; + /** + * + * @type {Array} + * @memberof SatpMessageActionResponse + */ + 'Arguments'?: Array; +} + +export const SatpMessageActionResponseResponseCodeEnum = { + OK: '200', + RESOURCE_NOT_FOUND: '404' +} as const; + +export type SatpMessageActionResponseResponseCodeEnum = typeof SatpMessageActionResponseResponseCodeEnum[keyof typeof SatpMessageActionResponseResponseCodeEnum]; + /** * * @export diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/public-api.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/public-api.ts index aa01ca344f..530de4eccc 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/public-api.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/public-api.ts @@ -3,7 +3,7 @@ export * from "./generated/openapi/typescript-axios/index"; export { IPluginSatpGatewayConstructorOptions, PluginSatpGateway, - OdapMessageType, + SatpMessageType, IKeyPair, } from "./gateway/plugin-satp-gateway"; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/client-side/client-request-endpoint.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/client-side/client-request-endpoint.ts index e1beb1e6b1..9ef597bf16 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/client-side/client-request-endpoint.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/client-side/client-request-endpoint.ts @@ -86,7 +86,7 @@ export class ClientRequestEndpointV1 implements IWebServiceEndpoint { const reqTag = `${this.getVerbLowerCase()} - ${this.getPath()}`; this.log.debug(reqTag); try { - await this.options.gateway.runOdap(req.body); + await this.options.gateway.runSatp(req.body); res.status(200).json("OK"); } catch (ex) { this.log.error(`Crash while serving ${reqTag}`, ex); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/backup-gateway-after-client-crash.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/backup-gateway-after-client-crash.test.ts index 37c1c8807e..56b53352a8 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/backup-gateway-after-client-crash.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/backup-gateway-after-client-crash.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -21,7 +19,6 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; @@ -66,27 +63,20 @@ import { import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../knex.config"; - -/** - * Use this to debug issues with the fabric node SDK - * ```sh - * export HFC_LOGGING='{"debug":"console","info":"console"}' - * ``` - */ -let ipfsApiHost: string; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../knex.config"; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -132,51 +122,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } - { // Fabric ledger connection const channelId = "mychannel"; @@ -572,7 +517,6 @@ beforeAll(async () => { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, fabricPath: fabricPath, fabricSigningCredential: fabricSigningCredential, fabricChannelName: fabricChannelName, @@ -580,7 +524,8 @@ beforeAll(async () => { backupGatewaysAllowed: allowedGateways, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; serverGatewayPluginOptions = { @@ -588,28 +533,26 @@ beforeAll(async () => { dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -794,7 +737,7 @@ test("client gateway crashes after lock fabric asset", async () => { ); // now we simulate the crash of the client gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); await Servers.shutdown(sourceGatewayServer); const expressApp = express(); @@ -814,14 +757,14 @@ test("client gateway crashes after lock fabric asset", async () => { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: backupGatewayKeys, - ipfsPath: ipfsApiHost, fabricPath: fabricPath, fabricSigningCredential: fabricSigningCredential, fabricChannelName: fabricChannelName, fabricContractName: fabricContractName, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); @@ -831,7 +774,7 @@ test("client gateway crashes after lock fabric asset", async () => { // backup client gateway back online await pluginSourceGateway.recoverOpenSessions(true); - expect(pluginSourceGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); await makeSessionDataChecks( pluginSourceGateway, @@ -849,17 +792,14 @@ test("client gateway crashes after lock fabric asset", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-delete-asset.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-delete-asset.test.ts index 0afb4f775b..fa5743855f 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-delete-asset.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-delete-asset.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -21,7 +19,6 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; @@ -65,7 +62,11 @@ import { import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../knex.config"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../knex.config"; /** * Use this to debug issues with the fabric node SDK @@ -73,19 +74,15 @@ import { knexClientConnection, knexServerConnection } from "../knex.config"; * export HFC_LOGGING='{"debug":"console","info":"console"}' * ``` */ -let ipfsApiHost: string; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -129,51 +126,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } - { // Fabric ledger connection const channelId = "mychannel"; @@ -563,14 +515,14 @@ beforeAll(async () => { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, fabricPath: fabricPath, fabricSigningCredential: fabricSigningCredential, fabricChannelName: fabricChannelName, fabricContractName: fabricContractName, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; serverGatewayPluginOptions = { @@ -578,28 +530,26 @@ beforeAll(async () => { dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -820,7 +770,7 @@ test("client gateway crashes after deleting fabric asset", async () => { await pluginSourceGateway.deleteAsset(sessionID); // now we simulate the crash of the client gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); await Servers.shutdown(sourceGatewayServer); const expressApp = express(); @@ -856,17 +806,16 @@ test("client gateway crashes after deleting fabric asset", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-lock-asset.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-lock-asset.test.ts index 9739e31846..8ce74cc602 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-lock-asset.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-lock-asset.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -21,7 +19,6 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; @@ -65,7 +62,11 @@ import { import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../knex.config"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../knex.config"; /** * Use this to debug issues with the fabric node SDK @@ -73,19 +74,15 @@ import { knexClientConnection, knexServerConnection } from "../knex.config"; * export HFC_LOGGING='{"debug":"console","info":"console"}' * ``` */ -let ipfsApiHost: string; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -129,51 +126,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } - { // Fabric ledger connection const channelId = "mychannel"; @@ -564,14 +516,14 @@ beforeAll(async () => { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, fabricPath: fabricPath, fabricSigningCredential: fabricSigningCredential, fabricChannelName: fabricChannelName, fabricContractName: fabricContractName, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; serverGatewayPluginOptions = { @@ -579,28 +531,26 @@ beforeAll(async () => { dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -756,7 +706,8 @@ test("client gateway crashes after lock fabric asset", async () => { ); // now we simulate the crash of the client gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); await Servers.shutdown(sourceGatewayServer); const expressApp = express(); @@ -792,17 +743,16 @@ test("client gateway crashes after lock fabric asset", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-transfer-initiation.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-transfer-initiation.test.ts index 1fe269bec7..7222bbffd7 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-transfer-initiation.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/client-crash-after-transfer-initiation.test.ts @@ -2,22 +2,17 @@ import http, { Server } from "http"; import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express, { Express } from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { IListenOptions, - LogLevelDesc, Secp256k1Keys, Servers, } from "@hyperledger/cactus-common"; -import { Configuration } from "@hyperledger/cactus-core-api"; import { IPluginSatpGatewayConstructorOptions, PluginSatpGateway, } from "../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { AssetProfile, ClientV1Request, @@ -29,7 +24,11 @@ import { FabricSatpGateway } from "../../../main/typescript/gateway/fabric-satp- import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; -import { knexClientConnection, knexServerConnection } from "../knex.config"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; @@ -37,18 +36,12 @@ const MAX_TIMEOUT = 5000; const FABRIC_ASSET_ID = uuidv4(); const BESU_ASSET_ID = uuidv4(); -const logLevel: LogLevelDesc = "INFO"; - let serverGatewayPluginOptions: IPluginSatpGatewayConstructorOptions; let clientGatewayPluginOptions: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; -let ipfsContainer: GoIpfsTestContainer; -let ipfsApiHost: string; -let ipfsServer: Server; - let sourceGatewayServer: Server; let recipientGatewayserver: Server; @@ -64,61 +57,17 @@ let clientExpressApp: Express; let clientListenOptions: IListenOptions; beforeAll(async () => { - { - // Define IPFS connection - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const ipfsApi = new ObjectStoreIpfsApi(config); - - expect(ipfsApi).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } { // Server Gateway configuration serverGatewayPluginOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; serverExpressApp = express(); @@ -137,14 +86,13 @@ beforeAll(async () => { const { address, port } = addressInfo; serverGatewayApiHost = `http://${address}:${port}`; - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginRecipientGateway.localRepository?.reset(); await pluginRecipientGateway.registerWebServices(serverExpressApp); } @@ -154,11 +102,11 @@ beforeAll(async () => { name: "cactus-plugin#satpGateway", dltIDs: ["DLT2"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; clientExpressApp = express(); @@ -179,12 +127,11 @@ beforeAll(async () => { pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - if (pluginSourceGateway.database == undefined) { + if (pluginSourceGateway.localRepository?.database == undefined) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); await pluginSourceGateway.registerWebServices(clientExpressApp); @@ -225,25 +172,6 @@ beforeAll(async () => { } }); -beforeEach(async () => { - if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined - ) { - throw new Error("Database is not correctly initialized"); - } - - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); -}); - -afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); -}); - test("successful run ODAP after client gateway crashed after after receiving transfer initiation response", async () => { const sessionID = pluginSourceGateway.configureOdapSession(clientRequest); @@ -282,7 +210,8 @@ test("successful run ODAP after client gateway crashed after after receiving tra ); // now we simulate the crash of the client gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); await Servers.shutdown(sourceGatewayServer); clientExpressApp = express(); @@ -310,11 +239,10 @@ test("successful run ODAP after client gateway crashed after after receiving tra }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(sourceGatewayServer); await Servers.shutdown(recipientGatewayserver); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call-with-ledger-connector.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call-with-ledger-connector.test.ts index e8ead19647..3a006161b4 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call-with-ledger-connector.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call-with-ledger-connector.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -20,13 +18,12 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import { ClientV1Request, - DefaultApi as OdapApi, + DefaultApi as SatpApi, } from "../../../main/typescript/public-api"; import LockAssetContractJson from "../../solidity/lock-asset-contract/LockAsset.json"; import { PluginRegistry } from "@hyperledger/cactus-core"; @@ -64,6 +61,7 @@ import { } from "../../../main/typescript/gateway/besu-satp-gateway"; import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../knex.config"; /** * Use this to debug issues with the fabric node SDK @@ -71,19 +69,15 @@ import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/ser * export HFC_LOGGING='{"debug":"console","info":"console"}' * ``` */ -let ipfsApiHost: string; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -124,51 +118,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } - { // Fabric ledger connection const channelId = "mychannel"; @@ -408,7 +357,7 @@ beforeAll(async () => { // does the same thing, it just waits 10 seconds for good measure so there // might not be a way for us to avoid doing this, but if there is a way we // absolutely should not have timeouts like this, anywhere... - await new Promise((resolve) => setTimeout(resolve, 10000)); + await new Promise((resolve) => setTimeout(resolve, 15000)); fabricSigningCredential = { keychainId, @@ -528,45 +477,42 @@ beforeAll(async () => { { // Gateways configuration - const clientGatewayPluginOptions: IFabricSatpGatewayConstructorOptions = - { - name: "cactus-plugin#satpGateway", - dltIDs: ["DLT2"], - instanceId: uuidv4(), - ipfsPath: ipfsApiHost, - fabricPath: fabricPath, - fabricSigningCredential: fabricSigningCredential, - fabricChannelName: fabricChannelName, - fabricContractName: fabricContractName, - clientHelper: new ClientGatewayHelper(), - serverHelper: new ServerGatewayHelper(), - }; + const clientGatewayPluginOptions: IFabricSatpGatewayConstructorOptions = { + name: "cactus-plugin#satpGateway", + dltIDs: ["DLT2"], + instanceId: uuidv4(), + fabricPath: fabricPath, + fabricSigningCredential: fabricSigningCredential, + fabricChannelName: fabricChannelName, + fabricContractName: fabricContractName, + clientHelper: new ClientGatewayHelper(), + serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, + }; const serverGatewayPluginOptions: IBesuSatpGatewayConstructorOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -609,10 +555,10 @@ beforeAll(async () => { }); test("runs ODAP between two gateways via openApi", async () => { - const odapApiConfig = new Configuration({ + const satpApiConfig = new Configuration({ basePath: clientGatewayApiHost, }); - const apiClient = new OdapApi(odapApiConfig); + const apiClient = new SatpApi(satpApiConfig); const expiryDate = new Date(2060, 11, 24).toString(); const assetProfile: AssetProfile = { expirationDate: expiryDate }; @@ -672,17 +618,16 @@ test("runs ODAP between two gateways via openApi", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call.test.ts index e6e857623e..7872b5517f 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-api-call.test.ts @@ -2,22 +2,14 @@ import http, { Server } from "http"; import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { DefaultApi as OdapApi } from "../../../main/typescript/public-api"; +import { DefaultApi as SatpApi } from "../../../main/typescript/public-api"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; +import { IListenOptions, Servers } from "@hyperledger/cactus-common"; import { Configuration } from "@hyperledger/cactus-core-api"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; - import { PluginSatpGateway, IPluginSatpGatewayConstructorOptions, @@ -32,6 +24,7 @@ import { BesuSatpGateway } from "../../../main/typescript/gateway/besu-satp-gate import { FabricSatpGateway } from "../../../main/typescript/gateway/fabric-satp-gateway"; import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; @@ -39,91 +32,39 @@ const MAX_TIMEOUT = 5000; const FABRIC_ASSET_ID = uuidv4(); const BESU_ASSET_ID = uuidv4(); -let ipfsApiHost: string; -let ipfsContainer: GoIpfsTestContainer; - -const logLevel: LogLevelDesc = "INFO"; - let sourceGatewayServer: Server; let recipientGatewayserver: Server; -let ipfsServer: Server; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - test("runs ODAP between two gateways via openApi", async () => { const clientGatewayPluginOptions: IPluginSatpGatewayConstructorOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT2"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; const serverGatewayPluginOptions: IPluginSatpGatewayConstructorOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect(pluginRecipientGateway.localRepository?.database).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); let serverGatewayApiHost: string; @@ -165,10 +106,10 @@ test("runs ODAP between two gateways via openApi", async () => { await pluginSourceGateway.getOrCreateWebServices(); await pluginSourceGateway.registerWebServices(expressApp); - const odapApiConfig = new Configuration({ + const satpApiConfig = new Configuration({ basePath: clientGatewayApiHost, }); - const apiClient = new OdapApi(odapApiConfig); + const apiClient = new SatpApi(satpApiConfig); const expiryDate = new Date(2060, 11, 24).toString(); const assetProfile: AssetProfile = { expirationDate: expiryDate }; @@ -221,11 +162,10 @@ test("runs ODAP between two gateways via openApi", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(sourceGatewayServer); await Servers.shutdown(recipientGatewayserver); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-rollback.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-rollback.test.ts index 58418a2a57..b932b4378b 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-rollback.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap-rollback.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -21,7 +19,6 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, DEFAULT_FABRIC_2_AIO_IMAGE_NAME, DEFAULT_FABRIC_2_AIO_IMAGE_VERSION, @@ -66,6 +63,7 @@ import { } from "../../../main/typescript/gateway/besu-satp-gateway"; import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../knex.config"; /** * Use this to debug issues with the fabric node SDK @@ -73,19 +71,15 @@ import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/ser * export HFC_LOGGING='{"debug":"console","info":"console"}' * ``` */ -let ipfsApiHost: string; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -129,51 +123,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } - { // Fabric ledger connection const channelId = "mychannel"; @@ -566,13 +515,13 @@ beforeAll(async () => { dltIDs: ["DLT2"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, fabricPath: fabricPath, fabricSigningCredential: fabricSigningCredential, fabricChannelName: fabricChannelName, fabricContractName: fabricContractName, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; serverGatewayPluginOptions = { @@ -580,27 +529,25 @@ beforeAll(async () => { dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -844,7 +791,8 @@ test("client sends rollback message at the end of the protocol", async () => { console.log(r1); console.log(r2); // now we simulate the crash of the client gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); await Servers.shutdown(sourceGatewayServer); await new Promise((resolve) => setTimeout(resolve, 5000)); @@ -884,17 +832,16 @@ test("client sends rollback message at the end of the protocol", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap.test.ts index b9231a90ba..1ff28ee2f1 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/odap.test.ts @@ -1,20 +1,6 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; -import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; import { PluginSatpGateway } from "../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { AssetProfile, @@ -26,91 +12,40 @@ import { BesuSatpGateway } from "../../../main/typescript/gateway/besu-satp-gate import { FabricSatpGateway } from "../../../main/typescript/gateway/fabric-satp-gateway"; import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -const logLevel: LogLevelDesc = "INFO"; - let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - test("successful run ODAP instance", async () => { const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect(pluginRecipientGateway.localRepository?.database).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); const dummyPath = { apiHost: "dummyPath" }; @@ -353,9 +288,8 @@ test("successful run ODAP instance", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-create-asset.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-create-asset.test.ts index 181bc74c42..beeda4d4b0 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-create-asset.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-create-asset.test.ts @@ -4,10 +4,8 @@ import http, { Server } from "http"; import { Server as SocketIoServer } from "socket.io"; import { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { AssetProfile } from "../../../main/typescript/generated/openapi/typescript-axios"; import { IListenOptions, @@ -21,7 +19,6 @@ import { Containers, FabricTestLedgerV1, pruneDockerAllIfGithubAction, - GoIpfsTestContainer, BesuTestLedger, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; @@ -66,7 +63,11 @@ import { import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../knex.config"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../knex.config"; /** * Use this to debug issues with the fabric node SDK @@ -74,19 +75,15 @@ import { knexClientConnection, knexServerConnection } from "../knex.config"; * export HFC_LOGGING='{"debug":"console","info":"console"}' * ``` */ -let ipfsApiHost: string; let fabricSigningCredential: FabricSigningCredential; const logLevel: LogLevelDesc = "INFO"; -let ipfsServer: Server; let sourceGatewayServer: Server; let recipientGatewayServer: Server; let besuServer: Server; let fabricServer: Server; -let ipfsContainer: GoIpfsTestContainer; - let fabricLedger: FabricTestLedgerV1; let fabricContractName: string; let fabricChannelName: string; @@ -129,50 +126,6 @@ beforeAll(async () => { fail("Pruning didn't throw OK"); }); - { - // IPFS configuration - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } { // Fabric ledger connection const channelId = "mychannel"; @@ -412,7 +365,7 @@ beforeAll(async () => { // does the same thing, it just waits 10 seconds for good measure so there // might not be a way for us to avoid doing this, but if there is a way we // absolutely should not have timeouts like this, anywhere... - await new Promise((resolve) => setTimeout(resolve, 10000)); + await new Promise((resolve) => setTimeout(resolve, 15000)); fabricSigningCredential = { keychainId, @@ -560,49 +513,46 @@ beforeAll(async () => { beforeEach(async () => { { // Gateways configuration - const clientGatewayPluginOptions: IFabricSatpGatewayConstructorOptions = - { - name: "cactus-plugin#satpGateway", - dltIDs: ["DLT2"], - instanceId: uuidv4(), - keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, - fabricPath: fabricPath, - fabricSigningCredential: fabricSigningCredential, - fabricChannelName: fabricChannelName, - fabricContractName: fabricContractName, - clientHelper: new ClientGatewayHelper(), - serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, - }; + const clientGatewayPluginOptions: IFabricSatpGatewayConstructorOptions = { + name: "cactus-plugin#satpGateway", + dltIDs: ["DLT2"], + instanceId: uuidv4(), + keyPair: Secp256k1Keys.generateKeyPairsBuffer(), + fabricPath: fabricPath, + fabricSigningCredential: fabricSigningCredential, + fabricChannelName: fabricChannelName, + fabricContractName: fabricContractName, + clientHelper: new ClientGatewayHelper(), + serverHelper: new ServerGatewayHelper(), + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, + }; serverGatewayPluginOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), keyPair: Secp256k1Keys.generateKeyPairsBuffer(), - ipfsPath: ipfsApiHost, besuPath: besuPath, besuWeb3SigningCredential: besuWeb3SigningCredential, besuContractName: besuContractName, besuKeychainId: besuKeychainId, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginSourceGateway.database).not.toBeUndefined(); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect(pluginSourceGateway.localRepository?.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginSourceGateway.database?.migrate.rollback(); - await pluginSourceGateway.database?.migrate.latest(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); } { // Server Gateway configuration @@ -842,7 +792,8 @@ test("server gateway crashes after creating besu asset", async () => { await pluginRecipientGateway.createAsset(sessionID); // now we simulate the crash of the server gateway - pluginRecipientGateway.database?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); await Servers.shutdown(recipientGatewayServer); const expressApp = express(); @@ -878,17 +829,16 @@ test("server gateway crashes after creating besu asset", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); await fabricLedger.stop(); await fabricLedger.destroy(); await besuTestLedger.stop(); await besuTestLedger.destroy(); - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); + await pluginSourceGateway.localRepository?.destroy(); + await pluginRecipientGateway.localRepository?.destroy(); + await pluginSourceGateway.remoteRepository?.destroy(); + await pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(besuServer); await Servers.shutdown(fabricServer); await Servers.shutdown(sourceGatewayServer); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-transfer-initiation.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-transfer-initiation.test.ts index 9dd6a11f1f..7e22aa5441 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-transfer-initiation.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/server-crash-after-transfer-initiation.test.ts @@ -2,18 +2,13 @@ import http, { Server } from "http"; import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; import bodyParser from "body-parser"; import express, { Express } from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { IListenOptions, - LogLevelDesc, Secp256k1Keys, Servers, } from "@hyperledger/cactus-common"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { AssetProfile, @@ -31,7 +26,7 @@ import { import { ClientGatewayHelper } from "../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection } from "../knex.config"; +import { knexClientConnection, knexRemoteConnection } from "../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; @@ -39,17 +34,11 @@ const MAX_TIMEOUT = 5000; const FABRIC_ASSET_ID = uuidv4(); const BESU_ASSET_ID = uuidv4(); -const logLevel: LogLevelDesc = "INFO"; - let clientGatewayPluginOptions: IFabricSatpGatewayConstructorOptions; let serverGatewayPluginOptions: IBesuSatpGatewayConstructorOptions; let pluginSourceGateway: FabricSatpGateway; let pluginRecipientGateway: BesuSatpGateway; -let ipfsContainer: GoIpfsTestContainer; -let ipfsApiHost: string; -let ipfsServer: Server; - let sourceGatewayServer: Server; let recipientGatewayserver: Server; @@ -65,60 +54,16 @@ let clientExpressApp: Express; let clientListenOptions: IListenOptions; beforeAll(async () => { - { - // Define IPFS connection - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const ipfsApi = new ObjectStoreIpfsApi(config); - - expect(ipfsApi).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); - } { // Server Gateway configuration serverGatewayPluginOptions = { name: "cactus-plugin#satpGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; serverExpressApp = express(); @@ -137,14 +82,13 @@ beforeAll(async () => { const { address, port } = addressInfo; serverGatewayApiHost = `http://${address}:${port}`; - pluginRecipientGateway = new BesuSatpGateway( - serverGatewayPluginOptions, - ); + pluginRecipientGateway = new BesuSatpGateway(serverGatewayPluginOptions); - expect(pluginRecipientGateway.database).not.toBeUndefined(); + expect( + pluginRecipientGateway.localRepository?.database, + ).not.toBeUndefined(); - await pluginRecipientGateway.database?.migrate.rollback(); - await pluginRecipientGateway.database?.migrate.latest(); + await pluginRecipientGateway.localRepository?.reset(); await pluginRecipientGateway.registerWebServices(serverExpressApp); } @@ -154,11 +98,11 @@ beforeAll(async () => { name: "cactus-plugin#satpGateway", dltIDs: ["DLT2"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, + knexLocalConfig: knexClientConnection, }; clientExpressApp = express(); @@ -179,12 +123,11 @@ beforeAll(async () => { pluginSourceGateway = new FabricSatpGateway(clientGatewayPluginOptions); - if (pluginSourceGateway.database == undefined) { + if (pluginSourceGateway.localRepository?.database == undefined) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); await pluginSourceGateway.registerWebServices(clientExpressApp); @@ -246,7 +189,8 @@ test("server gateway crashes after transfer initiation flow", async () => { ); // now we simulate the crash of the server gateway - pluginRecipientGateway.database?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); await Servers.shutdown(recipientGatewayserver); serverExpressApp = express(); @@ -274,13 +218,11 @@ test("server gateway crashes after transfer initiation flow", async () => { }); afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); - await Servers.shutdown(ipfsServer); await Servers.shutdown(sourceGatewayServer); await Servers.shutdown(recipientGatewayserver); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/knex.config.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/knex.config.ts index fa4578bd05..3376a92c91 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/knex.config.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/knex.config.ts @@ -19,3 +19,14 @@ export const knexServerConnection = { }, useNullAsDefault: true, }; + +export const knexRemoteConnection = { + client: "sqlite3", + connection: { + filename: "./packages/cactus-plugin-satp-hermes/knex/.dev.remote.sqlite3", + }, + migrations: { + directory: "./packages/cactus-plugin-satp-hermes/knex/migrations", + }, + useNullAsDefault: true, +}; diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/make-checks.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/make-checks.ts index 594542cd01..d82d6f39a1 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/make-checks.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/make-checks.ts @@ -160,122 +160,122 @@ export async function makeSessionDataChecks( await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "validate"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "validate"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "validate"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "validate"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "validate"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "validate"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "ack", "validate"), + PluginSatpGateway.getSatpLogKey(sessionId, "ack", "validate"), ), ).resolves.not.toBeUndefined(); await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "commence"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "commence"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "commence"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "commence"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "commence"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "commence"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "ack", "commence"), + PluginSatpGateway.getSatpLogKey(sessionId, "ack", "commence"), ), ).resolves.not.toBeUndefined(); await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "lock"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "lock"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "lock"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "lock"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "lock"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "lock"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "ack", "lock"), + PluginSatpGateway.getSatpLogKey(sessionId, "ack", "lock"), ), ).resolves.not.toBeUndefined(); await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "prepare"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "prepare"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "prepare"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "prepare"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "prepare"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "prepare"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "ack", "prepare"), + PluginSatpGateway.getSatpLogKey(sessionId, "ack", "prepare"), ), ).resolves.not.toBeUndefined(); await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "final"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "final"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "final"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "final"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "final"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "final"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "ack", "final"), + PluginSatpGateway.getSatpLogKey(sessionId, "ack", "final"), ), ).resolves.not.toBeUndefined(); await expect( pluginSourceGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "init", "complete"), + PluginSatpGateway.getSatpLogKey(sessionId, "init", "complete"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "exec", "complete"), + PluginSatpGateway.getSatpLogKey(sessionId, "exec", "complete"), ), ).resolves.not.toBeUndefined(); await expect( pluginRecipientGateway.getLogFromDatabase( - PluginSatpGateway.getOdapLogKey(sessionId, "done", "complete"), + PluginSatpGateway.getSatpLogKey(sessionId, "done", "complete"), ), ).resolves.not.toBeUndefined(); } diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-final.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-final.test.ts index 40a7f370e6..5af9109a5d 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-final.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-final.test.ts @@ -1,39 +1,24 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; -import bodyParser from "body-parser"; import { v4 as uuidv4 } from "uuid"; -import http, { Server } from "http"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { CommitFinalV1Response, SessionData, } from "../../../../main/typescript/public-api"; -import { - LogLevelDesc, - IListenOptions, - Servers, -} from "@hyperledger/cactus-common"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; - -import express from "express"; -import { AddressInfo } from "net"; import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-satp-gateway"; import { BesuSatpGateway } from "../../../../main/typescript/gateway/besu-satp-gateway"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; +import { knexRemoteConnection } from "../../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -const logLevel: LogLevelDesc = "TRACE"; - const COMMIT_FINAL_REQUEST_MESSAGE_HASH = "dummyCommitFinalRequestMessageHash"; const COMMIT_ACK_CLAIM = "dummyCommitAckClaim"; @@ -45,86 +30,36 @@ let sequenceNumber: number; let sessionID: string; let step: number; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sequenceNumber = randomInt(100); sessionID = uuidv4(); @@ -155,26 +90,24 @@ beforeEach(async () => { }); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); }); afterEach(async () => { - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); + await pluginSourceGateway.localRepository?.destroy(); + await pluginRecipientGateway.localRepository?.destroy(); }); test("valid commit final response", async () => { const commitFinalResponse: CommitFinalV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -211,7 +144,7 @@ test("valid commit final response", async () => { test("commit final response invalid because of wrong previous message hash", async () => { const commitFinalResponse: CommitFinalV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -239,7 +172,7 @@ test("commit final response invalid because of wrong previous message hash", asy test("commit final response invalid because of wrong signature", async () => { const commitFinalResponse: CommitFinalV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -293,15 +226,9 @@ test("timeout in commit final request because no server gateway is connected", a }); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); -}); - afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-preparation.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-preparation.test.ts index bd864f05c2..283c6d75d4 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-preparation.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/commit-preparation.test.ts @@ -2,7 +2,8 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; import { v4 as uuidV4 } from "uuid"; import { - OdapMessageType, + IPluginSatpGatewayConstructorOptions, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -20,8 +21,8 @@ const MAX_TIMEOUT = 5000; const COMMIT_PREPARATION_REQUEST_MESSAGE_HASH = "dummyCommitPreparationRequestMessageHash"; -let sourceGatewayConstructor; -let recipientGatewayConstructor; +let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; +let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let sequenceNumber: number; @@ -48,16 +49,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sequenceNumber = randomInt(100); sessionID = uuidV4(); @@ -83,7 +82,7 @@ beforeEach(async () => { test("valid commit preparation response", async () => { const commitPreparationResponse: CommitPreparationV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitPreparationResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -122,7 +121,7 @@ test("valid commit preparation response", async () => { test("commit preparation response invalid because of wrong previous message hash", async () => { const commitPreparationResponse: CommitPreparationV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitPreparationResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -154,7 +153,7 @@ test("commit preparation response invalid because of wrong previous message hash test("commit preparation response invalid because of wrong signature", async () => { const commitPreparationResponse: CommitPreparationV1Response = { - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitPreparationResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -210,6 +209,8 @@ test("timeout in commit preparation request because no server gateway is connect }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/lock-evidence.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/lock-evidence.test.ts index 8669d9029b..03d28603a5 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/lock-evidence.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/lock-evidence.test.ts @@ -2,7 +2,7 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; import { v4 as uuidV4 } from "uuid"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -48,16 +48,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sequenceNumber = randomInt(100); sessionID = uuidV4(); @@ -83,7 +81,7 @@ beforeEach(async () => { test("valid lock evidence response", async () => { const lockEvidenceResponse: LockEvidenceV1Response = { - messageType: OdapMessageType.LockEvidenceResponse, + messageType: SatpMessageType.LockEvidenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -118,7 +116,7 @@ test("valid lock evidence response", async () => { test("lock evidence response invalid because of wrong previous message hash", async () => { const lockEvidenceResponse: LockEvidenceV1Response = { - messageType: OdapMessageType.LockEvidenceResponse, + messageType: SatpMessageType.LockEvidenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -145,7 +143,7 @@ test("lock evidence response invalid because of wrong previous message hash", as test("lock evidence response invalid because of wrong signature", async () => { const lockEvidenceResponse: LockEvidenceV1Response = { - messageType: OdapMessageType.LockEvidenceResponse, + messageType: SatpMessageType.LockEvidenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -201,6 +199,8 @@ test("timeout in lock evidence request because no server gateway is connected", }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-commence.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-commence.test.ts index 5f09feeb35..f695f62883 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-commence.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-commence.test.ts @@ -2,7 +2,7 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; import { v4 as uuidV4 } from "uuid"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -48,16 +48,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sequenceNumber = randomInt(100); sessionID = uuidV4(); @@ -83,7 +81,7 @@ beforeEach(async () => { test("valid transfer commence response", async () => { const transferCommenceResponse: TransferCommenceV1Response = { - messageType: OdapMessageType.TransferCommenceResponse, + messageType: SatpMessageType.TransferCommenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -120,7 +118,7 @@ test("valid transfer commence response", async () => { test("transfer commence response invalid because of wrong previous message hash", async () => { const transferCommenceResponse: TransferCommenceV1Response = { - messageType: OdapMessageType.TransferCommenceResponse, + messageType: SatpMessageType.TransferCommenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -150,7 +148,7 @@ test("transfer commence response invalid because of wrong previous message hash" test("transfer commence response invalid because of wrong signature", async () => { const transferCommenceResponse: TransferCommenceV1Response = { - messageType: OdapMessageType.TransferCommenceResponse, + messageType: SatpMessageType.TransferCommenceResponse, sessionID: sessionID, serverIdentityPubkey: pluginRecipientGateway.pubKey, clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -222,6 +220,8 @@ test("timeout in transfer commence request because no server gateway is connecte }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-initialization.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-initialization.test.ts index 660429c239..d1f14ffc56 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-initialization.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/client/transfer-initialization.test.ts @@ -2,7 +2,7 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; import { v4 as uuidV4 } from "uuid"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -49,16 +49,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sequenceNumber = randomInt(100); sessionID = uuidV4(); @@ -84,7 +82,7 @@ beforeEach(async () => { test("valid transfer initiation response", async () => { const initializationResponseMessage: TransferInitializationV1Response = { - messageType: OdapMessageType.InitializationResponse, + messageType: SatpMessageType.InitializationResponse, sessionID: sessionID, initialRequestMessageHash: INITIALIZATION_REQUEST_MESSAGE_HASH, timeStamp: Date.now().toString(), @@ -131,7 +129,7 @@ test("valid transfer initiation response", async () => { test("transfer initiation response invalid because of wrong previous message hash", async () => { const initializationResponseMessage: TransferInitializationV1Response = { - messageType: OdapMessageType.InitializationResponse, + messageType: SatpMessageType.InitializationResponse, sessionID: sessionID, initialRequestMessageHash: "wrongMessageHash", timeStamp: Date.now().toString(), @@ -165,7 +163,7 @@ test("transfer initiation response invalid because of wrong previous message has test("transfer initiation response invalid because it does not match transfer initialization request sessionID", async () => { const initializationResponseMessage: TransferInitializationV1Response = { - messageType: OdapMessageType.InitializationResponse, + messageType: SatpMessageType.InitializationResponse, sessionID: uuidV4(), initialRequestMessageHash: "wrongMessageHash", timeStamp: Date.now().toString(), @@ -239,6 +237,8 @@ test("timeout in transfer initiation request because no server gateway is connec }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/logging.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/logging.test.ts index 68123bd74f..9bea4dc804 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/logging.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/logging.test.ts @@ -1,31 +1,15 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Secp256k1Keys, - Servers, -} from "@hyperledger/cactus-common"; +import { Secp256k1Keys } from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { PluginSatpGateway } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; - import { - LocalLog, - SessionData, -} from "../../../../main/typescript/public-api"; + ILocalLog, + PluginSatpGateway, +} from "../../../../main/typescript/gateway/plugin-satp-gateway"; + +import { SessionData } from "../../../../main/typescript/public-api"; import { SHA256 } from "crypto-js"; -import { - BesuSatpGateway, - IBesuSatpGatewayConstructorOptions, -} from "../../../../main/typescript/gateway/besu-satp-gateway"; +import { BesuSatpGateway } from "../../../../main/typescript/gateway/besu-satp-gateway"; import { FabricSatpGateway, IFabricSatpGatewayConstructorOptions, @@ -33,12 +17,13 @@ import { import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../../knex.config"; - -const logLevel: LogLevelDesc = "TRACE"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../../knex.config"; let sourceGatewayConstructor: IFabricSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IBesuSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; @@ -49,85 +34,37 @@ let type2: string; let type3: string; let type4: string; let operation: string; -let odapLog: LocalLog; -let odapLog2: LocalLog; -let odapLog3: LocalLog; -let odapLog4: LocalLog; +let satpLog: ILocalLog; +let satpLog2: ILocalLog; +let satpLog3: ILocalLog; +let satpLog4: ILocalLog; let sessionData: SessionData; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); +beforeEach(async () => { + sessionID = uuidv4(); + step = 3; + type = "type1"; + operation = "operation1"; sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; -}); - -beforeEach(async () => { - sessionID = uuidv4(); - step = 3; - type = "type1"; - operation = "operation1"; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); @@ -139,7 +76,7 @@ beforeEach(async () => { recipientGatewayPubkey: pluginRecipientGateway.pubKey, }; - odapLog = { + satpLog = { sessionID: sessionID, type: type, operation: operation, @@ -150,32 +87,25 @@ beforeEach(async () => { pluginRecipientGateway.sessions.set(sessionID, sessionData); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); -}); - -afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); }); test("successful translation of log keys", async () => { - expect(PluginSatpGateway.getOdapLogKey(sessionID, type, operation)).toBe( + expect(PluginSatpGateway.getSatpLogKey(sessionID, type, operation)).toBe( `${sessionID}-${type}-${operation}`, ); }); test("successful logging of proof to ipfs and sqlite", async () => { const claim = "claim"; - const odapLogKey = PluginSatpGateway.getOdapLogKey( + const satpLogKey = PluginSatpGateway.getSatpLogKey( sessionID, "proof", "lock", @@ -188,20 +118,21 @@ test("successful logging of proof to ipfs and sqlite", async () => { data: claim, }); - const retrievedLogIPFS = await pluginSourceGateway.getLogFromIPFS(odapLogKey); + const retrievedLogRemote = + await pluginSourceGateway.getLogFromRemote(satpLogKey); const retrievedLogDB = - await pluginSourceGateway.getLogFromDatabase(odapLogKey); + await pluginSourceGateway.getLogFromDatabase(satpLogKey); - if (retrievedLogDB == undefined || retrievedLogIPFS == undefined) { + if (retrievedLogDB == undefined || retrievedLogRemote == undefined) { throw new Error("Test Failed"); } - expect(retrievedLogIPFS.key).toBe(odapLogKey); - expect(retrievedLogDB.key).toBe(odapLogKey); - expect(retrievedLogIPFS.hash).toBe(SHA256(claim).toString()); + expect(retrievedLogRemote.key).toBe(satpLogKey); + expect(retrievedLogDB.key).toBe(satpLogKey); + expect(retrievedLogRemote.hash).toBe(SHA256(claim).toString()); expect( pluginRecipientGateway.verifySignature( - retrievedLogIPFS, + retrievedLogRemote, pluginSourceGateway.pubKey, ), ).toBe(true); @@ -210,31 +141,32 @@ test("successful logging of proof to ipfs and sqlite", async () => { }); test("successful logging to ipfs and sqlite", async () => { - const odapLogKey = PluginSatpGateway.getOdapLogKey( + const satpLogKey = PluginSatpGateway.getSatpLogKey( sessionID, type, operation, ); - await pluginSourceGateway.storeLog(odapLog); + await pluginSourceGateway.storeLog(satpLog); - const retrievedLogIPFS = await pluginSourceGateway.getLogFromIPFS(odapLogKey); + const retrievedLogRemote = + await pluginSourceGateway.getLogFromRemote(satpLogKey); const retrievedLogDB = - await pluginSourceGateway.getLogFromDatabase(odapLogKey); + await pluginSourceGateway.getLogFromDatabase(satpLogKey); if ( - retrievedLogIPFS == undefined || + retrievedLogRemote == undefined || retrievedLogDB == undefined || retrievedLogDB.data == undefined || - odapLog.data == undefined + satpLog.data == undefined ) { throw new Error("Test failed"); } - expect(retrievedLogIPFS.signerPubKey).toBe(pluginSourceGateway.pubKey); - expect(retrievedLogIPFS.hash).toBe( + expect(retrievedLogRemote.signerPubKey).toBe(pluginSourceGateway.pubKey); + expect(retrievedLogRemote.hash).toBe( SHA256( - JSON.stringify(odapLog, [ + JSON.stringify(satpLog, [ "sessionID", "type", "key", @@ -244,61 +176,61 @@ test("successful logging to ipfs and sqlite", async () => { ]), ).toString(), ); - expect(retrievedLogIPFS.key).toBe(odapLogKey); + expect(retrievedLogRemote.key).toBe(satpLogKey); - expect(retrievedLogDB.type).toBe(odapLog.type); - expect(retrievedLogDB.operation).toBe(odapLog.operation); - expect(retrievedLogDB.data).toBe(odapLog.data); + expect(retrievedLogDB.type).toBe(satpLog.type); + expect(retrievedLogDB.operation).toBe(satpLog.operation); + expect(retrievedLogDB.data).toBe(satpLog.data); - expect(retrievedLogDB.timestamp).toBe(odapLog.timestamp); - expect(retrievedLogDB.type).toBe(odapLog.type); - expect(retrievedLogDB.operation).toBe(odapLog.operation); - expect(retrievedLogDB.sessionID).toBe(odapLog.sessionID); - expect(retrievedLogDB.key).toBe(odapLogKey); + expect(retrievedLogDB.timestamp).toBe(satpLog.timestamp); + expect(retrievedLogDB.type).toBe(satpLog.type); + expect(retrievedLogDB.operation).toBe(satpLog.operation); + expect(retrievedLogDB.sessionID).toBe(satpLog.sessionID); + expect(retrievedLogDB.key).toBe(satpLogKey); }); test("successful retrieval of last log", async () => { type2 = type + "2"; type3 = type + "3"; - odapLog2 = { + satpLog2 = { sessionID: sessionID, type: type2, operation: operation, data: JSON.stringify(sessionData), }; - odapLog3 = { + satpLog3 = { sessionID: sessionID, type: type3, operation: operation, data: JSON.stringify(sessionData), }; - await pluginSourceGateway.storeLog(odapLog2); - await pluginSourceGateway.storeLog(odapLog3); + await pluginSourceGateway.storeLog(satpLog2); + await pluginSourceGateway.storeLog(satpLog3); const lastLog = await pluginSourceGateway.getLastLogFromDatabase(sessionID); if ( lastLog == undefined || - odapLog3 == undefined || + satpLog3 == undefined || lastLog.data == undefined || - odapLog3.data == undefined + satpLog3.data == undefined ) { throw new Error("Test failed"); } - expect(lastLog.type).toBe(odapLog3.type); - expect(lastLog.operation).toBe(odapLog3.operation); - expect(lastLog.data).toBe(odapLog3.data); + expect(lastLog.type).toBe(satpLog3.type); + expect(lastLog.operation).toBe(satpLog3.operation); + expect(lastLog.data).toBe(satpLog3.data); - expect(lastLog.timestamp).toBe(odapLog3.timestamp); - expect(lastLog.type).toBe(odapLog3.type); - expect(lastLog.operation).toBe(odapLog3.operation); - expect(lastLog.sessionID).toBe(odapLog3.sessionID); + expect(lastLog.timestamp).toBe(satpLog3.timestamp); + expect(lastLog.type).toBe(satpLog3.type); + expect(lastLog.operation).toBe(satpLog3.operation); + expect(lastLog.sessionID).toBe(satpLog3.sessionID); expect(lastLog.key).toBe( - PluginSatpGateway.getOdapLogKey(sessionID, type3, operation), + PluginSatpGateway.getSatpLogKey(sessionID, type3, operation), ); }); @@ -306,27 +238,27 @@ test("successful retrieval of logs more recent than another log", async () => { type2 = type + "2"; type3 = type + "3"; - odapLog2 = { + satpLog2 = { sessionID: sessionID, type: type2, operation: operation, data: JSON.stringify(sessionData), }; - odapLog3 = { + satpLog3 = { sessionID: sessionID, type: type3, operation: operation, data: JSON.stringify(sessionData), }; - await pluginSourceGateway.storeLog(odapLog2); + await pluginSourceGateway.storeLog(satpLog2); const referenceTimestamp = Date.now().toString(); await new Promise((resolve) => setTimeout(resolve, 1000)); - await pluginSourceGateway.storeLog(odapLog); - await pluginSourceGateway.storeLog(odapLog3); + await pluginSourceGateway.storeLog(satpLog); + await pluginSourceGateway.storeLog(satpLog3); const moreRecentLogs = await pluginSourceGateway.getLogsMoreRecentThanTimestamp( @@ -338,34 +270,34 @@ test("successful retrieval of logs more recent than another log", async () => { moreRecentLogs.length != 2 || moreRecentLogs[0].data == undefined || moreRecentLogs[1].data == undefined || - odapLog.data == undefined || - odapLog3.data == undefined + satpLog.data == undefined || + satpLog3.data == undefined ) { throw new Error("Test failed"); } - expect(moreRecentLogs[0].type).toBe(odapLog.type); - expect(moreRecentLogs[0].operation).toBe(odapLog.operation); - expect(moreRecentLogs[0].data).toBe(odapLog.data); + expect(moreRecentLogs[0].type).toBe(satpLog.type); + expect(moreRecentLogs[0].operation).toBe(satpLog.operation); + expect(moreRecentLogs[0].data).toBe(satpLog.data); - expect(moreRecentLogs[0].timestamp).toBe(odapLog.timestamp); - expect(moreRecentLogs[0].type).toBe(odapLog.type); - expect(moreRecentLogs[0].operation).toBe(odapLog.operation); - expect(moreRecentLogs[0].sessionID).toBe(odapLog.sessionID); + expect(moreRecentLogs[0].timestamp).toBe(satpLog.timestamp); + expect(moreRecentLogs[0].type).toBe(satpLog.type); + expect(moreRecentLogs[0].operation).toBe(satpLog.operation); + expect(moreRecentLogs[0].sessionID).toBe(satpLog.sessionID); expect(moreRecentLogs[0].key).toBe( - PluginSatpGateway.getOdapLogKey(sessionID, type, operation), + PluginSatpGateway.getSatpLogKey(sessionID, type, operation), ); - expect(moreRecentLogs[1].type).toBe(odapLog3.type); - expect(moreRecentLogs[1].operation).toBe(odapLog3.operation); - expect(moreRecentLogs[1].data).toBe(odapLog3.data); + expect(moreRecentLogs[1].type).toBe(satpLog3.type); + expect(moreRecentLogs[1].operation).toBe(satpLog3.operation); + expect(moreRecentLogs[1].data).toBe(satpLog3.data); - expect(moreRecentLogs[1].timestamp).toBe(odapLog3.timestamp); - expect(moreRecentLogs[1].type).toBe(odapLog3.type); - expect(moreRecentLogs[1].operation).toBe(odapLog3.operation); - expect(moreRecentLogs[1].sessionID).toBe(odapLog3.sessionID); + expect(moreRecentLogs[1].timestamp).toBe(satpLog3.timestamp); + expect(moreRecentLogs[1].type).toBe(satpLog3.type); + expect(moreRecentLogs[1].operation).toBe(satpLog3.operation); + expect(moreRecentLogs[1].sessionID).toBe(satpLog3.sessionID); expect(moreRecentLogs[1].key).toBe( - PluginSatpGateway.getOdapLogKey(sessionID, type3, operation), + PluginSatpGateway.getSatpLogKey(sessionID, type3, operation), ); }); @@ -394,21 +326,21 @@ test("successful recover of sessions after crash", async () => { recipientGatewayPubkey: pluginRecipientGateway.pubKey, }; - odapLog2 = { + satpLog2 = { sessionID: sessionID, type: type2, operation: operation, data: JSON.stringify(sessionData), }; - odapLog3 = { + satpLog3 = { sessionID: sessionID, type: type3, operation: operation, data: JSON.stringify(sessionData), }; - odapLog4 = { + satpLog4 = { sessionID: newSessionID, type: type4, operation: operation, @@ -417,13 +349,13 @@ test("successful recover of sessions after crash", async () => { pluginSourceGateway.sessions.set(newSessionID, data); - await pluginSourceGateway.storeLog(odapLog); - await pluginSourceGateway.storeLog(odapLog3); - await pluginSourceGateway.storeLog(odapLog2); - await pluginSourceGateway.storeLog(odapLog4); + await pluginSourceGateway.storeLog(satpLog); + await pluginSourceGateway.storeLog(satpLog3); + await pluginSourceGateway.storeLog(satpLog2); + await pluginSourceGateway.storeLog(satpLog4); // simulate the crash of one gateway - pluginSourceGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); const newPluginSourceGateway = new FabricSatpGateway( sourceGatewayConstructor, ); @@ -447,13 +379,12 @@ test("successful recover of sessions after crash", async () => { expect(data.recipientGatewayPubkey).toBe(pluginRecipientGateway.pubKey); } - newPluginSourceGateway.database?.destroy(); + newPluginSourceGateway.localRepository?.destroy(); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); +afterEach(async () => { + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-success.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-success.test.ts index 2cca94f454..9ba8213ba8 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-success.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-success.test.ts @@ -1,20 +1,7 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; import { PluginSatpGateway } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { RecoverSuccessV1Message, @@ -27,100 +14,51 @@ import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-sa import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../../knex.config"; - -const logLevel: LogLevelDesc = "TRACE"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../../knex.config"; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let sessionID: string; let sessionData: SessionData; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - let sequenceNumber: number; -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - // t.comment(`Go IPFS Test Container API URL: ${ipfsApiUrl}`); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sessionID = uuidv4(); sequenceNumber = randomInt(100); @@ -172,12 +110,8 @@ test("valid recover success message from server", async () => { }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); -}); - -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update-ack.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update-ack.test.ts index e1fefca63d..7aee41c579 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update-ack.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update-ack.test.ts @@ -1,20 +1,7 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; import { PluginSatpGateway } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { RecoverUpdateAckV1Message, @@ -27,75 +14,28 @@ import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-sa import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../../knex.config"; - -const logLevel: LogLevelDesc = "TRACE"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../../knex.config"; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let sessionID: string; let sessionData: SessionData; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - let sequenceNumber: number; -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - // t.comment(`Go IPFS Test Container API URL: ${ipfsApiUrl}`); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", @@ -103,23 +43,22 @@ beforeEach(async () => { instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sessionID = uuidv4(); sequenceNumber = randomInt(100); @@ -173,12 +112,8 @@ test("valid recover update ack message from server", async () => { }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); -}); - -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update.test.ts index cd7447079c..070154ea22 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover-update.test.ts @@ -1,24 +1,10 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Secp256k1Keys, - Servers, -} from "@hyperledger/cactus-common"; +import { Secp256k1Keys } from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; import { PluginSatpGateway } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; import { - LocalLog, RecoverUpdateV1Message, RecoverV1Message, SessionData, @@ -35,9 +21,11 @@ import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-sa import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../../knex.config"; - -const logLevel: LogLevelDesc = "TRACE"; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; @@ -47,93 +35,42 @@ let pluginRecipientGateway: PluginSatpGateway; let sessionID: string; let sessionData: SessionData; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - let sequenceNumber: number; -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - // t.comment(`Go IPFS Test Container API URL: ${ipfsApiUrl}`); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); sessionID = uuidv4(); sequenceNumber = randomInt(100); @@ -148,11 +85,6 @@ beforeEach(async () => { pluginRecipientGateway.sessions.set(sessionID, sessionData); }); -afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); -}); - test("valid recover update message from server", async () => { const recoverUpdateMessage: RecoverUpdateV1Message = { sessionID: sessionID, @@ -172,7 +104,7 @@ test("valid recover update message from server", async () => { }); }); -test("check valid built of recover update message", async () => { +test("check valid build of recover update message", async () => { const sessionData1: SessionData = { id: sessionID, maxRetries: MAX_RETRIES, @@ -199,44 +131,36 @@ test("check valid built of recover update message", async () => { pluginRecipientGateway.sessions.set(sessionID, sessionData2); - const odapLog1: LocalLog = { + const firstTimestamp = Date.now().toString(); + await new Promise((resolve) => setTimeout(resolve, 5000)); + + await pluginSourceGateway.storeLog({ sessionID: sessionID, type: "init", operation: "validate", data: JSON.stringify(sessionData), - }; - - const firstTimestamp = Date.now().toString(); - await new Promise((resolve) => setTimeout(resolve, 5000)); - - await pluginSourceGateway.storeLog(odapLog1); + }); - const odapLog2: LocalLog = { + await pluginRecipientGateway.storeLog({ sessionID: sessionID, type: "exec", operation: "validate", data: JSON.stringify(sessionData), - }; - - await pluginRecipientGateway.storeLog(odapLog2); + }); - const odapLog3: LocalLog = { + await pluginRecipientGateway.storeLog({ sessionID: sessionID, type: "done", operation: "validate", data: JSON.stringify(sessionData), - }; - - await pluginRecipientGateway.storeLog(odapLog3); + }); - const odapLog4: LocalLog = { + await pluginRecipientGateway.storeLog({ sessionID: sessionID, type: "ack", operation: "validate", data: JSON.stringify(sessionData), - }; - - await pluginRecipientGateway.storeLog(odapLog4); + }); const recoverMessage: RecoverV1Message = { sessionID: sessionID, @@ -276,10 +200,9 @@ test("check valid built of recover update message", async () => { expect(pluginRecipientGateway.sessions.get(sessionId)).toBe(sessionData2); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); +afterEach(() => { + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover.test.ts index d87df27892..ea25ec8b7c 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/recovery/recover.test.ts @@ -1,24 +1,7 @@ -import http, { Server } from "http"; -import type { AddressInfo } from "net"; -import { v4 as uuidv4 } from "uuid"; import "jest-extended"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import bodyParser from "body-parser"; -import express from "express"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { - IListenOptions, - LogLevelDesc, - Secp256k1Keys, - Servers, -} from "@hyperledger/cactus-common"; +import { Secp256k1Keys } from "@hyperledger/cactus-common"; import { v4 as uuidV4 } from "uuid"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { - IPluginSatpGatewayConstructorOptions, - PluginSatpGateway, -} from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; +import { PluginSatpGateway } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { RecoverV1Message } from "../../../../main/typescript/public-api"; import { randomInt } from "crypto"; @@ -29,91 +12,42 @@ import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-sa import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; -import { knexClientConnection, knexServerConnection } from "../../knex.config"; - -const logLevel: LogLevelDesc = "TRACE"; - -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; +import { + knexClientConnection, + knexRemoteConnection, + knexServerConnection, +} from "../../knex.config"; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let sessionID: string; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - let sequenceNumber: number; -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); +beforeEach(async () => { + sessionID = uuidV4(); + sequenceNumber = randomInt(100); - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexClientConnection, + knexLocalConfig: knexClientConnection, + knexRemoteConfig: knexRemoteConnection, }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, keyPair: Secp256k1Keys.generateKeyPairsBuffer(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), - knexConfig: knexServerConnection, + knexLocalConfig: knexServerConnection, + knexRemoteConfig: knexRemoteConnection, }; -}); - -beforeEach(async () => { - sessionID = uuidv4(); - sequenceNumber = randomInt(100); pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); @@ -135,21 +69,14 @@ beforeEach(async () => { pluginRecipientGateway.sessions.set(sessionID, sessionData); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); -}); - -afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); }); test("valid recover message request from client", async () => { @@ -216,10 +143,9 @@ test("recover message request from client with wrong signature", async () => { ); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); +afterEach(() => { + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-final.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-final.test.ts index 106982cffa..d2eeaf8f7d 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-final.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-final.test.ts @@ -1,44 +1,28 @@ import { randomInt } from "crypto"; import { v4 as uuidv4 } from "uuid"; -import bodyParser from "body-parser"; -import http, { Server } from "http"; import { SHA256 } from "crypto-js"; import { - IPluginSatpGatewayConstructorOptions, - OdapMessageType, + SatpMessageType, PluginSatpGateway, + ILocalLog, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; + import { CommitFinalV1Request, SessionData, } from "../../../../main/typescript/generated/openapi/typescript-axios/api"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; - -import express from "express"; -import { AddressInfo } from "net"; import { BesuSatpGateway } from "../../../../main/typescript/gateway/besu-satp-gateway"; import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-satp-gateway"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; +import { knexRemoteConnection } from "../../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -const logLevel: LogLevelDesc = "TRACE"; - const COMMIT_FINAL_CLAIM = "dummyCommitFinalClaim"; -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let dummyCommitPreparationResponseMessageHash: string; @@ -46,87 +30,37 @@ let sessionData: SessionData; let sessionID: string; let sequenceNumber: number; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidv4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); dummyCommitPreparationResponseMessageHash = SHA256( "commitPreparationResponseMessageData", @@ -158,30 +92,23 @@ beforeEach(async () => { type: "proof", operation: "delete", data: COMMIT_FINAL_CLAIM, - }); + } as ILocalLog); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); -}); - -afterEach(async () => { - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); }); test("valid commit final request", async () => { const commitFinalRequestMessage: CommitFinalV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalRequest, + messageType: SatpMessageType.CommitFinalRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -221,7 +148,7 @@ test("commit final request with wrong sessionId", async () => { const commitFinalRequestMessage: CommitFinalV1Request = { sessionID: wrongSessionId, - messageType: OdapMessageType.CommitFinalRequest, + messageType: SatpMessageType.CommitFinalRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -252,7 +179,7 @@ test("commit final request with wrong sessionId", async () => { test("commit final request with wrong message type", async () => { const commitFinalRequestMessage: CommitFinalV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -281,7 +208,7 @@ test("commit final request with wrong message type", async () => { test("commit final request with wrong previous message hash", async () => { const commitFinalRequestMessage: CommitFinalV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalRequest, + messageType: SatpMessageType.CommitFinalRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -337,15 +264,9 @@ test("timeout in commit final response because no client gateway is connected", }); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - await pluginSourceGateway.database?.destroy(); - await pluginRecipientGateway.database?.destroy(); -}); - afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-preparation.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-preparation.test.ts index caa67c3b22..7a5fe43217 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-preparation.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/commit-preparation.test.ts @@ -1,7 +1,6 @@ import { randomInt } from "crypto"; import { - IPluginSatpGatewayConstructorOptions, - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -18,8 +17,6 @@ import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/ const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let dummyLockEvidenceResponseMessageHash: string; @@ -28,14 +25,14 @@ let sessionID: string; let sequenceNumber: number; beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), @@ -47,16 +44,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); dummyLockEvidenceResponseMessageHash = SHA256( "lockEvidenceResponseMessageData", @@ -87,7 +82,7 @@ beforeEach(async () => { test("valid commit prepare request", async () => { const commitPrepareRequestMessage: CommitPreparationV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitPreparationRequest, + messageType: SatpMessageType.CommitPreparationRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -124,7 +119,7 @@ test("commit prepare request with wrong sessionId", async () => { const commitPrepareRequestMessage: CommitPreparationV1Request = { sessionID: wrongSessionId, - messageType: OdapMessageType.CommitPreparationRequest, + messageType: SatpMessageType.CommitPreparationRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -154,7 +149,7 @@ test("commit prepare request with wrong sessionId", async () => { test("commit prepare request with wrong message type", async () => { const commitPrepareRequestMessage: CommitPreparationV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitFinalResponse, + messageType: SatpMessageType.CommitFinalResponse, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -184,7 +179,7 @@ test("commit prepare request with wrong message type", async () => { test("commit prepare request with wrong previous message hash", async () => { const commitPrepareRequestMessage: CommitPreparationV1Request = { sessionID: sessionID, - messageType: OdapMessageType.CommitPreparationRequest, + messageType: SatpMessageType.CommitPreparationRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -239,6 +234,8 @@ test("timeout in commit preparation response because no client gateway is connec }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/lock-evidence.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/lock-evidence.test.ts index e88198bab1..fc23aeef54 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/lock-evidence.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/lock-evidence.test.ts @@ -1,45 +1,26 @@ import { randomInt } from "crypto"; -import { v4 as uuidv4 } from "uuid"; -import bodyParser from "body-parser"; -import http, { Server } from "http"; import { - IPluginSatpGatewayConstructorOptions, - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { LockEvidenceV1Request, SessionData, } from "../../../../main/typescript/generated/openapi/typescript-axios/api"; -import { DefaultApi as ObjectStoreIpfsApi } from "@hyperledger/cactus-plugin-object-store-ipfs"; import { v4 as uuidV4 } from "uuid"; import { SHA256 } from "crypto-js"; -import { - IListenOptions, - LogLevelDesc, - Servers, -} from "@hyperledger/cactus-common"; -import { Configuration } from "@hyperledger/cactus-core-api"; -import { PluginObjectStoreIpfs } from "@hyperledger/cactus-plugin-object-store-ipfs"; -import { GoIpfsTestContainer } from "@hyperledger/cactus-test-tooling"; - -import express from "express"; -import { AddressInfo } from "net"; import { BesuSatpGateway } from "../../../../main/typescript/gateway/besu-satp-gateway"; import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-satp-gateway"; import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../../knex.config"; const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -const logLevel: LogLevelDesc = "TRACE"; - const LOCK_EVIDENCE_CLAIM = "dummyLockEvidenceClaim"; -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let dummyTransferCommenceResponseMessageHash: string; @@ -48,86 +29,36 @@ let lockExpiryDate: string; let sessionID: string; let sequenceNumber: number; -let ipfsContainer: GoIpfsTestContainer; -let ipfsServer: Server; -let ipfsApiHost: string; - -beforeAll(async () => { - ipfsContainer = new GoIpfsTestContainer({ logLevel }); - expect(ipfsContainer).not.toBeUndefined(); - - const container = await ipfsContainer.start(); - expect(container).not.toBeUndefined(); - - const expressApp = express(); - expressApp.use(bodyParser.json({ limit: "250mb" })); - ipfsServer = http.createServer(expressApp); - const listenOptions: IListenOptions = { - hostname: "127.0.0.1", - port: 0, - server: ipfsServer, - }; - - const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; - const { address, port } = addressInfo; - ipfsApiHost = `http://${address}:${port}`; - - const config = new Configuration({ basePath: ipfsApiHost }); - const apiClient = new ObjectStoreIpfsApi(config); - - expect(apiClient).not.toBeUndefined(); - - const ipfsApiUrl = await ipfsContainer.getApiUrl(); - - const kuboRpcModule = await import("kubo-rpc-client"); - const ipfsClientOrOptions = kuboRpcModule.create({ - url: ipfsApiUrl, - }); - - const instanceId = uuidv4(); - const pluginIpfs = new PluginObjectStoreIpfs({ - parentDir: `/${uuidv4()}/${uuidv4()}/`, - logLevel, - instanceId, - ipfsClientOrOptions, - }); - - await pluginIpfs.getOrCreateWebServices(); - await pluginIpfs.registerWebServices(expressApp); -}); - beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), - ipfsPath: ipfsApiHost, clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); dummyTransferCommenceResponseMessageHash = SHA256( "transferCommenceResponseMessageData", @@ -165,27 +96,25 @@ beforeEach(async () => { }); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); }); test("valid lock evidence request", async () => { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceRequest, + messageType: SatpMessageType.LockEvidenceRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -225,7 +154,7 @@ test("lock evidence request with wrong sessionId", async () => { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: wrongSessionId, - messageType: OdapMessageType.LockEvidenceRequest, + messageType: SatpMessageType.LockEvidenceRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -257,7 +186,7 @@ test("lock evidence request with wrong sessionId", async () => { test("lock evidence request with wrong message type", async () => { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceResponse, + messageType: SatpMessageType.LockEvidenceResponse, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -287,7 +216,7 @@ test("lock evidence request with wrong message type", async () => { test("lock evidence request with wrong previous message hash", async () => { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceRequest, + messageType: SatpMessageType.LockEvidenceRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -317,7 +246,7 @@ test("lock evidence request with wrong previous message hash", async () => { test("transfer commence flow with invalid claim", async () => { const lockEvidenceRequestMessage: LockEvidenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.LockEvidenceRequest, + messageType: SatpMessageType.LockEvidenceRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -374,15 +303,9 @@ test("timeout in lock evidence response because no client gateway is connected", }); }); -afterAll(async () => { - await ipfsContainer.stop(); - await ipfsContainer.destroy(); - await Servers.shutdown(ipfsServer); - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); -}); - afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-commence.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-commence.test.ts index 3a47e34629..d1b4484278 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-commence.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-commence.test.ts @@ -1,7 +1,6 @@ import { randomInt } from "crypto"; import { - IPluginSatpGatewayConstructorOptions, - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -19,8 +18,6 @@ import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/ const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let dummyInitializationResponseMessageHash: string; @@ -32,14 +29,14 @@ let sessionID: string; let sequenceNumber: number; beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), @@ -51,16 +48,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); dummyInitializationResponseMessageHash = SHA256( "initializationResponseMessageData", @@ -101,7 +96,7 @@ beforeEach(async () => { test("valid transfer commence request", async () => { const transferCommenceRequest: TransferCommenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, originatorPubkey: "originatorDummyPubKey", beneficiaryPubkey: "beneficiaryDummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -146,7 +141,7 @@ test("transfer commence request with wrong sessionId", async () => { const wrongSessionId = uuidV4(); const transferCommenceRequest: TransferCommenceV1Request = { sessionID: wrongSessionId, - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, originatorPubkey: "dummyPubKey", beneficiaryPubkey: "dummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -181,7 +176,7 @@ test("transfer commence request with wrong sessionId", async () => { test("transfer commence request with wrong message type", async () => { const transferCommenceRequest: TransferCommenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceResponse, + messageType: SatpMessageType.TransferCommenceResponse, originatorPubkey: "dummyPubKey", beneficiaryPubkey: "dummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -216,7 +211,7 @@ test("transfer commence request with wrong message type", async () => { test("transfer commence request with wrong signature", async () => { const transferCommenceRequest: TransferCommenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, originatorPubkey: "dummyPubKey", beneficiaryPubkey: "dummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -251,7 +246,7 @@ test("transfer commence request with wrong signature", async () => { test("transfer commence request with wrong previous message hash", async () => { const transferCommenceRequest: TransferCommenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, originatorPubkey: "dummyPubKey", beneficiaryPubkey: "dummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -286,7 +281,7 @@ test("transfer commence request with wrong previous message hash", async () => { test("transfer commence request with wrong asset profile hash", async () => { const transferCommenceRequest: TransferCommenceV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCommenceRequest, + messageType: SatpMessageType.TransferCommenceRequest, originatorPubkey: "dummyPubKey", beneficiaryPubkey: "dummyPubKey", clientIdentityPubkey: pluginSourceGateway.pubKey, @@ -347,6 +342,8 @@ test("timeout in transfer commence response because no client gateway is connect }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-complete.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-complete.test.ts index cada10e280..aab405e348 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-complete.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-complete.test.ts @@ -1,6 +1,5 @@ import { - IPluginSatpGatewayConstructorOptions, - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -14,9 +13,8 @@ import { BesuSatpGateway } from "../../../../main/typescript/gateway/besu-satp-g import { FabricSatpGateway } from "../../../../main/typescript/gateway/fabric-satp-gateway"; import { ClientGatewayHelper } from "../../../../main/typescript/gateway/client/client-helper"; import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/server-helper"; +import { knexRemoteConnection } from "../../knex.config"; -let sourceGatewayConstructor: IPluginSatpGatewayConstructorOptions; -let recipientGatewayConstructor: IPluginSatpGatewayConstructorOptions; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let dummyCommitFinalResponseMessageHash: string; @@ -26,35 +24,35 @@ let sessionID: string; let sequenceNumber: number; beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), + knexRemoteConfig: knexRemoteConnection, }; pluginSourceGateway = new FabricSatpGateway(sourceGatewayConstructor); pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); dummyCommitFinalResponseMessageHash = SHA256( "commitFinalResponseMessageData", @@ -91,7 +89,7 @@ beforeEach(async () => { test("dummy test for transfer complete flow", async () => { const transferCompleteRequestMessage: TransferCompleteV1Request = { sessionID: sessionID, - messageType: OdapMessageType.TransferCompleteRequest, + messageType: SatpMessageType.TransferCompleteRequest, clientIdentityPubkey: pluginSourceGateway.pubKey, serverIdentityPubkey: pluginRecipientGateway.pubKey, signature: "", @@ -104,17 +102,15 @@ test("dummy test for transfer complete flow", async () => { pluginSourceGateway.sign(JSON.stringify(transferCompleteRequestMessage)), ); - pluginRecipientGateway.serverHelper - .checkValidTransferCompleteRequest( - transferCompleteRequestMessage, - pluginRecipientGateway, - ) - .catch(() => { - throw new Error("Test failed"); - }); + await pluginRecipientGateway.serverHelper.checkValidTransferCompleteRequest( + transferCompleteRequestMessage, + pluginRecipientGateway, + ); }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); }); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-initialization.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-initialization.test.ts index 1dc1f229ac..9615f80401 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-initialization.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/server/transfer-initialization.test.ts @@ -2,7 +2,7 @@ import { randomInt } from "crypto"; import { SHA256 } from "crypto-js"; import { v4 as uuidV4 } from "uuid"; import { - OdapMessageType, + SatpMessageType, PluginSatpGateway, } from "../../../../main/typescript/gateway/plugin-satp-gateway"; import { @@ -18,8 +18,6 @@ import { ServerGatewayHelper } from "../../../../main/typescript/gateway/server/ const MAX_RETRIES = 5; const MAX_TIMEOUT = 5000; -let sourceGatewayConstructor; -let recipientGatewayConstructor; let pluginSourceGateway: PluginSatpGateway; let pluginRecipientGateway: PluginSatpGateway; let expiryDate: string; @@ -28,14 +26,14 @@ let sequenceNumber: number; let sessionID: string; beforeEach(async () => { - sourceGatewayConstructor = { + const sourceGatewayConstructor = { name: "plugin-satp-gateway#sourceGateway", dltIDs: ["DLT2"], instanceId: uuidV4(), clientHelper: new ClientGatewayHelper(), serverHelper: new ServerGatewayHelper(), }; - recipientGatewayConstructor = { + const recipientGatewayConstructor = { name: "plugin-satp-gateway#recipientGateway", dltIDs: ["DLT1"], instanceId: uuidV4(), @@ -47,16 +45,14 @@ beforeEach(async () => { pluginRecipientGateway = new BesuSatpGateway(recipientGatewayConstructor); if ( - pluginSourceGateway.database == undefined || - pluginRecipientGateway.database == undefined + pluginSourceGateway.localRepository?.database == undefined || + pluginRecipientGateway.localRepository?.database == undefined ) { throw new Error("Database is not correctly initialized"); } - await pluginSourceGateway.database.migrate.rollback(); - await pluginSourceGateway.database.migrate.latest(); - await pluginRecipientGateway.database.migrate.rollback(); - await pluginRecipientGateway.database.migrate.latest(); + await pluginSourceGateway.localRepository?.reset(); + await pluginRecipientGateway.localRepository?.reset(); expiryDate = new Date(2060, 11, 24).toString(); assetProfile = { expirationDate: expiryDate }; @@ -69,7 +65,7 @@ test("valid transfer initiation request", async () => { const initializationRequestMessage: TransferInitializationV1Request = { maxRetries: MAX_RETRIES, maxTimeout: MAX_TIMEOUT, - messageType: OdapMessageType.InitializationRequest, + messageType: SatpMessageType.InitializationRequest, sessionID: sessionID, version: "0.0.0", loggingProfile: "dummyLoggingProfile", @@ -137,7 +133,7 @@ test("transfer initiation request invalid because of incompatible DLTs", async ( const initializationRequestMessage: TransferInitializationV1Request = { maxRetries: MAX_RETRIES, maxTimeout: MAX_TIMEOUT, - messageType: OdapMessageType.InitializationRequest, + messageType: SatpMessageType.InitializationRequest, sessionID: sessionID, version: "0.0.0", loggingProfile: "dummy", @@ -188,7 +184,7 @@ test("transfer initiation request invalid because of asset expired", async () => const initializationRequestMessage: TransferInitializationV1Request = { maxRetries: MAX_RETRIES, maxTimeout: MAX_TIMEOUT, - messageType: OdapMessageType.InitializationRequest, + messageType: SatpMessageType.InitializationRequest, sessionID: sessionID, version: "0.0.0", loggingProfile: "dummy", @@ -259,6 +255,8 @@ test("timeout in commit final response because no client gateway is connected", }); afterEach(() => { - pluginSourceGateway.database?.destroy(); - pluginRecipientGateway.database?.destroy(); + pluginSourceGateway.localRepository?.destroy(); + pluginRecipientGateway.localRepository?.destroy(); + pluginSourceGateway.remoteRepository?.destroy(); + pluginRecipientGateway.remoteRepository?.destroy(); });