diff --git a/packages/cactus-plugin-keychain-aws-sm/docs/architecture/get-keychain-entry-endpoint.puml b/packages/cactus-plugin-keychain-aws-sm/docs/architecture/get-keychain-entry-endpoint.puml index 195b74be5e..c05e81f6dd 100644 --- a/packages/cactus-plugin-keychain-aws-sm/docs/architecture/get-keychain-entry-endpoint.puml +++ b/packages/cactus-plugin-keychain-aws-sm/docs/architecture/get-keychain-entry-endpoint.puml @@ -32,4 +32,4 @@ end awssm --> apis: Response apis --> apic: Formatted Response apic --> a: GetKeychainEntryResponse -@enduml \ No newline at end of file +@enduml diff --git a/packages/cactus-plugin-satp-hermes/docs/initialization-standalone-plugin.puml b/packages/cactus-plugin-satp-hermes/docs/initialization-standalone-plugin.puml new file mode 100644 index 0000000000..e36b77b8b4 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/docs/initialization-standalone-plugin.puml @@ -0,0 +1,52 @@ +@startuml +title Hyperledger Cacti SATP-Hermes\nInitialization (standalone) + +skinparam sequenceArrowThickness 2 +skinparam roundcorner 20 +skinparam maxmessagesize 120 +skinparam sequenceParticipant underline +skinparam autonumber true + +entity "SATPGateway" as g +entity "Orchestrator (GOL)" as gol +entity "Counterparty SATP Gateway" as cg +entity "WebServices" as web +entity "Dispatcher (BLO)" as dispatcher +entity "SATPManager" as manager +component "SATP Core" as core + + +g --> g: constructor(options) +g --> g: ProcessGatewayCoordinatorConfig() +g --> g: basic initialization (logger, signer, etc) + +== GOL Init == +g -> gol: initialize GatewayOrchestrator(GOLoptions) +group #Yellow if { get GOLoptions.CounterpartyGateways() } + gol -> gol: basic initialization (logger, etc) + gol -> gol: connectToCounterPartyGateways() + gol -> gol: createChannel(counterpartyGateway) + gol -> gol: createConnectClients(counterpartyGateway) + gol -> cg: call healthcheck endpoint (TBD 🚨) +else #Pink else only do basic initialization +end +gol --> g: GatewayOrchestrator + +== BLO and SATP Manager Init == +g --> bol: initialize BLODispatcher(options, GatewayOrchestrator) +bol --> bol: expose endpoints via getOrCreateWebServices() +bol --> manager: initialize SATPManager(options) +manager --> core: get SATP Service classes +core --> manager: services +manager --> manager: instantiate services (options) +manager --> core: get SATP Handler classes +core --> manager: handlers +manager --> manager: instatiate handlers (services, options) +manager --> bol: SATP manager + +== Misc == + +g --> g: setup OpenAPI UI server + + +@enduml diff --git a/packages/cactus-plugin-satp-hermes/package.json b/packages/cactus-plugin-satp-hermes/package.json index 12c0743709..45f2175947 100644 --- a/packages/cactus-plugin-satp-hermes/package.json +++ b/packages/cactus-plugin-satp-hermes/package.json @@ -63,7 +63,7 @@ "generate-sdk:typescript-axios-bol": "yarn bundle-openapi-yaml && yarn bundle-openapi-json && openapi-generator-cli generate -i ./src/main/yml/bol/openapi-blo-bundled.yml -g typescript-axios -o ./src/main/typescript/generated/gateway-client/typescript-axios/ --reserved-words-mappings protected=protected --enable-post-process-file", "generate-sdk:go": "openapi-generator-cli generate -i ./src/main/yml/bol/openapi-blo-bundled.yml -g go -o ./src/main/go/generated/gateway-client --additional-properties=packageName=generated,generateInterfaces=true,packageVersion=v0.0.1,moduleName=github.com/hyperledger/cacti/packages/cactus-plugin-satp-hermes/src/main/go/generated --git-user-id hyperledger --git-repo-id cacti/packages/cactus-plugin-satp-hermes/src/main/go/generated", "lint": "run-p 'lint:*'", - "lint:eslint": "eslint '*/*/src/**/*.{js,ts}' --quiet --fix && cspell \"*/*/src/**/*.{js,ts}\"", + "lint:eslint": "eslint './src/**/*.{js,ts}' --quiet --fix && cspell \"*/*/src/**/*.{js,ts}\"", "lint:oapi": "vacuum lint -d -e ./src/main/yml/bol/openapi-blo-bundled.yml", "lint:protobuf": "buf lint --path src/main/proto --verbose", "pretsc": "npm run generate-sdk", diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-audit-handler-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-audit-handler-service.ts deleted file mode 100644 index 65b3dba385..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-audit-handler-service.ts +++ /dev/null @@ -1 +0,0 @@ -// todo diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-status-handler-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-status-handler-service.ts index fad34c1286..76034e9f1e 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-status-handler-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/admin/get-status-handler-service.ts @@ -6,7 +6,7 @@ import { } from "../../generated/gateway-client/typescript-axios"; import { Logger } from "@hyperledger/cactus-common"; -export async function GetStatusHandler( +export async function ExecuteGetStatus( logger: Logger, req: StatusRequest, ): Promise { diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/dispatcher.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/dispatcher.ts index 864372f02e..7a146527d2 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/dispatcher.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/dispatcher.ts @@ -3,25 +3,30 @@ import { Checks, LogLevelDesc, LoggerProvider, + JsObjectSigner, } from "@hyperledger/cactus-common"; import { IWebServiceEndpoint } from "@hyperledger/cactus-core-api"; //import { GatewayIdentity, GatewayChannel } from "../core/types"; //import { GetStatusError, NonExistantGatewayIdentity } from "../core/errors"; -import { GetStatusEndpointV1 } from "../web-services/blo/status-endpoint"; +import { GetStatusEndpointV1 } from "../web-services/status-endpoint"; //import { GetAuditRequest, GetAuditResponse } from "../generated/gateway-client/typescript-axios"; import { StatusRequest, StatusResponse, } from "../generated/gateway-client/typescript-axios"; -import { GetStatusHandler } from "./admin/get-status-handler-service"; +import { ExecuteGetStatus } from "./admin/get-status-handler-service"; +import { ISATPManagerOptions, SATPManager } from "../gol/satp-manager"; +import { GatewayOrchestrator } from "../gol/gateway-orchestrator"; export interface BLODispatcherOptions { logger: Logger; logLevel?: LogLevelDesc; instanceId: string; + orchestrator: GatewayOrchestrator; + signer: JsObjectSigner; } export class BLODispatcher { @@ -29,6 +34,8 @@ export class BLODispatcher { private readonly logger: Logger; private endpoints: IWebServiceEndpoint[] | undefined; private readonly instanceId: string; + private manager: SATPManager; + private orchestrator: GatewayOrchestrator; constructor(public readonly options: BLODispatcherOptions) { const fnTag = `${BLODispatcher.CLASS_NAME}#constructor()`; @@ -39,6 +46,18 @@ export class BLODispatcher { this.logger = LoggerProvider.getOrCreate({ level, label }); this.instanceId = options.instanceId; this.logger.info(`Instantiated ${this.className} OK`); + this.orchestrator = options.orchestrator; + const signer = options.signer; + const ourGateway = this.orchestrator.ourGateway; + + const SATPManagerOpts: ISATPManagerOptions = { + logLevel: "DEBUG", + instanceId: ourGateway!.id, + signer: signer, + supportedDLTs: this.orchestrator.supportedDLTs, + }; + + this.manager = new SATPManager(SATPManagerOpts); } public get className(): string { @@ -64,9 +83,31 @@ export class BLODispatcher { return theEndpoints; } + private getTargetGatewayClient(id: string) { + const channels = Array.from(this.orchestrator.getChannels()); + channels.filter((ch) => { + id == ch[0] && ch[1].toGatewayID == id; + }); + + if (channels.length == 0) { + throw new Error(`No channels with specified target gateway id ${id}`); + } else if (channels.length > 1) { + throw new Error( + `Duplicated channels with specified target gateway id ${id}`, + ); + } else { + return channels[0]; + } + } + public async GetStatus(req: StatusRequest): Promise { - return GetStatusHandler(this.logger, req); + return ExecuteGetStatus(this.logger, req); } + public async Transact(req: StatusRequest): Promise { + return ExecuteGetStatus(this.logger, req); + } + // get channel by caller; give needed client from orchestrator to handler to call + // for all channels, find session id on request // TODO implement handlers GetAudit, Transact, Cancel, Routes } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/cancel-handler-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/cancel-handler-service.ts deleted file mode 100644 index 65b3dba385..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/cancel-handler-service.ts +++ /dev/null @@ -1 +0,0 @@ -// todo diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/routes-handler-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/routes-handler-service.ts deleted file mode 100644 index 65b3dba385..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/blo/transaction/routes-handler-service.ts +++ /dev/null @@ -1 +0,0 @@ -// todo diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts index 0c9fec11af..0eb24f198b 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts @@ -1,5 +1,10 @@ export class SATPError extends Error { - constructor(message: string, public code: number = 500, public internalErrorId?: string, public trace?: string) { + constructor( + message: string, + public code: number = 500, + public internalErrorId?: string, + public trace?: string, + ) { super(message); this.name = this.constructor.name; Object.setPrototypeOf(this, new.target.prototype); // make sure prototype chain is set to error @@ -9,7 +14,12 @@ export class SATPError extends Error { export class BootstrapError extends SATPError { constructor(internalErrorId?: string, trace?: string) { - super("Bootstrap already called in this Gateway Manager", 409, internalErrorId, trace); + super( + "Bootstrap already called in this Gateway Manager", + 409, + internalErrorId, + trace, + ); } } @@ -20,7 +30,17 @@ export class NonExistantGatewayIdentity extends SATPError { } export class GetStatusError extends SATPError { - constructor(sessionID: string, message: string, internalErrorId?: string, trace?: string) { - super(`Could not GetStatus at Session: with id ${sessionID}. Reason: ${message}`, 400, internalErrorId, trace); + constructor( + sessionID: string, + message: string, + internalErrorId?: string, + trace?: string, + ) { + super( + `Could not GetStatus at Session: with id ${sessionID}. Reason: ${message}`, + 400, + internalErrorId, + trace, + ); } } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/satp-session.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/satp-session.ts index 21259abbfe..3a8f316e0a 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/satp-session.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/satp-session.ts @@ -1,24 +1,24 @@ import { v4 as uuidv4 } from "uuid"; import { SessionData } from "../generated/proto/cacti/satp/v02/common/session_pb"; - +// Define interface on protos export interface ISATPSessionOptions { contextID: string; } export class SATPSession { - private static readonly CLASS_NAME = "SATPSession"; + public static readonly CLASS_NAME = "SATPSession"; private sessionData: SessionData; constructor(ops: ISATPSessionOptions) { this.sessionData = new SessionData(); this.sessionData.transferContextId = ops.contextID; this.sessionData.id = this.generateSessionID(); - } private generateSessionID(): string { - return this.sessionData.id = uuidv4() + "-" + this.sessionData.transferContextId; + return (this.sessionData.id = + uuidv4() + "-" + this.sessionData.transferContextId); } public getSessionData(): SessionData { diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage1-handler.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage1-handler.ts index 71e7089cc9..942acd3ff9 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage1-handler.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage1-handler.ts @@ -1,50 +1,92 @@ import { ConnectRouter, HandlerContext } from "@connectrpc/connect"; import { SatpStage1Service } from "../../generated/proto/cacti/satp/v02/stage_1_connect"; -import { TransferCommenceRequestMessage, TransferProposalRequestMessage } from "../../generated/proto/cacti/satp/v02/stage_1_pb"; +import { + TransferCommenceRequestMessage, + TransferCommenceResponseMessage, + TransferProposalReceiptMessage, + TransferProposalRequestMessage, +} from "../../generated/proto/cacti/satp/v02/stage_1_pb"; import { SATPSession } from "../satp-session"; import { Stage1ServerService } from "../stage-services/server/stage1-server-service"; import { Stage1ClientService } from "../stage-services/client/stage1-client-service"; -import { SupportedGatewayImplementations } from "../types"; -import { SATPHandler } from './SATPHandler'; // Assuming the interface is exported from this path +import { SupportedChain } from "../types"; +import { SATPHandler, SATPHandlerOptions } from "../../types/satp-protocol"; +import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; export class Stage1SATPHandler implements SATPHandler { - constructor( - private session: SATPSession | undefined, - private serverService: Stage1ServerService, - private clientService: Stage1ClientService, - private supportedDLTs: SupportedGatewayImplementations[] - ) {} + public static readonly CLASS_NAME = "Stage1SATPHandler"; + private session: SATPSession; + private serverService: Stage1ServerService; + private clientService: Stage1ClientService; + private supportedDLTs: SupportedChain[]; + private logger: Logger; - setupRouter(router: ConnectRouter): void { - router.service(SatpStage1Service, { - transferProposal: async (req: TransferProposalRequestMessage, context: HandlerContext) => { - try { - console.log("Received TransferProposalRequest", req, context); - const sessionData = await this.serverService.checkTransferProposalRequestMessage(req, this.session, this.supportedDLTs); - const message = await this.serverService.transferProposalResponse(req, this.session); - console.log("Returning response", message); - return message; - } catch (error) { - console.error("Error handling TransferProposalRequest:", error); - throw new Error("Failed to process TransferProposalRequest"); - } - }, - transferCommence: async (req: TransferCommenceRequestMessage, context: HandlerContext) => { - try { - console.log("Received TransferCommenceRequest", req, context); - const sessionData = await this.serverService.checkTransferCommenceRequestMessage(req, this.session); - const message = await this.serverService.transferCommenceResponse(req, this.session); - console.log("Returning response", message); - return message; - } catch (error) { - console.error("Error handling TransferCommenceRequest:", error); - throw new Error("Failed to process TransferCommenceRequest"); - } - } - }); + constructor(ops: SATPHandlerOptions) { + this.session = ops.session; + this.serverService = ops.serverService as Stage1ServerService; + this.clientService = ops.clientService as Stage1ClientService; + this.supportedDLTs = ops.supportedDLTs; + this.logger = LoggerProvider.getOrCreate(ops.loggerOptions); + this.logger.trace(`Initialized ${Stage1SATPHandler.CLASS_NAME}`); } getHandlerIdentifier(): string { - return "Stage1SATPHandler"; + return Stage1SATPHandler.CLASS_NAME; + } + + async TransferProposalImplementation( + req: TransferProposalRequestMessage, + ): Promise { + try { + console.log("Received TransferProposalRequest", req); + const sessionData = + await this.serverService.checkTransferProposalRequestMessage( + req, + this.session, + this.supportedDLTs, + ); + const message = await this.serverService.transferProposalResponse( + req, + this.session, + ); + console.log("message", message); + console.log("Returning response", sessionData); + const response = new TransferProposalReceiptMessage(); + return response; + } catch (error) { + console.error("Error handling TransferProposalRequest:", error); + throw new Error("Failed to process TransferProposalRequest"); + } + } + + async TransferCommenceImplementation( + req: TransferCommenceRequestMessage, + ): Promise { + try { + console.log("Received TransferCommenceRequest", req); + const sessionData = + await this.serverService.checkTransferCommenceRequestMessage( + req, + this.session, + ); + const message = await this.serverService.transferCommenceResponse( + req, + this.session, + ); + console.log("Returning response", message); + console.log("Returning response", sessionData); + const response = new TransferProposalReceiptMessage(); + return response; + } catch (error) { + console.error("Error handling TransferCommenceRequest:", error); + throw new Error("Failed to process TransferCommenceRequest"); + } + } + + setupRouter(router: ConnectRouter): void { + router.service(SatpStage1Service, { + transferProposal: this.TransferProposalImplementation, + transferCommence: this.TransferCommenceImplementation, + }); } } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage2-handler.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage2-handler.ts index e421fee9a6..9159b4eef2 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage2-handler.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage2-handler.ts @@ -1,3 +1,4 @@ +/* import { ConnectRouter, HandlerContext } from "@connectrpc/connect"; import { SatpStage2Service } from "../../generated/proto/cacti/satp/v02/stage_2_connect"; import { LockAssertionRequestMessage } from "../../generated/proto/cacti/satp/v02/stage_2_pb"; @@ -7,9 +8,15 @@ import { TimestampType, saveTimestamp } from "../session-utils"; import { MessageType } from "../../generated/proto/cacti/satp/v02/common/message_pb"; import { SATPSession } from "../satp-session"; import { ServiceType } from "@bufbuild/protobuf"; -import { SupportedGatewayImplementations } from "../types"; - -export const Stage2Handler = (session: SATPSession, service: Stage2ServerService, connectClients: ServiceType[], supportedDLTs: SupportedGatewayImplementations[]) => +import { SupportedChain } from "../types"; + +export const Stage2Handler = + ( + session: SATPSession, + service: Stage2ServerService, + connectClients: ServiceType[], + supportedDLTs: SupportedChain[], + ) => (router: ConnectRouter) => router.service(SatpStage2Service, { async lockAssertion( @@ -48,3 +55,4 @@ export const Stage2Handler = (session: SATPSession, service: Stage2ServerService return message; }, }); +*/ diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage3-handler.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage3-handler.ts index b5c91b4db0..d967e99a33 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage3-handler.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/stage3-handler.ts @@ -1,3 +1,4 @@ +/* import { ConnectRouter, HandlerContext } from "@connectrpc/connect"; import { SatpStage3Service } from "../../generated/proto/cacti/satp/v02/stage_3_connect"; import { @@ -11,9 +12,15 @@ import { SATPGateway } from "../../plugin-satp-hermes-gateway"; import { TimestampType, saveTimestamp } from "../session-utils"; import { MessageType } from "../../generated/proto/cacti/satp/v02/common/message_pb"; import { SATPSession } from "../satp-session"; -import { SupportedGatewayImplementations } from "../types"; - -export const Stage3Handler = (session: SATPSession, service: Stage3ServerService, connectClients: ServiceType[], supportedDLTs: SupportedGatewayImplementations[]) => +import { SupportedChain } from "../types"; + +export const Stage3Handler = + ( + session: SATPSession, + service: Stage3ServerService, + connectClients: ServiceType[], + supportedDLTs: SupportedChain[], + ) => (router: ConnectRouter) => router.service(SatpStage3Service, { async commitPreparation( @@ -108,3 +115,4 @@ export const Stage3Handler = (session: SATPSession, service: Stage3ServerService return new Empty({}); }, }); +*/ diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage1-client-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage1-client-service.ts index 105fd216e5..1d8b10cf26 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage1-client-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage1-client-service.ts @@ -1,5 +1,3 @@ -import { JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; import { TransferCommenceRequestMessage, TransferProposalRequestMessage, @@ -16,7 +14,6 @@ import { bufArray2HexStr, getHash, sign, - storeLog, verifySignature, } from "../../../gateway-utils"; import { @@ -25,50 +22,39 @@ import { saveSignature, checkSessionData, } from "../../session-utils"; -import { SupportedGatewayImplementations } from "../../types"; +import { SupportedChain } from "../../types"; import { SATPSession } from "../../../core/satp-session"; -import { SATPService, ISATPClientServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; - -export class Stage1ClientService implements SATPService { - public static readonly CLASS_NAME = "client-service"; - public static readonly SATP_STAGE = "stage-1"; - public static readonly SATP_SERVICE_TYPE = SATPServiceType.Client; - private _log: Logger; - private signer: JsObjectSigner; - - constructor(ops: ISATPClientServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage1ClientService.CLASS_NAME; - } - - public get stage(): string { - return Stage1ClientService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } +import { + SATPService, + SATPServiceType, + ISATPClientServiceOptions, + ISATPServiceOptions, +} from "../satp-service"; - public get serviceType(): SATPServiceType { - return SATPServiceType.Client; - } +export class Stage1ClientService extends SATPService { + public static readonly SATP_STAGE = "1"; + public static readonly SERVICE_TYPE = SATPServiceType.Client; - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; + constructor(ops: ISATPClientServiceOptions) { + // for now stage1serverservice does not have any different options than the SATPService class + + const commonOptions: ISATPServiceOptions = { + stage: Stage1ClientService.SATP_STAGE, + loggerOptions: ops.loggerOptions, + serviceName: ops.serviceName, + signer: ops.signer, + serviceType: Stage1ClientService.SERVICE_TYPE, + }; + super(commonOptions); } async transferProposalRequest( sessionID: string, session: SATPSession, - supportedDLTs: SupportedGatewayImplementations[], + supportedDLTs: SupportedChain[], ): Promise { - const fnTag = `${this.className}#transferProposalRequest()`; + const stepTag = `transferProposalRequest()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; const sessionData = session.getSessionData(); @@ -77,7 +63,9 @@ export class Stage1ClientService implements SATPService { } if ( - !supportedDLTs.includes(sessionData.senderGatewayNetworkId as SupportedGatewayImplementations) + !supportedDLTs.includes( + sessionData.senderGatewayNetworkId as SupportedChain, + ) ) { throw new Error( //todo change this to the transferClaims check `${fnTag}, recipient gateway dlt system is not supported by this gateway`, @@ -135,29 +123,29 @@ export class Stage1ClientService implements SATPService { networkCapabilities.accessControlProfile = sessionData.accessControlProfile; if (sessionData.permissions != undefined) { - this.log.info(`${fnTag}, Optional variable loaded: permissions...`); + this.Log.info(`${fnTag}, Optional variable loaded: permissions...`); networkCapabilities.permissions = sessionData.permissions; } if (sessionData.developerUrn != undefined) { - this.log.info(`${fnTag}, Optional variable loaded: developerUrn...`); + this.Log.info(`${fnTag}, Optional variable loaded: developerUrn...`); networkCapabilities.developerUrn = sessionData.developerUrn; } if (sessionData.applicationProfile != undefined) { - this.log.info( + this.Log.info( `${fnTag}, Optional variable loaded: applicationProfile...`, ); networkCapabilities.applicationProfile = sessionData.applicationProfile; } if (sessionData.subsequentCalls != undefined) { - this.log.info(`${fnTag}, Optional variable loaded: subsequentCalls...`); + this.Log.info(`${fnTag}, Optional variable loaded: subsequentCalls...`); networkCapabilities.subsequentCalls = sessionData.subsequentCalls; } if (sessionData.history != undefined) { - this.log.info(`${fnTag}, Optional variable loaded: history...`); + this.Log.info(`${fnTag}, Optional variable loaded: history...`); networkCapabilities.history = sessionData.history; } @@ -167,21 +155,21 @@ export class Stage1ClientService implements SATPService { transferProposalRequestMessage.networkCapabilities = networkCapabilities; if (sessionData.transferClaimsFormat != undefined) { - this.log.info( + this.Log.info( `${fnTag}, Optional variable loaded: transferInitClaimsFormat...`, ); transferProposalRequestMessage.transferInitClaimsFormat = sessionData.transferClaimsFormat; } if (sessionData.multipleCancelsAllowed != undefined) { - this.log.info( + this.Log.info( `${fnTag}, Optional variable loaded: multipleCancelsAllowed...`, ); transferProposalRequestMessage.multipleCancelsAllowed = sessionData.multipleCancelsAllowed; } if (sessionData.multipleClaimsAllowed != undefined) { - this.log.info( + this.Log.info( `${fnTag}, Optional variable loaded: multipleClaimsAllowed...`, ); transferProposalRequestMessage.multipleClaimsAllowed = @@ -189,10 +177,7 @@ export class Stage1ClientService implements SATPService { } const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(transferProposalRequestMessage), - ), + sign(this.Signer, JSON.stringify(transferProposalRequestMessage)), ); transferProposalRequestMessage.common.signature = messageSignature; @@ -213,7 +198,7 @@ export class Stage1ClientService implements SATPService { data: JSON.stringify(sessionData), }); */ - this.log.info(`${fnTag}, sending TransferProposalRequest...`); + this.Log.info(`${fnTag}, sending TransferProposalRequest...`); return transferProposalRequestMessage; } @@ -222,7 +207,8 @@ export class Stage1ClientService implements SATPService { response: TransferProposalReceiptMessage, session: SATPSession, ): Promise { - const fnTag = `${this.className}#transferCommenceRequest()`; + const stepTag = `transferCommenceRequest()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if (!response || !response.common) { throw new Error("Response or response.common is undefined"); @@ -259,10 +245,7 @@ export class Stage1ClientService implements SATPService { // transferCommenceRequestMessage.clientTransferNumber = sessionData.clientTransferNumber; const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(transferCommenceRequestMessage), - ), + sign(this.Signer, JSON.stringify(transferCommenceRequestMessage)), ); transferCommenceRequestMessage.common.signature = messageSignature; @@ -287,7 +270,7 @@ export class Stage1ClientService implements SATPService { data: JSON.stringify(sessionData), }); */ - this.log.info(`${fnTag}, sending TransferCommenceRequest...`); + this.Log.info(`${fnTag}, sending TransferCommenceRequest...`); return transferCommenceRequestMessage; } @@ -296,8 +279,8 @@ export class Stage1ClientService implements SATPService { response: TransferProposalReceiptMessage, session: SATPSession, ): Promise { - const fnTag = `${this.className}#checkTransferProposalReceiptMessage()`; - + const stepTag = `checkTransferProposalReceiptMessage()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if (response.common == undefined) { throw new Error(`${fnTag}, message has no satp common body`); } @@ -311,7 +294,7 @@ export class Stage1ClientService implements SATPService { throw new Error(`${fnTag}, satp common body is missing required fields`); } - const sessionId = response.common.sessionId; + // const sessionId = response.common.sessionId; const sessionData = session.getSessionData(); @@ -377,11 +360,7 @@ export class Stage1ClientService implements SATPService { } if ( - !verifySignature( - this.signer, - response, - sessionData.serverGatewayPubkey, - ) + !verifySignature(this.Signer, response, sessionData.serverGatewayPubkey) ) { throw new Error( `${fnTag}, TransferProposalReceipt message signature verification failed`, @@ -398,27 +377,29 @@ export class Stage1ClientService implements SATPService { response.common.messageType == MessageType.INIT_REJECT && response.transferCounterClaims != undefined ) { - if (this.checkProposedTransferClaims(response.transferCounterClaims)) { + if ( + await this.checkProposedTransferClaims(response.transferCounterClaims) + ) { sessionData.proposedTransferInitClaims = getHash( response.transferCounterClaims, ); return true; } else { - this.log.info( + this.Log.info( `TransferProposalReceipt proposedTransferClaims were rejected`, ); sessionData.completed = true; return false; } } - this.log.info(`TransferProposalReceipt passed all checks.`); + this.Log.info(`TransferProposalReceipt passed all checks.`); return true; } - private checkProposedTransferClaims( + async checkProposedTransferClaims( // eslint-disable-next-line @typescript-eslint/no-unused-vars counterTransfer: TransferClaims, - ): boolean { + ): Promise { //const fnTag = `${this.className}#checkCounterTransferClaims()`; //todo return true; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage2-client-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage2-client-service.ts index 56603fb305..9cbdce756e 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage2-client-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage2-client-service.ts @@ -1,226 +1,233 @@ -import { JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { TransferCommenceResponseMessage } from "../../../generated/proto/cacti/satp/v02/stage_1_pb"; -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; -import { SATP_VERSION } from "../../constants"; -import { - CommonSatp, - MessageType, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { LockAssertionRequestMessage } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; -import { - bufArray2HexStr, - getHash, - sign, - storeLog, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; -import { SATPSession } from "../../../core/satp-session"; -import { SATPService, ISATPClientServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; - -export class Stage2ClientService implements SATPService { - public static readonly CLASS_NAME = "client-service"; - public static readonly SATP_STAGE = "stage-2"; - public static readonly SATP_SERVICE_TYPE = SATPServiceType.Client; - - private _log: Logger; - private signer: JsObjectSigner; - - constructor(ops: ISATPClientServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage2ClientService.CLASS_NAME; - } - - public get stage(): string { - return Stage2ClientService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } - - public get serviceType(): SATPServiceType { - return SATPServiceType.Client; - } - - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; - } - - async lockAssertionRequest( - response: TransferCommenceResponseMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#lockAssertionRequest()`; - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.COMMIT_READY, getHash(response)); - - const commonBody = new CommonSatp(); - commonBody.version = sessionData.version; - commonBody.messageType = MessageType.LOCK_ASSERT; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.TRANSFER_COMMENCE_RESPONSE, - ); - - commonBody.sessionId = response.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const lockAssertionRequestMessage = new LockAssertionRequestMessage(); - lockAssertionRequestMessage.common = commonBody; - - lockAssertionRequestMessage.lockAssertionClaim = - sessionData.lockAssertionClaim; - lockAssertionRequestMessage.lockAssertionFormat = - sessionData.lockAssertionFormat; - - const messageSignature = bufArray2HexStr( - sign(this.signer, JSON.stringify(lockAssertionRequestMessage)), - ); - - lockAssertionRequestMessage.common.signature = messageSignature; - - saveSignature(sessionData, MessageType.LOCK_ASSERT, messageSignature); - - saveHash( - sessionData, - MessageType.LOCK_ASSERT, - getHash(lockAssertionRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "lockAssertionRequest", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - this.log.info(`${fnTag}, sending LockAssertionMessage...`); - - return lockAssertionRequestMessage; - } - - - checkTransferCommenceResponseMessage( - response: TransferCommenceResponseMessage, - session: SATPSession, - ): void { - const fnTag = `${this.className}#lockAssertionRequestMessage()`; - - if ( - response.common == undefined || - response.common.version == undefined || - response.common.messageType == undefined || - response.common.sessionId == undefined || - // request.common.transferContextId == undefined || - response.common.sequenceNumber == undefined || - response.common.resourceUrl == undefined || - // request.common.actionResponse == undefined || - // request.common.payloadProfile == undefined || - // request.common.applicationProfile == undefined || - response.common.signature == undefined || - response.common.clientGatewayPubkey == undefined || - response.common.serverGatewayPubkey == undefined - ) { - throw new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); - } - - if (response.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, unsupported SATP version`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - if ( - sessionData.serverGatewayPubkey == undefined || - sessionData.lastSequenceNumber == undefined - ) { - throw new Error(`${fnTag}, session data was not load correctly`); - } - - if ( - response.common.serverGatewayPubkey != sessionData.serverGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferCommenceResponse serverIdentity public key does not match the one that was sent`, - ); - } - - if ( - response.common.clientGatewayPubkey != sessionData.clientGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferCommenceResponse clientIdentity public key does not match the one that was sent`, - ); - } - - if ( - !verifySignature( - this.signer, - response.common, - response.common.serverGatewayPubkey, - ) - ) { - throw new Error( - `${fnTag}, TransferCommenceResponse message signature verification failed`, - ); - } - - if (response.common.messageType != MessageType.TRANSFER_COMMENCE_RESPONSE) { - throw new Error( - `${fnTag}, wrong message type for TransferCommenceResponse `, - ); - } - - if ( - response.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw new Error( - `${fnTag}, TransferCommenceResponse sequence number is wrong`, - ); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE) - ) { - throw new Error( - `${fnTag}, TransferCommenceResponse previous message hash does not match the one that was sent`, - ); - } - - this.log.info(`TransferCommenceResponse passed all checks.`); - } -} +// import { +// JsObjectSigner, +// Logger, +// LoggerProvider, +// } from "@hyperledger/cactus-common"; +// import { TransferCommenceResponseMessage } from "../../../generated/proto/cacti/satp/v02/stage_1_pb"; +// import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; +// import { SATP_VERSION } from "../../constants"; +// import { +// CommonSatp, +// MessageType, +// } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; +// import { LockAssertionRequestMessage } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; +// import { +// bufArray2HexStr, +// getHash, +// sign, +// storeLog, +// verifySignature, +// } from "../../../gateway-utils"; +// import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; +// import { SATPSession } from "../../../core/satp-session"; +// import { +// SATPService, +// ISATPClientServiceOptions, +// SATPServiceType, +// } from "../../../types/satp-protocol"; + +// export class Stage2ClientService implements SATPService { +// public static readonly CLASS_NAME = "client-service"; +// public static readonly SATP_STAGE = "stage-2"; +// public static readonly SATP_SERVICE_TYPE = SATPServiceType.Client; + +// private _log: Logger; +// private signer: JsObjectSigner; + +// constructor(ops: ISATPClientServiceOptions) { +// const level = ops.logLevel || "INFO"; +// const label = this.getServiceIdentifier(); +// this._log = LoggerProvider.getOrCreate({ level, label }); +// this.signer = ops.signer; +// } + +// public get className(): string { +// return Stage2ClientService.CLASS_NAME; +// } + +// public get stage(): string { +// return Stage2ClientService.SATP_STAGE; +// } + +// public get log(): Logger { +// return this._log; +// } + +// public get serviceType(): SATPServiceType { +// return SATPServiceType.Client; +// } + +// public getServiceIdentifier(): string { +// return `${this.className}#${this.serviceType}`; +// } + +// async lockAssertionRequest( +// response: TransferCommenceResponseMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#lockAssertionRequest()`; +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.COMMIT_READY, getHash(response)); + +// const commonBody = new CommonSatp(); +// commonBody.version = sessionData.version; +// commonBody.messageType = MessageType.LOCK_ASSERT; +// commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); + +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.TRANSFER_COMMENCE_RESPONSE, +// ); + +// commonBody.sessionId = response.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const lockAssertionRequestMessage = new LockAssertionRequestMessage(); +// lockAssertionRequestMessage.common = commonBody; + +// lockAssertionRequestMessage.lockAssertionClaim = +// sessionData.lockAssertionClaim; +// lockAssertionRequestMessage.lockAssertionFormat = +// sessionData.lockAssertionFormat; + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(lockAssertionRequestMessage)), +// ); + +// lockAssertionRequestMessage.common.signature = messageSignature; + +// saveSignature(sessionData, MessageType.LOCK_ASSERT, messageSignature); + +// saveHash( +// sessionData, +// MessageType.LOCK_ASSERT, +// getHash(lockAssertionRequestMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "lockAssertionRequest", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ +// this.log.info(`${fnTag}, sending LockAssertionMessage...`); + +// return lockAssertionRequestMessage; +// } + +// checkTransferCommenceResponseMessage( +// response: TransferCommenceResponseMessage, +// session: SATPSession, +// ): void { +// const fnTag = `${this.className}#lockAssertionRequestMessage()`; + +// if ( +// response.common == undefined || +// response.common.version == undefined || +// response.common.messageType == undefined || +// response.common.sessionId == undefined || +// // request.common.transferContextId == undefined || +// response.common.sequenceNumber == undefined || +// response.common.resourceUrl == undefined || +// // request.common.actionResponse == undefined || +// // request.common.payloadProfile == undefined || +// // request.common.applicationProfile == undefined || +// response.common.signature == undefined || +// response.common.clientGatewayPubkey == undefined || +// response.common.serverGatewayPubkey == undefined +// ) { +// throw new Error( +// `${fnTag}, message satp common body is missing or is missing required fields`, +// ); +// } + +// if (response.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, unsupported SATP version`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.serverGatewayPubkey == undefined || +// sessionData.lastSequenceNumber == undefined +// ) { +// throw new Error(`${fnTag}, session data was not load correctly`); +// } + +// if ( +// response.common.serverGatewayPubkey != sessionData.serverGatewayPubkey +// ) { +// throw new Error( +// `${fnTag}, TransferCommenceResponse serverIdentity public key does not match the one that was sent`, +// ); +// } + +// if ( +// response.common.clientGatewayPubkey != sessionData.clientGatewayPubkey +// ) { +// throw new Error( +// `${fnTag}, TransferCommenceResponse clientIdentity public key does not match the one that was sent`, +// ); +// } + +// if ( +// !verifySignature( +// this.signer, +// response.common, +// response.common.serverGatewayPubkey, +// ) +// ) { +// throw new Error( +// `${fnTag}, TransferCommenceResponse message signature verification failed`, +// ); +// } + +// if (response.common.messageType != MessageType.TRANSFER_COMMENCE_RESPONSE) { +// throw new Error( +// `${fnTag}, wrong message type for TransferCommenceResponse `, +// ); +// } + +// if ( +// response.common.sequenceNumber != +// sessionData.lastSequenceNumber + BigInt(1) +// ) { +// throw new Error( +// `${fnTag}, TransferCommenceResponse sequence number is wrong`, +// ); +// } + +// if ( +// response.common.hashPreviousMessage != +// getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE) +// ) { +// throw new Error( +// `${fnTag}, TransferCommenceResponse previous message hash does not match the one that was sent`, +// ); +// } + +// this.log.info(`TransferCommenceResponse passed all checks.`); +// } +// } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage3-client-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage3-client-service.ts index 8b6fdc41ca..e407e98d5e 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage3-client-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage3-client-service.ts @@ -1,517 +1,516 @@ -import { JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; -import { - CommonSatp, - MessageType, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SATP_VERSION } from "../../constants"; -import { - CommitFinalAcknowledgementReceiptResponseMessage, - CommitFinalAssertionRequestMessage, - CommitPreparationRequestMessage, - CommitReadyResponseMessage, - TransferCompleteRequestMessage, -} from "../../../generated/proto/cacti/satp/v02/stage_3_pb"; -import { - bufArray2HexStr, - getHash, - sign, - storeLog, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; -import { SATPService, ISATPClientServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; -import { SATPSession } from "../../satp-session"; -import { LockAssertionReceiptMessage } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; - -export class Stage3ClientService implements SATPService { - public static readonly CLASS_NAME = "client-service"; - public static readonly SATP_STAGE = "stage-3"; - public static readonly SATP_SERVICE_TYPE = SATPServiceType.Client; - - private _log: Logger; - private signer: JsObjectSigner; - - constructor(ops: ISATPClientServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage3ClientService.CLASS_NAME; - } - - public get stage(): string { - return Stage3ClientService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } - - public get serviceType(): SATPServiceType { - return SATPServiceType.Client; - } - - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; - } - - async commitPreparation( - response: LockAssertionReceiptMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#commitPreparation()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.ASSERTION_RECEIPT, getHash(response)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.COMMIT_PREPARE; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.ASSERTION_RECEIPT, - ); - commonBody.sessionId = response.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const commitPreparationRequestMessage = - new CommitPreparationRequestMessage(); - commitPreparationRequestMessage.common = commonBody; - - const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(commitPreparationRequestMessage), - ), - ); - - commitPreparationRequestMessage.common.signature = messageSignature; - - saveSignature(sessionData, MessageType.COMMIT_PREPARE, messageSignature); - - saveHash( - sessionData, - MessageType.COMMIT_PREPARE, - getHash(commitPreparationRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "commitPreparation", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - - this.log.info(`${fnTag}, sending CommitPreparationMessage...`); - - return commitPreparationRequestMessage; - } - - async commitFinalAssertion( - response: CommitReadyResponseMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#commitPreparation()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.COMMIT_READY, getHash(response)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.COMMIT_FINAL; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.COMMIT_READY, - ); - - commonBody.sessionId = response.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const commitFinalAssertionRequestMessage = - new CommitFinalAssertionRequestMessage(); - commitFinalAssertionRequestMessage.common = commonBody; - - commitFinalAssertionRequestMessage.burnAssertionClaim = - sessionData.burnAssertionClaim; - commitFinalAssertionRequestMessage.burnAssertionClaimFormat = - sessionData.burnAssertionClaimFormat; - - const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(commitFinalAssertionRequestMessage), - ), - ); - - commitFinalAssertionRequestMessage.common.signature = messageSignature; - - saveSignature(sessionData, MessageType.COMMIT_FINAL, messageSignature); - - saveHash( - sessionData, - MessageType.COMMIT_FINAL, - getHash(commitFinalAssertionRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "commitFinalAssertion", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - this.log.info(`${fnTag}, sending CommitFinalAssertionMessage...`); - - return commitFinalAssertionRequestMessage; - } - - async transferComplete( - response: CommitFinalAcknowledgementReceiptResponseMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#transferComplete()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.ACK_COMMIT_FINAL, getHash(response)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.COMMIT_TRANSFER_COMPLETE; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.ACK_COMMIT_FINAL, - ); - - commonBody.sessionId = response.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const transferCompleteRequestMessage = new TransferCompleteRequestMessage(); - transferCompleteRequestMessage.common = commonBody; - - transferCompleteRequestMessage.hashTransferCommence = getMessageHash( - sessionData, - MessageType.TRANSFER_COMMENCE_REQUEST, - ); - - const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(transferCompleteRequestMessage), - ), - ); - - transferCompleteRequestMessage.common.signature = messageSignature; - - saveSignature( - sessionData, - MessageType.COMMIT_TRANSFER_COMPLETE, - messageSignature, - ); - - saveHash( - sessionData, - MessageType.COMMIT_TRANSFER_COMPLETE, - getHash(transferCompleteRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "transferComplete", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - - this.log.info(`${fnTag}, sending TransferCompleteMessage...`); - - return transferCompleteRequestMessage; - } - - checkLockAssertionReceiptMessage( - response: LockAssertionReceiptMessage, - session: SATPSession, - ): void { - const fnTag = `${this.className}#checkLockAssertionReceiptMessage()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (response.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (response.common.messageType != MessageType.ASSERTION_RECEIPT) { - throw new Error(`${fnTag}, message type is not ASSERTION_RECEIPT`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.LOCK_ASSERT) - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - response.common, - response.common.serverGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - this.log.info(`LockAssertionReceiptMessage passed all checks.`); - } - - checkCommitReadyResponseMessage( - response: CommitReadyResponseMessage, - session: SATPSession, - ): void { - const fnTag = `${this.className}#checkCommitReadyResponseMessage()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (response.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (response.common.messageType != MessageType.COMMIT_READY) { - throw new Error(`${fnTag}, message type is not COMMIT_READY`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.COMMIT_PREPARE) - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - response.common, - response.common.serverGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - if (response.mintAssertionClaims == undefined) { - //todo - throw new Error(`${fnTag}, mintAssertionClaims is missing`); - } - - this.log.info(`CommitReadyResponseMessage passed all checks.`); - } - - checkCommitFinalAcknowledgementReceiptResponseMessage( - response: CommitFinalAcknowledgementReceiptResponseMessage, - session: SATPSession, - ): void { - const fnTag = `${this.className}#checkCommitFinalAcknowledgementReceiptResponseMessage()`; - - if (response.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (response.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (response.common.messageType != MessageType.ACK_COMMIT_FINAL) { - throw new Error(`${fnTag}, message type is not ACK_COMMIT_FINAL`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.COMMIT_FINAL) - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - response.common, - response.common.serverGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - if (response.assignmentAssertionClaim == undefined) { - throw new Error(`${fnTag}, assignmentAssertionClaim is missing`); - } - - this.log.info( - `CommitFinalAcknowledgementReceiptResponseMessage passed all checks.`, - ); - } -} +// import { +// JsObjectSigner, +// Logger, +// LoggerProvider, +// } from "@hyperledger/cactus-common"; +// import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; +// import { +// CommonSatp, +// MessageType, +// } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; +// import { SATP_VERSION } from "../../constants"; +// import { +// CommitFinalAcknowledgementReceiptResponseMessage, +// CommitFinalAssertionRequestMessage, +// CommitPreparationRequestMessage, +// CommitReadyResponseMessage, +// TransferCompleteRequestMessage, +// } from "../../../generated/proto/cacti/satp/v02/stage_3_pb"; +// import { +// bufArray2HexStr, +// getHash, +// sign, +// storeLog, +// verifySignature, +// } from "../../../gateway-utils"; +// import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; +// import { +// SATPService, +// ISATPClientServiceOptions, +// SATPServiceType, +// } from "../../../types/satp-protocol"; +// import { SATPSession } from "../../satp-session"; +// import { LockAssertionReceiptMessage } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; + +// export class Stage3ClientService implements SATPService { +// public static readonly CLASS_NAME = "client-service"; +// public static readonly SATP_STAGE = "stage-3"; +// public static readonly SATP_SERVICE_TYPE = SATPServiceType.Client; + +// private _log: Logger; +// private signer: JsObjectSigner; + +// constructor(ops: ISATPClientServiceOptions) { +// const level = ops.logLevel || "INFO"; +// const label = this.getServiceIdentifier(); +// this._log = LoggerProvider.getOrCreate({ level, label }); +// this.signer = ops.signer; +// } + +// public get className(): string { +// return Stage3ClientService.CLASS_NAME; +// } + +// public get stage(): string { +// return Stage3ClientService.SATP_STAGE; +// } + +// public get log(): Logger { +// return this._log; +// } + +// public get serviceType(): SATPServiceType { +// return SATPServiceType.Client; +// } + +// public getServiceIdentifier(): string { +// return `${this.className}#${this.serviceType}`; +// } + +// async commitPreparation( +// response: LockAssertionReceiptMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#commitPreparation()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.ASSERTION_RECEIPT, getHash(response)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.COMMIT_PREPARE; +// commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.ASSERTION_RECEIPT, +// ); +// commonBody.sessionId = response.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const commitPreparationRequestMessage = +// new CommitPreparationRequestMessage(); +// commitPreparationRequestMessage.common = commonBody; + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(commitPreparationRequestMessage)), +// ); + +// commitPreparationRequestMessage.common.signature = messageSignature; + +// saveSignature(sessionData, MessageType.COMMIT_PREPARE, messageSignature); + +// saveHash( +// sessionData, +// MessageType.COMMIT_PREPARE, +// getHash(commitPreparationRequestMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "commitPreparation", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ + +// this.log.info(`${fnTag}, sending CommitPreparationMessage...`); + +// return commitPreparationRequestMessage; +// } + +// async commitFinalAssertion( +// response: CommitReadyResponseMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#commitPreparation()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.COMMIT_READY, getHash(response)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.COMMIT_FINAL; +// commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); + +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.COMMIT_READY, +// ); + +// commonBody.sessionId = response.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const commitFinalAssertionRequestMessage = +// new CommitFinalAssertionRequestMessage(); +// commitFinalAssertionRequestMessage.common = commonBody; + +// commitFinalAssertionRequestMessage.burnAssertionClaim = +// sessionData.burnAssertionClaim; +// commitFinalAssertionRequestMessage.burnAssertionClaimFormat = +// sessionData.burnAssertionClaimFormat; + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(commitFinalAssertionRequestMessage)), +// ); + +// commitFinalAssertionRequestMessage.common.signature = messageSignature; + +// saveSignature(sessionData, MessageType.COMMIT_FINAL, messageSignature); + +// saveHash( +// sessionData, +// MessageType.COMMIT_FINAL, +// getHash(commitFinalAssertionRequestMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "commitFinalAssertion", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ +// this.log.info(`${fnTag}, sending CommitFinalAssertionMessage...`); + +// return commitFinalAssertionRequestMessage; +// } + +// async transferComplete( +// response: CommitFinalAcknowledgementReceiptResponseMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#transferComplete()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.ACK_COMMIT_FINAL, getHash(response)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.COMMIT_TRANSFER_COMPLETE; +// commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); + +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.ACK_COMMIT_FINAL, +// ); + +// commonBody.sessionId = response.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const transferCompleteRequestMessage = new TransferCompleteRequestMessage(); +// transferCompleteRequestMessage.common = commonBody; + +// transferCompleteRequestMessage.hashTransferCommence = getMessageHash( +// sessionData, +// MessageType.TRANSFER_COMMENCE_REQUEST, +// ); + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(transferCompleteRequestMessage)), +// ); + +// transferCompleteRequestMessage.common.signature = messageSignature; + +// saveSignature( +// sessionData, +// MessageType.COMMIT_TRANSFER_COMPLETE, +// messageSignature, +// ); + +// saveHash( +// sessionData, +// MessageType.COMMIT_TRANSFER_COMPLETE, +// getHash(transferCompleteRequestMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "transferComplete", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ + +// this.log.info(`${fnTag}, sending TransferCompleteMessage...`); + +// return transferCompleteRequestMessage; +// } + +// checkLockAssertionReceiptMessage( +// response: LockAssertionReceiptMessage, +// session: SATPSession, +// ): void { +// const fnTag = `${this.className}#checkLockAssertionReceiptMessage()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (response.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (response.common.messageType != MessageType.ASSERTION_RECEIPT) { +// throw new Error(`${fnTag}, message type is not ASSERTION_RECEIPT`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// response.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// response.common.hashPreviousMessage != +// getMessageHash(sessionData, MessageType.LOCK_ASSERT) +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if ( +// sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey +// ) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if ( +// sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey +// ) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// response.common, +// response.common.serverGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// this.log.info(`LockAssertionReceiptMessage passed all checks.`); +// } + +// checkCommitReadyResponseMessage( +// response: CommitReadyResponseMessage, +// session: SATPSession, +// ): void { +// const fnTag = `${this.className}#checkCommitReadyResponseMessage()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (response.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (response.common.messageType != MessageType.COMMIT_READY) { +// throw new Error(`${fnTag}, message type is not COMMIT_READY`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// response.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// response.common.hashPreviousMessage != +// getMessageHash(sessionData, MessageType.COMMIT_PREPARE) +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if ( +// sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey +// ) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if ( +// sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey +// ) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// response.common, +// response.common.serverGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// if (response.mintAssertionClaims == undefined) { +// //todo +// throw new Error(`${fnTag}, mintAssertionClaims is missing`); +// } + +// this.log.info(`CommitReadyResponseMessage passed all checks.`); +// } + +// checkCommitFinalAcknowledgementReceiptResponseMessage( +// response: CommitFinalAcknowledgementReceiptResponseMessage, +// session: SATPSession, +// ): void { +// const fnTag = `${this.className}#checkCommitFinalAcknowledgementReceiptResponseMessage()`; + +// if (response.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (response.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (response.common.messageType != MessageType.ACK_COMMIT_FINAL) { +// throw new Error(`${fnTag}, message type is not ACK_COMMIT_FINAL`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${response.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// response.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// response.common.hashPreviousMessage != +// getMessageHash(sessionData, MessageType.COMMIT_FINAL) +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if ( +// sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey +// ) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if ( +// sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey +// ) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// response.common, +// response.common.serverGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// if (response.assignmentAssertionClaim == undefined) { +// throw new Error(`${fnTag}, assignmentAssertionClaim is missing`); +// } + +// this.log.info( +// `CommitFinalAcknowledgementReceiptResponseMessage passed all checks.`, +// ); +// } +// } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/satp-bridge-manager.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/satp-bridge-manager.ts index 6bd6a18bab..16d6ca7673 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/satp-bridge-manager.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/satp-bridge-manager.ts @@ -1,7 +1,12 @@ // this file contains a class that encapsulates the logic for managing the SATP bridge (lock, unlock, etc). // should inject satp gateway session data (having parameters/chains for transactions), and processes smart contract output +import { SATPLedgerConnector } from "../../../types/blockchain-interaction"; + export abstract class SATPBridgeManager { + // Instantiate connectors based on supported implementations, at bridge level + private connectors: SATPLedgerConnector[] = []; + public abstract lockAsset( sessionId: string, assetId: string, diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-service.ts new file mode 100644 index 0000000000..b20d70fdac --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-service.ts @@ -0,0 +1,69 @@ +import { + JsObjectSigner, + Logger, + LoggerProvider, + ILoggerOptions, +} from "@hyperledger/cactus-common"; + +export enum SATPServiceType { + Server, + Client, +} + +export type ISATPServiceOptions = { + serviceName: string; + stage: "0" | "1" | "2" | "3"; + loggerOptions: ILoggerOptions; + signer: JsObjectSigner; + serviceType: SATPServiceType; +}; + +export type ISATPServerServiceOptions = ISATPServiceOptions; + +export type ISATPClientServiceOptions = ISATPServiceOptions; + +/** + * Interface for SATP Services. + * Each service implementing this interface must provide one or more function(s) to handle specific stages of the SATP protocol. + * Implementations should ensure compliance with the defined asynchronous patterns essential for SATP protocol interactions. + */ +export abstract class SATPService { + readonly stage: string; + readonly logger: Logger; + readonly serviceType: SATPServiceType; + private readonly signer: JsObjectSigner; + readonly serviceName: string; + + constructor(ops: ISATPServiceOptions) { + this.logger = LoggerProvider.getOrCreate(ops.loggerOptions); + this.serviceName = ops.serviceName; + this.serviceType = ops.serviceType; + this.stage = ops.stage; + this.signer = ops.signer; + this.logger.trace(`Signer logger level: ${this.signer.options.logLevel}`); + } + + public getServiceIdentifier(): string { + return `${this.serviceType}#${this.stage}`; + } + + public get Stage(): string { + return this.stage; + } + + public get Log(): Logger { + return this.logger; + } + + public get ServiceType(): SATPServiceType { + return this.serviceType; + } + + public get ServiceName(): string { + return this.serviceName; + } + + public get Signer(): JsObjectSigner { + return this.signer; + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage1-server-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage1-server-service.ts index 32e60eb722..e1237ed33b 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage1-server-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage1-server-service.ts @@ -1,6 +1,3 @@ -import { IJsObjectSignerOptions, JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; - -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; import { TransferCommenceResponseMessage, TransferCommenceRequestMessage, @@ -11,16 +8,12 @@ import { MessageType, CommonSatp, } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { - ACCEPTANCE, - SessionData, -} from "../../../generated/proto/cacti/satp/v02/common/session_pb"; +import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; import { SATP_VERSION } from "../../constants"; import { bufArray2HexStr, getHash, sign, - storeLog, verifySignature, } from "../../../gateway-utils"; import { TransferClaims } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; @@ -32,51 +25,38 @@ import { saveHash, saveSignature, } from "../../session-utils"; -import { SupportedGatewayImplementations } from "../../types"; +import { SupportedChain } from "../../types"; import { SATPSession } from "../../../core/satp-session"; -import { SATPService, ISATPServerServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; - -export class Stage1ServerService implements SATPService { - public static readonly CLASS_NAME = "server-service"; - public static readonly SATP_STAGE = "stage-1"; +import { + SATPService, + SATPServiceType, + ISATPServerServiceOptions, + ISATPServiceOptions, +} from "../satp-service"; + +export class Stage1ServerService extends SATPService { + public static readonly SATP_STAGE = "1"; public static readonly SERVICE_TYPE = SATPServiceType.Server; - private _log: Logger; - private signer: JsObjectSigner; - constructor(ops: ISATPServerServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage1ServerService.CLASS_NAME; - } - - public get stage(): string { - return Stage1ServerService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } - - - public get serviceType(): SATPServiceType { - return SATPServiceType.Server; - } - - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; + // for now stage1serverservice does not have any different options than the SATPService class + + const commonOptions: ISATPServiceOptions = { + stage: Stage1ServerService.SATP_STAGE, + loggerOptions: ops.loggerOptions, + serviceName: ops.serviceName, + signer: ops.signer, + serviceType: Stage1ServerService.SERVICE_TYPE, + }; + super(commonOptions); } async transferProposalResponse( request: TransferProposalRequestMessage, session: SATPSession | undefined, ): Promise { - const fnTag = `${this.className}#transferProposalResponse()`; + const stepTag = `transferProposalResponse()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if ( request.common == undefined || @@ -89,9 +69,7 @@ export class Stage1ServerService implements SATPService { } if (session == undefined) { - throw new Error( - `${fnTag}, session is undefined`, - ); + throw new Error(`${fnTag}, session is undefined`); } const sessionData = session.getSessionData(); @@ -131,8 +109,7 @@ export class Stage1ServerService implements SATPService { MessageType.INIT_PROPOSAL, ); - const transferProposalReceiptMessage = - new TransferProposalReceiptMessage(); + const transferProposalReceiptMessage = new TransferProposalReceiptMessage(); transferProposalReceiptMessage.common = commonBody; transferProposalReceiptMessage.hashTransferInitClaims = sessionData.hashTransferInitClaims; @@ -150,7 +127,7 @@ export class Stage1ServerService implements SATPService { ); if (!counterProposalTransferClaims) { - this.log.info(`${fnTag}, ProposalTransferClaims were rejected...`); + this.Log.info(`${fnTag}, ProposalTransferClaims were rejected...`); sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_REJECTED; } else { sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_CONDITIONAL; @@ -164,10 +141,7 @@ export class Stage1ServerService implements SATPService { */ const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(transferProposalReceiptMessage), - ), + sign(this.Signer, JSON.stringify(transferProposalReceiptMessage)), ); transferProposalReceiptMessage.common.signature = messageSignature; @@ -188,8 +162,8 @@ export class Stage1ServerService implements SATPService { operation: "lock", data: JSON.stringify(sessionData), }); - */ - this.log.info(`${fnTag}, sending TransferProposalResponseMessage...`); + */ + this.Log.info(`${fnTag}, sending TransferProposalResponseMessage...`); return transferProposalReceiptMessage; } @@ -198,7 +172,8 @@ export class Stage1ServerService implements SATPService { request: TransferCommenceRequestMessage, session: SATPSession | undefined, ): Promise { - const fnTag = `${this.className}#transferCommenceResponse()`; + const stepTag = `transferCommenceResponse()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if (request.common == undefined) { throw new Error( @@ -207,9 +182,7 @@ export class Stage1ServerService implements SATPService { } if (session == undefined) { - throw new Error( - `${fnTag}, session is undefined`, - ); + throw new Error(`${fnTag}, session is undefined`); } const sessionData = session.getSessionData(); @@ -245,10 +218,7 @@ export class Stage1ServerService implements SATPService { sessionData.lastSequenceNumber = commonBody.sequenceNumber; const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(transferCommenceResponseMessage), - ), + sign(this.Signer, JSON.stringify(transferCommenceResponseMessage)), ); transferCommenceResponseMessage.common.signature = messageSignature; @@ -273,8 +243,8 @@ export class Stage1ServerService implements SATPService { data: JSON.stringify(sessionData), }); */ - - this.log.info(`${fnTag}, sending TransferCommenceResponseMessage...`); + + this.Log.info(`${fnTag}, sending TransferCommenceResponseMessage...`); return transferCommenceResponseMessage; } @@ -282,9 +252,10 @@ export class Stage1ServerService implements SATPService { async checkTransferProposalRequestMessage( request: TransferProposalRequestMessage, session: SATPSession | undefined, - supportedDLTs: SupportedGatewayImplementations[], + supportedDLTs: SupportedChain[], ): Promise { - const fnTag = `${this.className}#checkTransferProposalRequestMessage()`; + const stepTag = `checkTransferProposalRequestMessage()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if ( request.common == undefined || @@ -312,7 +283,7 @@ export class Stage1ServerService implements SATPService { if ( !verifySignature( - this.signer, + this.Signer, request.common, request.common.clientGatewayPubkey, ) @@ -339,17 +310,16 @@ export class Stage1ServerService implements SATPService { `${fnTag}, TransferProposalRequest message does not contain network capabilities and parameters`, ); } - const senderId = request.transferInitClaims.senderGatewayNetworkId as SupportedGatewayImplementations; + const senderId = request.transferInitClaims + .senderGatewayNetworkId as SupportedChain; - if ( - !supportedDLTs.includes(senderId) - ) { + if (!supportedDLTs.includes(senderId)) { throw new Error( //todo change this to the transferClaims check `${fnTag}, recipient gateway dlt system is not supported by this gateway`, ); } - this.log.info(`TransferProposalRequest passed all checks.`); + this.Log.info(`TransferProposalRequest passed all checks.`); const sessionData = createSessionData( request.common.sessionId, @@ -371,8 +341,8 @@ export class Stage1ServerService implements SATPService { request.networkCapabilities.accessControlProfile, ); - this.log.info(`Session data created for session id ${sessionData.id}`); - if (!this.checkTransferClaims(request.transferInitClaims)) { + this.Log.info(`Session data created for session id ${sessionData.id}`); + if (!this.checkTransferClaims(request.transferInitClaims)) { throw new Error(); } return sessionData; @@ -382,7 +352,8 @@ export class Stage1ServerService implements SATPService { request: TransferCommenceRequestMessage, session: SATPSession | undefined, ): Promise { - const fnTag = `${this.className}#transferCommenceResponse()`; + const stepTag = `checkTransferCommenceRequestMessage()`; + const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; if ( request.common == undefined || @@ -409,9 +380,7 @@ export class Stage1ServerService implements SATPService { } if (session == undefined) { - throw new Error( - `${fnTag}, session is undefined`, - ); + throw new Error(`${fnTag}, session is undefined`); } const sessionData = session.getSessionData(); @@ -446,7 +415,7 @@ export class Stage1ServerService implements SATPService { if ( !verifySignature( - this.signer, + this.Signer, request.common, request.common.clientGatewayPubkey, ) @@ -490,18 +459,14 @@ export class Stage1ServerService implements SATPService { } if ( - !verifySignature( - this.signer, - request, - sessionData.clientGatewayPubkey, - ) + !verifySignature(this.Signer, request, sessionData.clientGatewayPubkey) ) { throw new Error( `${fnTag}, TransferCommenceRequest message signature verification failed`, ); } - this.log.info(`TransferCommenceRequest passed all checks.`); + this.Log.info(`TransferCommenceRequest passed all checks.`); return sessionData; } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage2-server-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage2-server-service.ts index 359ac37eff..702abebcdb 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage2-server-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage2-server-service.ts @@ -1,226 +1,234 @@ -import { JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { - LockAssertionReceiptMessage, - LockAssertionRequestMessage, -} from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; -import { SATP_VERSION } from "../../constants"; -import { - CommonSatp, - MessageType, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; -import { - bufArray2HexStr, - getHash, - sign, - storeLog, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; -import { SATPService, ISATPServerServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; -import { SATPSession } from "../../../core/satp-session"; -export class Stage2ServerService implements SATPService { - public static readonly CLASS_NAME = "server-service"; - public static readonly SATP_STAGE = "stage-2"; - public static readonly SERVICE_TYPE = SATPServiceType.Server; - - private _log: Logger; - private signer: JsObjectSigner; - - constructor(ops: ISATPServerServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage2ServerService.CLASS_NAME; - } - - public get stage(): string { - return Stage2ServerService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } - - public get serviceType(): SATPServiceType { - return SATPServiceType.Server; - } - - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; - } - - async lockAssertionResponse( - request: LockAssertionRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#lockAssertionResponse()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.LOCK_ASSERT, getHash(request)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.ASSERTION_RECEIPT; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.LOCK_ASSERT, - ); - commonBody.sessionId = request.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const lockAssertionReceiptMessage = new LockAssertionReceiptMessage(); - lockAssertionReceiptMessage.common = commonBody; - - const messageSignature = bufArray2HexStr( - sign(this.signer, JSON.stringify(lockAssertionReceiptMessage)), - ); - - lockAssertionReceiptMessage.common.signature = messageSignature; - - saveSignature(sessionData, MessageType.ASSERTION_RECEIPT, messageSignature); - - saveHash( - sessionData, - MessageType.ASSERTION_RECEIPT, - getHash(lockAssertionReceiptMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "lockAssertionResponse", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - - this.log.info(`${fnTag}, sending LockAssertionResponseMessage...`); - - return lockAssertionReceiptMessage; - } - - async checkLockAssertionRequestMessage( - request: LockAssertionRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#checkLockAssertionRequestMessage()`; - - if ( - request.common == undefined || - request.common.version == undefined || - request.common.messageType == undefined || - request.common.sessionId == undefined || - // request.common.transferContextId == undefined || - request.common.sequenceNumber == undefined || - request.common.resourceUrl == undefined || - // request.common.actionrequest == undefined || - // request.common.payloadProfile == undefined || - // request.common.applicationProfile == undefined || - request.common.signature == undefined || - request.common.clientGatewayPubkey == undefined || - request.common.serverGatewayPubkey == undefined - ) { - throw new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); - } - - if (request.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, unsupported SATP version`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - if ( - sessionData.serverGatewayPubkey == undefined || - sessionData.lastSequenceNumber == undefined - ) { - throw new Error(`${fnTag}, session data was not load correctly`); - } - - if (request.common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { - throw new Error( - `${fnTag}, LockAssertionRequest serverIdentity public key does not match the one that was sent`, - ); - } - - if (request.common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { - throw new Error( - `${fnTag}, LockAssertionRequest clientIdentity public key does not match the one that was sent`, - ); - } - - if ( - !verifySignature( - this.signer, - request.common, - request.common.serverGatewayPubkey, - ) - ) { - throw new Error( - `${fnTag}, LockAssertionRequest message signature verification failed`, - ); - } - - if (request.common.messageType != MessageType.LOCK_ASSERT) { - throw new Error(`${fnTag}, wrong message type for LockAssertionRequest`); - } - - if ( - request.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw new Error( - `${fnTag}, LockAssertionRequest Message sequence number is wrong`, - ); - } - - if ( - request.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE) - ) { - throw new Error( - `${fnTag}, LockAssertionRequest previous message hash does not match the one that was sent`, - ); - } - - if ( - request.lockAssertionFormat == undefined || - request.lockAssertionClaim == undefined - ) { - throw new Error( - `${fnTag}, LockAssertionRequest lockAssertionFormat or lockAssertionClaim is missing`, - ); - } - - this.log.info(`LockAssertionRequest passed all checks.`); - return sessionData; - } -} +// import { +// JsObjectSigner, +// Logger, +// LoggerProvider, +// } from "@hyperledger/cactus-common"; +// import { +// LockAssertionReceiptMessage, +// LockAssertionRequestMessage, +// } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; +// import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; +// import { SATP_VERSION } from "../../constants"; +// import { +// CommonSatp, +// MessageType, +// } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; +// import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; +// import { +// bufArray2HexStr, +// getHash, +// sign, +// storeLog, +// verifySignature, +// } from "../../../gateway-utils"; +// import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; +// import { +// SATPService, +// ISATPServerServiceOptions, +// SATPServiceType, +// } from "../../../types/satp-protocol"; +// import { SATPSession } from "../../../core/satp-session"; +// export class Stage2ServerService implements SATPService { +// public static readonly CLASS_NAME = "server-service"; +// public static readonly SATP_STAGE = "stage-2"; +// public static readonly SERVICE_TYPE = SATPServiceType.Server; + +// private _log: Logger; +// private signer: JsObjectSigner; + +// constructor(ops: ISATPServerServiceOptions) { +// const level = ops.logLevel || "INFO"; +// const label = this.getServiceIdentifier(); +// this._log = LoggerProvider.getOrCreate({ level, label }); +// this.signer = ops.signer; +// } + +// public get className(): string { +// return Stage2ServerService.CLASS_NAME; +// } + +// public get stage(): string { +// return Stage2ServerService.SATP_STAGE; +// } + +// public get log(): Logger { +// return this._log; +// } + +// public get serviceType(): SATPServiceType { +// return SATPServiceType.Server; +// } + +// public getServiceIdentifier(): string { +// return `${this.className}#${this.serviceType}`; +// } + +// async lockAssertionResponse( +// request: LockAssertionRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#lockAssertionResponse()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.LOCK_ASSERT, getHash(request)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.ASSERTION_RECEIPT; +// commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.LOCK_ASSERT, +// ); +// commonBody.sessionId = request.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const lockAssertionReceiptMessage = new LockAssertionReceiptMessage(); +// lockAssertionReceiptMessage.common = commonBody; + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(lockAssertionReceiptMessage)), +// ); + +// lockAssertionReceiptMessage.common.signature = messageSignature; + +// saveSignature(sessionData, MessageType.ASSERTION_RECEIPT, messageSignature); + +// saveHash( +// sessionData, +// MessageType.ASSERTION_RECEIPT, +// getHash(lockAssertionReceiptMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "lockAssertionResponse", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ + +// this.log.info(`${fnTag}, sending LockAssertionResponseMessage...`); + +// return lockAssertionReceiptMessage; +// } + +// async checkLockAssertionRequestMessage( +// request: LockAssertionRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#checkLockAssertionRequestMessage()`; + +// if ( +// request.common == undefined || +// request.common.version == undefined || +// request.common.messageType == undefined || +// request.common.sessionId == undefined || +// // request.common.transferContextId == undefined || +// request.common.sequenceNumber == undefined || +// request.common.resourceUrl == undefined || +// // request.common.actionrequest == undefined || +// // request.common.payloadProfile == undefined || +// // request.common.applicationProfile == undefined || +// request.common.signature == undefined || +// request.common.clientGatewayPubkey == undefined || +// request.common.serverGatewayPubkey == undefined +// ) { +// throw new Error( +// `${fnTag}, message satp common body is missing or is missing required fields`, +// ); +// } + +// if (request.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, unsupported SATP version`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.serverGatewayPubkey == undefined || +// sessionData.lastSequenceNumber == undefined +// ) { +// throw new Error(`${fnTag}, session data was not load correctly`); +// } + +// if (request.common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { +// throw new Error( +// `${fnTag}, LockAssertionRequest serverIdentity public key does not match the one that was sent`, +// ); +// } + +// if (request.common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { +// throw new Error( +// `${fnTag}, LockAssertionRequest clientIdentity public key does not match the one that was sent`, +// ); +// } + +// if ( +// !verifySignature( +// this.signer, +// request.common, +// request.common.serverGatewayPubkey, +// ) +// ) { +// throw new Error( +// `${fnTag}, LockAssertionRequest message signature verification failed`, +// ); +// } + +// if (request.common.messageType != MessageType.LOCK_ASSERT) { +// throw new Error(`${fnTag}, wrong message type for LockAssertionRequest`); +// } + +// if ( +// request.common.sequenceNumber != +// sessionData.lastSequenceNumber + BigInt(1) +// ) { +// throw new Error( +// `${fnTag}, LockAssertionRequest Message sequence number is wrong`, +// ); +// } + +// if ( +// request.common.hashPreviousMessage != +// getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE) +// ) { +// throw new Error( +// `${fnTag}, LockAssertionRequest previous message hash does not match the one that was sent`, +// ); +// } + +// if ( +// request.lockAssertionFormat == undefined || +// request.lockAssertionClaim == undefined +// ) { +// throw new Error( +// `${fnTag}, LockAssertionRequest lockAssertionFormat or lockAssertionClaim is missing`, +// ); +// } + +// this.log.info(`LockAssertionRequest passed all checks.`); +// return sessionData; +// } +// } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage3-server-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage3-server-service.ts index 4a1aca5121..24bedb08db 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage3-server-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage3-server-service.ts @@ -1,425 +1,433 @@ -import { JsObjectSigner, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; -import { - CommitFinalAcknowledgementReceiptResponseMessage, - CommitFinalAssertionRequestMessage, - CommitPreparationRequestMessage, - CommitReadyResponseMessage, -} from "../../../generated/proto/cacti/satp/v02/stage_3_pb"; -import { SATP_VERSION } from "../../constants"; -import { - CommonSatp, - MessageType, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; -import { - bufArray2HexStr, - getHash, - sign, - storeLog, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; -import { SATPService, ISATPServerServiceOptions, SATPServiceType } from "../../../types/satp-protocol"; -import { SATPSession } from "../../../core/satp-session"; - -export class Stage3ServerService implements SATPService { - public static readonly CLASS_NAME = "server-service"; - public static readonly SATP_STAGE = "stage-3"; - public static readonly SERVICE_TYPE = SATPServiceType.Server; - private _log: Logger; - private signer: JsObjectSigner; - - constructor(ops: ISATPServerServiceOptions) { - const level = ops.logLevel || "INFO"; - const label = this.getServiceIdentifier(); - this._log = LoggerProvider.getOrCreate({ level, label }); - this.signer = ops.signer; - } - - public get className(): string { - return Stage3ServerService.CLASS_NAME; - } - - public get stage(): string { - return Stage3ServerService.SATP_STAGE; - } - - public get log(): Logger { - return this._log; - } - - public get serviceType(): SATPServiceType { - return SATPServiceType.Server; - } - - public getServiceIdentifier(): string { - return `${this.className}#${this.serviceType}`; - } - - async commitReady( - request: CommitPreparationRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#commitReady()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.COMMIT_PREPARE, getHash(request)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.COMMIT_READY; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.COMMIT_PREPARE, - ); - commonBody.sessionId = request.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const commitReadyMessage = new CommitReadyResponseMessage(); - commitReadyMessage.common = commonBody; - - commitReadyMessage.mintAssertionClaims = sessionData.mintAssertionClaims; - commitReadyMessage.mintAssertionClaimsFormat = - sessionData.mintAssertionClaimsFormat; - - const messageSignature = bufArray2HexStr( - sign(this.signer, JSON.stringify(commitReadyMessage)), - ); - - saveSignature(sessionData, MessageType.COMMIT_READY, messageSignature); - - saveHash( - sessionData, - MessageType.COMMIT_READY, - getHash(commitReadyMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "commitReady", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - this.log.info(`${fnTag}, sending commitReadyMessage...`); - - return commitReadyMessage; - } - - async commitFinalAcknowledgementReceiptResponse( - request: CommitFinalAssertionRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#commitFinalAcknowledgementReceiptResponse()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, - ); - } - - saveHash(sessionData, MessageType.COMMIT_FINAL, getHash(request)); - - const commonBody = new CommonSatp(); - commonBody.version = SATP_VERSION; - commonBody.messageType = MessageType.ACK_COMMIT_FINAL; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.COMMIT_FINAL, - ); - commonBody.sessionId = request.common.sessionId; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const commitFinalAcknowledgementReceiptResponseMessage = - new CommitFinalAcknowledgementReceiptResponseMessage(); - commitFinalAcknowledgementReceiptResponseMessage.common = commonBody; - - commitFinalAcknowledgementReceiptResponseMessage.assignmentAssertionClaim = - sessionData.assignmentAssertionClaim; - commitFinalAcknowledgementReceiptResponseMessage.assignmentAssertionClaimFormat = - sessionData.assignmentAssertionClaimFormat; - - const messageSignature = bufArray2HexStr( - sign( - this.signer, - JSON.stringify(commitFinalAcknowledgementReceiptResponseMessage), - ), - ); - - saveSignature(sessionData, MessageType.ACK_COMMIT_FINAL, messageSignature); - - saveHash(sessionData, MessageType.ACK_COMMIT_FINAL, getHash(request)); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "commitFinalAcknowledgementReceiptResponse", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - this.log.info( - `${fnTag}, sending commitFinalAcknowledgementReceiptResponseMessage...`, - ); - - return commitFinalAcknowledgementReceiptResponseMessage; - } - - async checkCommitPreparationRequestMessage( - request: CommitPreparationRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#checkCommitPreparationRequestMessage()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (request.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (request.common.messageType != MessageType.COMMIT_PREPARE) { - throw new Error(`${fnTag}, message type is not COMMIT_PREPARE`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - getMessageHash(sessionData, MessageType.ASSERTION_RECEIPT) != - request.common.hashPreviousMessage - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - request.common, - request.common.clientGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - this.log.info(`CommitPreparationRequestMessage passed all checks.`); - - return sessionData; - } - - async checkCommitFinalAssertionRequestMessage( - request: CommitFinalAssertionRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#checkCommitFinalAssertionRequestMessage()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (request.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (request.common.messageType != MessageType.COMMIT_FINAL) { - throw new Error(`${fnTag}, message type is not COMMIT_FINAL`); - } - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - getMessageHash(sessionData, MessageType.COMMIT_READY) != - request.common.hashPreviousMessage - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - request.common, - request.common.clientGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - if (request.burnAssertionClaim == undefined) { - throw new Error(`${fnTag}, mintAssertionClaims is missing`); - } - - //todo check burn - - this.log.info(`CommitFinalAssertionRequestMessage passed all checks.`); - - return sessionData; - } - - async checkTransferCompleteRequestMessage( - request: CommitFinalAssertionRequestMessage, - session: SATPSession, - ): Promise { - const fnTag = `${this.className}#checkTransferCompleteRequestMessage()`; - - if (request.common == undefined) { - throw new Error(`${fnTag}, message common body is missing`); - } - - if (request.common.version != SATP_VERSION) { - throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); - } - - if (request.common.messageType != MessageType.COMMIT_TRANSFER_COMPLETE) { - throw new Error(`${fnTag}, message type is not COMMIT_TRANSFER_COMPLETE`); - } - - this.log.info( - `${fnTag}, TransferCompleteRequestMessage passed all checks.`, - ); - - const sessionData = session.getSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw new Error( - `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw new Error(`${fnTag}, sequenceNumber does not match`); - } - - if ( - getMessageHash(sessionData, MessageType.COMMIT_FINAL) != - request.common.hashPreviousMessage - ) { - throw new Error(`${fnTag}, hashPreviousMessage does not match`); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw new Error(`${fnTag}, clientGatewayPubkey does not match`); - } - - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw new Error(`${fnTag}, serverGatewayPubkey does not match`); - } - - if ( - !verifySignature( - this.signer, - request.common, - request.common.clientGatewayPubkey, - ) - ) { - throw new Error(`${fnTag}, message signature verification failed`); - } - - this.log.info( - `${fnTag}, TransferCompleteRequestMessage passed all checks.`, - ); - - return sessionData; - } -} +// import { +// JsObjectSigner, +// Logger, +// LoggerProvider, +// } from "@hyperledger/cactus-common"; +// import { SATPGateway } from "../../../plugin-satp-hermes-gateway"; +// import { +// CommitFinalAcknowledgementReceiptResponseMessage, +// CommitFinalAssertionRequestMessage, +// CommitPreparationRequestMessage, +// CommitReadyResponseMessage, +// } from "../../../generated/proto/cacti/satp/v02/stage_3_pb"; +// import { SATP_VERSION } from "../../constants"; +// import { +// CommonSatp, +// MessageType, +// } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; +// import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; +// import { +// bufArray2HexStr, +// getHash, +// sign, +// storeLog, +// verifySignature, +// } from "../../../gateway-utils"; +// import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; +// import { +// SATPService, +// ISATPServerServiceOptions, +// SATPServiceType, +// } from "../../../types/satp-protocol"; +// import { SATPSession } from "../../../core/satp-session"; + +// export class Stage3ServerService implements SATPService { +// public static readonly CLASS_NAME = "server-service"; +// public static readonly SATP_STAGE = "stage-3"; +// public static readonly SERVICE_TYPE = SATPServiceType.Server; +// private _log: Logger; +// private signer: JsObjectSigner; + +// constructor(ops: ISATPServerServiceOptions) { +// const level = ops.logLevel || "INFO"; +// const label = this.getServiceIdentifier(); +// this._log = LoggerProvider.getOrCreate({ level, label }); +// this.signer = ops.signer; +// } + +// public get className(): string { +// return Stage3ServerService.CLASS_NAME; +// } + +// public get stage(): string { +// return Stage3ServerService.SATP_STAGE; +// } + +// public get log(): Logger { +// return this._log; +// } + +// public get serviceType(): SATPServiceType { +// return SATPServiceType.Server; +// } + +// public getServiceIdentifier(): string { +// return `${this.className}#${this.serviceType}`; +// } + +// async commitReady( +// request: CommitPreparationRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#commitReady()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.COMMIT_PREPARE, getHash(request)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.COMMIT_READY; +// commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.COMMIT_PREPARE, +// ); +// commonBody.sessionId = request.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const commitReadyMessage = new CommitReadyResponseMessage(); +// commitReadyMessage.common = commonBody; + +// commitReadyMessage.mintAssertionClaims = sessionData.mintAssertionClaims; +// commitReadyMessage.mintAssertionClaimsFormat = +// sessionData.mintAssertionClaimsFormat; + +// const messageSignature = bufArray2HexStr( +// sign(this.signer, JSON.stringify(commitReadyMessage)), +// ); + +// saveSignature(sessionData, MessageType.COMMIT_READY, messageSignature); + +// saveHash( +// sessionData, +// MessageType.COMMIT_READY, +// getHash(commitReadyMessage), +// ); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "commitReady", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ +// this.log.info(`${fnTag}, sending commitReadyMessage...`); + +// return commitReadyMessage; +// } + +// async commitFinalAcknowledgementReceiptResponse( +// request: CommitFinalAssertionRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#commitFinalAcknowledgementReceiptResponse()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, +// ); +// } + +// saveHash(sessionData, MessageType.COMMIT_FINAL, getHash(request)); + +// const commonBody = new CommonSatp(); +// commonBody.version = SATP_VERSION; +// commonBody.messageType = MessageType.ACK_COMMIT_FINAL; +// commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); +// commonBody.hashPreviousMessage = getMessageHash( +// sessionData, +// MessageType.COMMIT_FINAL, +// ); +// commonBody.sessionId = request.common.sessionId; +// commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; +// commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + +// sessionData.lastSequenceNumber = commonBody.sequenceNumber; + +// const commitFinalAcknowledgementReceiptResponseMessage = +// new CommitFinalAcknowledgementReceiptResponseMessage(); +// commitFinalAcknowledgementReceiptResponseMessage.common = commonBody; + +// commitFinalAcknowledgementReceiptResponseMessage.assignmentAssertionClaim = +// sessionData.assignmentAssertionClaim; +// commitFinalAcknowledgementReceiptResponseMessage.assignmentAssertionClaimFormat = +// sessionData.assignmentAssertionClaimFormat; + +// const messageSignature = bufArray2HexStr( +// sign( +// this.signer, +// JSON.stringify(commitFinalAcknowledgementReceiptResponseMessage), +// ), +// ); + +// saveSignature(sessionData, MessageType.ACK_COMMIT_FINAL, messageSignature); + +// saveHash(sessionData, MessageType.ACK_COMMIT_FINAL, getHash(request)); + +// /* +// await storeLog(gateway, { +// sessionID: sessionData.id, +// type: "commitFinalAcknowledgementReceiptResponse", +// operation: "lock", +// data: JSON.stringify(sessionData), +// }); +// */ +// this.log.info( +// `${fnTag}, sending commitFinalAcknowledgementReceiptResponseMessage...`, +// ); + +// return commitFinalAcknowledgementReceiptResponseMessage; +// } + +// async checkCommitPreparationRequestMessage( +// request: CommitPreparationRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#checkCommitPreparationRequestMessage()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (request.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (request.common.messageType != MessageType.COMMIT_PREPARE) { +// throw new Error(`${fnTag}, message type is not COMMIT_PREPARE`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined || +// sessionData.signatures == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// request.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// getMessageHash(sessionData, MessageType.ASSERTION_RECEIPT) != +// request.common.hashPreviousMessage +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// request.common, +// request.common.clientGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// this.log.info(`CommitPreparationRequestMessage passed all checks.`); + +// return sessionData; +// } + +// async checkCommitFinalAssertionRequestMessage( +// request: CommitFinalAssertionRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#checkCommitFinalAssertionRequestMessage()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (request.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (request.common.messageType != MessageType.COMMIT_FINAL) { +// throw new Error(`${fnTag}, message type is not COMMIT_FINAL`); +// } + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined || +// sessionData.signatures == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// request.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// getMessageHash(sessionData, MessageType.COMMIT_READY) != +// request.common.hashPreviousMessage +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// request.common, +// request.common.clientGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// if (request.burnAssertionClaim == undefined) { +// throw new Error(`${fnTag}, mintAssertionClaims is missing`); +// } + +// //todo check burn + +// this.log.info(`CommitFinalAssertionRequestMessage passed all checks.`); + +// return sessionData; +// } + +// async checkTransferCompleteRequestMessage( +// request: CommitFinalAssertionRequestMessage, +// session: SATPSession, +// ): Promise { +// const fnTag = `${this.className}#checkTransferCompleteRequestMessage()`; + +// if (request.common == undefined) { +// throw new Error(`${fnTag}, message common body is missing`); +// } + +// if (request.common.version != SATP_VERSION) { +// throw new Error(`${fnTag}, message version is not ${SATP_VERSION}`); +// } + +// if (request.common.messageType != MessageType.COMMIT_TRANSFER_COMPLETE) { +// throw new Error(`${fnTag}, message type is not COMMIT_TRANSFER_COMPLETE`); +// } + +// this.log.info( +// `${fnTag}, TransferCompleteRequestMessage passed all checks.`, +// ); + +// const sessionData = session.getSessionData(); + +// if (sessionData == undefined) { +// throw new Error( +// `${fnTag}, session data not found for session id ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber == undefined || +// sessionData.version == undefined || +// sessionData.signatures == undefined +// ) { +// throw new Error( +// `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, +// ); +// } + +// if ( +// sessionData.lastSequenceNumber + BigInt(1) != +// request.common.sequenceNumber +// ) { +// throw new Error(`${fnTag}, sequenceNumber does not match`); +// } + +// if ( +// getMessageHash(sessionData, MessageType.COMMIT_FINAL) != +// request.common.hashPreviousMessage +// ) { +// throw new Error(`${fnTag}, hashPreviousMessage does not match`); +// } + +// if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { +// throw new Error(`${fnTag}, clientGatewayPubkey does not match`); +// } + +// if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { +// throw new Error(`${fnTag}, serverGatewayPubkey does not match`); +// } + +// if ( +// !verifySignature( +// this.signer, +// request.common, +// request.common.clientGatewayPubkey, +// ) +// ) { +// throw new Error(`${fnTag}, message signature verification failed`); +// } + +// this.log.info( +// `${fnTag}, TransferCompleteRequestMessage passed all checks.`, +// ); + +// return sessionData; +// } +// } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/types.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/types.ts index 0f7e2027ff..91f6a20937 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/types.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/types.ts @@ -3,8 +3,27 @@ import { ValidatorOptions } from "class-validator"; import { BLODispatcher } from "../blo/dispatcher"; import { ISignerKeyPairs } from "@hyperledger/cactus-common/src/main/typescript/signer-key-pairs"; import { createConnectTransport } from "@connectrpc/connect-node"; -import { SATPManager } from "../gol/protocol-manager/satp-manager"; +import { SATPManager } from "../gol/satp-manager"; import { SATPSession } from "./satp-session"; +import { SatpStage0Service } from "../generated/proto/cacti/satp/v02/stage_0_connect"; +import { SatpStage1Service } from "../generated/proto/cacti/satp/v02/stage_1_connect"; +import { SatpStage2Service } from "../generated/proto/cacti/satp/v02/stage_2_connect"; +import { SatpStage3Service } from "../generated/proto/cacti/satp/v02/stage_3_connect"; +import { ConnectRouter } from "@connectrpc/connect"; +import { SATPGateway } from "../plugin-satp-hermes-gateway"; +import { SATPService } from "../types/satp-protocol"; +import { PromiseClient as PromiseConnectClient } from "@connectrpc/connect"; + +export type SATPConnectHandler = ( + gateway: SATPGateway, + service: SATPService, +) => (router: ConnectRouter) => void; + +export type SATPServiceClient = + | typeof SatpStage0Service + | typeof SatpStage1Service + | typeof SatpStage2Service + | typeof SatpStage3Service; export enum CurrentDrafts { Core = "Core", @@ -25,7 +44,7 @@ export type ShutdownHook = { hook: () => Promise; }; -export enum SupportedGatewayImplementations { +export enum SupportedChain { FABRIC = "FabricSATPGateway", BESU = "BesuSATPGateway", } @@ -33,8 +52,9 @@ export enum SupportedGatewayImplementations { export type GatewayChannel = { fromGatewayID: string; toGatewayID: string; - manager: SATPManager; - sessions: Map; + sessions: Map; + supportedDLTs: SupportedChain[]; + clients: PromiseConnectClient[]; }; export type Address = @@ -46,7 +66,7 @@ export type GatewayIdentity = { id: string; name?: string; version: DraftVersions[]; - supportedChains: SupportedGatewayImplementations[]; + supportedDLTs: SupportedChain[]; proofID?: string; gatewayServerPort?: number; gatewayClientPort?: number; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/factory/plugin-factory-satp-hermes-bridge-manager.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/factory/plugin-factory-satp-hermes-bridge-manager.ts new file mode 100644 index 0000000000..70b786d12e --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/factory/plugin-factory-satp-hermes-bridge-manager.ts @@ -0,0 +1 @@ +// TODO diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway-utils.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway-utils.ts index 8b6bd2c6da..0c775ad781 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway-utils.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gateway-utils.ts @@ -73,7 +73,7 @@ export async function storeRemoteLog( key: string, hash: string, ) { - const fnTag = `${gateway.label}#storeInDatabase()`; + const fnTag = `${gateway.className}#storeInDatabase()`; const remoteLog: RemoteLog = { key: key, diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/gateway-orchestrator.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/gateway-orchestrator.ts index a713fc26d0..5dd70d9c1f 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/gateway-orchestrator.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/gateway-orchestrator.ts @@ -1,8 +1,21 @@ // a helper class to manage connections to counterparty gateways -import { ILoggerOptions, JsObjectSigner, LogLevelDesc, Logger, LoggerProvider } from "@hyperledger/cactus-common"; -import { GatewayIdentity, GatewayChannel, SupportedGatewayImplementations } from "../core/types"; -import { NonExistantGatewayIdentity } from "../core/errors"; -import { PromiseClient as PromiseConnectClient, Transport as ConnectTransport, PromiseClient } from "@connectrpc/connect"; +import { + ILoggerOptions, + JsObjectSigner, + LogLevelDesc, + Logger, + LoggerProvider, +} from "@hyperledger/cactus-common"; +import { + GatewayIdentity, + GatewayChannel, + SupportedChain, + SATPServiceClient, +} from "../core/types"; +import { + PromiseClient as PromiseConnectClient, + Transport as ConnectTransport, +} from "@connectrpc/connect"; import { SatpStage0Service } from "../generated/proto/cacti/satp/v02/stage_0_connect"; import { SatpStage1Service } from "../generated/proto/cacti/satp/v02/stage_1_connect"; @@ -11,44 +24,31 @@ import { SatpStage3Service } from "../generated/proto/cacti/satp/v02/stage_3_con export interface IGatewayOrchestratorOptions { logLevel?: LogLevelDesc; - ourGateway: GatewayIdentity; + localGateway: GatewayIdentity; counterPartyGateways: GatewayIdentity[] | undefined; signer: JsObjectSigner; } -import { - DEFAULT_PORT_GATEWAY_CLIENT, - DEFAULT_PORT_GATEWAY_GRPC, - DEFAULT_PORT_GATEWAY_SERVER, -} from "../core/constants"; - -import { BLODispatcher, BLODispatcherOptions } from "../blo/dispatcher"; //import { COREDispatcher, COREDispatcherOptions } from "../core/dispatcher"; -import express, { Express } from "express"; -import http from "http"; -import { SATPSession } from "../core/satp-session"; -import { SessionData } from "../generated/proto/cacti/satp/v02/common/session_pb"; -import { Transport, createPromiseClient } from "@connectrpc/connect"; +import { createPromiseClient } from "@connectrpc/connect"; import { createConnectTransport } from "@connectrpc/connect-node"; -import { ISATPManagerOptions, SATPManager, SATPServiceClient } from "./protocol-manager/satp-manager"; -import { log } from "console"; -import { getGatewaySeeds, resolveGatewayID } from "../network-identification/resolve-gateway"; -import { timingSafeEqual } from "crypto"; -import { ServiceType } from "@bufbuild/protobuf"; +import { + getGatewaySeeds, + resolveGatewayID, +} from "../network-identification/resolve-gateway"; export class GatewayOrchestrator { public readonly label = "GatewayOrchestrator"; - private ourGateway: GatewayIdentity; + protected localGateway: GatewayIdentity; private counterPartyGateways: Map = new Map(); + + // TODO!: add logic to manage sessions (parallelization, user input, freeze, unfreeze, rollback, recovery) private channels: Map = new Map(); private readonly logger: Logger; - private signer: JsObjectSigner; - constructor( - options: IGatewayOrchestratorOptions, - ) { + constructor(options: IGatewayOrchestratorOptions) { // add checks - this.ourGateway = options.ourGateway; + this.localGateway = options.localGateway; const level = options.logLevel || "INFO"; const logOptions: ILoggerOptions = { level: level, @@ -62,8 +62,9 @@ export class GatewayOrchestrator { this.logger.info( `Initializing gateway connection manager with ${seedGateways} seed gateways`, ); - this.signer = options.signer; - const allCounterPartyGateways = seedGateways.concat(options.counterPartyGateways ?? []); + const allCounterPartyGateways = seedGateways.concat( + options.counterPartyGateways ?? [], + ); // populate counterPartyGateways this.counterPartyGateways = new Map( allCounterPartyGateways.map((gateway) => [gateway.id, gateway]), @@ -73,7 +74,6 @@ export class GatewayOrchestrator { `Gateway Connection Manager bootstrapped with ${allCounterPartyGateways.length} gateways`, ); - this.addGateways(allCounterPartyGateways); const numberGatewayChannels = this.connectToCounterPartyGateways(); if (numberGatewayChannels > 0) { @@ -84,6 +84,9 @@ export class GatewayOrchestrator { } } + public get ourGateway(): GatewayIdentity { + return this.localGateway; + } async startupGatewayOrchestrator(): Promise { if (this.counterPartyGateways.values.length === 0) { this.logger.info("No gateways to connect to"); @@ -93,8 +96,11 @@ export class GatewayOrchestrator { } } + public getChannels(): Map { + return this.channels; + } isSelfId(id: string): boolean { - return id === this.ourGateway.id; + return id === this.localGateway.id; } isInCounterPartyGateways(id: string): boolean { @@ -107,17 +113,19 @@ export class GatewayOrchestrator { // Find IDs in counterPartyGateways that do not have a corresponding channel findUnchanneledGateways(): string[] { - return Array.from(this.counterPartyGateways.keys()).filter(id => { + return Array.from(this.counterPartyGateways.keys()).filter((id) => { return !this.isInChannels(id) && !this.isSelfId(id); }); } // Filter IDs that are not present in counterPartyGateways or channels and not the self ID filterNewIds(ids: string[]): string[] { - return ids.filter(id => { - return !this.isInCounterPartyGateways(id) && - !this.isInChannels(id) && - !this.isSelfId(id); + return ids.filter((id) => { + return ( + !this.isInCounterPartyGateways(id) && + !this.isInChannels(id) && + !this.isSelfId(id) + ); }); } @@ -128,21 +136,25 @@ export class GatewayOrchestrator { return 0; } - const idsToAdd = this.filterNewIds(Array.from(this.counterPartyGateways.keys())); + const idsToAdd = this.filterNewIds( + Array.from(this.counterPartyGateways.keys()), + ); if (idsToAdd.length === 0) { this.logger.info(`${fnTag}, No new gateways to connect to`); return 0; } - + // get gateway identtiies from counterPartyGateways - const gatewaysToAdd = idsToAdd.map(id => this.counterPartyGateways.get(id)!); + const gatewaysToAdd = idsToAdd.map( + (id) => this.counterPartyGateways.get(id)!, + ); let connected = 0; try { for (const gateway of gatewaysToAdd) { - const channel = this.createChannel(gateway); - this.channels.set(gateway.id, channel); - connected++; + const channel = this.createChannel(gateway); + this.channels.set(gateway.id, channel); + connected++; } } catch (ex) { this.logger.error(`${fnTag}, Failed to connect to gateway`); @@ -151,40 +163,40 @@ export class GatewayOrchestrator { return connected; } - get supportedDLTs(): SupportedGatewayImplementations[] { - return this.ourGateway.supportedChains; + get supportedDLTs(): SupportedChain[] { + return this.localGateway.supportedDLTs; } createChannel(identity: GatewayIdentity): GatewayChannel { const clients = this.createConnectClients(identity); - const SATPManagerOpts: ISATPManagerOptions = { - logLevel: "DEBUG", - instanceId: this.ourGateway!.id, - signer: this.signer, - supportedDLTs: this.supportedDLTs, - connectClients: clients, - }; - - const manager = new SATPManager(SATPManagerOpts); - const channel: GatewayChannel = { - fromGatewayID: this.ourGateway.id, - toGatewayID: identity.id, - manager: manager, + fromGatewayID: this.localGateway.id, + toGatewayID: identity.id, sessions: new Map(), + clients: clients, + supportedDLTs: identity.supportedDLTs, }; - return channel; } - private createConnectClients(identity: GatewayIdentity): PromiseConnectClient[] { - let createdClients: ServiceType[] = []; + protected getTargetChannel(id: string): GatewayChannel { + const channel = this.channels.get(id); + if (!channel) { + throw new Error(`Channel with gateway id ${id} does not exist`); + } else { + return channel; + } + } + + private createConnectClients( + identity: GatewayIdentity, + ): PromiseConnectClient[] { // one function for each client type; aggregate in array const transport = createConnectTransport({ baseUrl: identity.address + ":" + identity.gatewayGrpcPort, - httpVersion: "1.1" + httpVersion: "1.1", }); const stage0Client = this.createStage0ServiceClient(transport); @@ -192,39 +204,60 @@ export class GatewayOrchestrator { const stage2Client = this.createStage2ServiceClient(transport); const stage3Client = this.createStage3ServiceClient(transport); + // todo perform healthcheck on startup; should be in stage 0 return [stage0Client, stage1Client, stage2Client, stage3Client]; } - private createStage0ServiceClient(transport: ConnectTransport): PromiseConnectClient { - this.logger.debug("Creating stage 0 service client, with transport: ", transport); + private createStage0ServiceClient( + transport: ConnectTransport, + ): PromiseConnectClient { + this.logger.debug( + "Creating stage 0 service client, with transport: ", + transport, + ); const client = createPromiseClient(SatpStage0Service, transport); return client; } - private createStage1ServiceClient(transport: ConnectTransport): PromiseConnectClient { - this.logger.debug("Creating stage 1 service client, with transport: ", transport); + private createStage1ServiceClient( + transport: ConnectTransport, + ): PromiseConnectClient { + this.logger.debug( + "Creating stage 1 service client, with transport: ", + transport, + ); const client = createPromiseClient(SatpStage1Service, transport); return client; } - private createStage2ServiceClient(transport: ConnectTransport): PromiseConnectClient { - this.logger.debug("Creating stage 2 service client, with transport: ", transport); + private createStage2ServiceClient( + transport: ConnectTransport, + ): PromiseConnectClient { + this.logger.debug( + "Creating stage 2 service client, with transport: ", + transport, + ); const client = createPromiseClient(SatpStage2Service, transport); return client; } - private createStage3ServiceClient(transport: ConnectTransport): PromiseConnectClient { - this.logger.debug("Creating stage 3 service client, with transport: ", transport); + private createStage3ServiceClient( + transport: ConnectTransport, + ): PromiseConnectClient { + this.logger.debug( + "Creating stage 3 service client, with transport: ", + transport, + ); const client = createPromiseClient(SatpStage3Service, transport); return client; } - public async resolveAndAddGateways(IDs: string[]): Promise { + public async resolveAndAddGateways(IDs: string[]): Promise { const fnTag = `${this.label}#addGateways()`; this.logger.trace(`Entering ${fnTag}`); this.logger.info("Connecting to gateway"); const gatewaysToAdd: GatewayIdentity[] = []; - const thisID = this.ourGateway!.id; + const thisID = this.localGateway!.id; const otherIDs = IDs.filter((id) => id !== thisID); for (const id of otherIDs) { @@ -235,16 +268,20 @@ export class GatewayOrchestrator { return gatewaysToAdd.length; } - public addGateways(gateways: GatewayIdentity[]): string[] { + public addGateways(gateways: GatewayIdentity[]): string[] { const fnTag = `${this.label}#addGateways()`; this.logger.trace(`Entering ${fnTag}`); this.logger.info("Connecting to gateway"); - let addedIDs: string[] = []; + const addedIDs: string[] = []; // gateways tha are not self - const otherGateways = gateways.filter((gateway) => gateway.id !== this.ourGateway.id); + const otherGateways = gateways.filter( + (gateway) => gateway.id !== this.localGateway.id, + ); // gateways that are not already connected - const uniqueGateways = otherGateways.filter((gateway) => !this.counterPartyGateways.has(gateway.id)); + const uniqueGateways = otherGateways.filter( + (gateway) => !this.counterPartyGateways.has(gateway.id), + ); for (const gateway of uniqueGateways) { this.counterPartyGateways.set(gateway.id, gateway); @@ -275,18 +312,17 @@ export class GatewayOrchestrator { /* BOL TO GOL translation */ - async handleTransferRequest(): Promise { + async handleTransferRequest(): Promise { // add checks this.logger.info("Handling transfer request"); // ! todo implement transfer request this.logger.error("Not implemented"); } - async handleGetRoutes(): Promise { + async handleGetRoutes(): Promise { // add checks this.logger.info("Handling transfer request"); // ! todo implement transfer request this.logger.error("Not implemented"); } - } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/protocol-manager-builder.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/protocol-manager-builder.ts deleted file mode 100644 index b2cb2af53a..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/protocol-manager-builder.ts +++ /dev/null @@ -1,5 +0,0 @@ -interface ISATPManagerBuilder { - producePartA(): void; - producePartB(): void; - producePartC(): void; -} \ No newline at end of file diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/satp-manager.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/satp-manager.ts deleted file mode 100644 index ef756948e8..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/protocol-manager/satp-manager.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { - Checks, - JsObjectSigner, - LogLevelDesc, - Logger, - LoggerProvider, -} from "@hyperledger/cactus-common"; - -import { Stage1SATPHandler } from "../../core/stage-handlers/stage1-handler"; -import { Stage2Handler } from "../../core/stage-handlers/stage2-handler"; -import { Stage3Handler } from "../../core/stage-handlers/stage3-handler"; -import { Stage1ServerService } from "../../core/stage-services/server/stage1-server-service"; -import { SATPGateway } from "../../plugin-satp-hermes-gateway"; -import { Stage2ServerService } from "../../core/stage-services/server/stage2-server-service"; -import { Stage3ServerService } from "../../core/stage-services/server/stage3-server-service"; -import { ISATPSessionOptions, SATPSession } from "../../core/satp-session"; -import { ConnectRouter, createPromiseClient } from "@connectrpc/connect"; -import { ServiceType } from "@bufbuild/protobuf"; -import { SupportedGatewayImplementations } from "../../core/types"; -import { Stage1ClientService } from "../../core/stage-services/client/stage1-client-service"; -import { Stage2ClientService } from "../../core/stage-services/client/stage2-client-service"; -import { Stage3ClientService } from "../../core/stage-services/client/stage3-client-service"; -import { createConnectTransport } from "@connectrpc/connect-node"; -import { SATPService, ISATPServerServiceOptions, ISATPServiceOptions, SATPHandler, SATPServiceType } from "../../types/satp-protocol"; -import { SatpStage0Service } from "../../generated/proto/cacti/satp/v02/stage_0_connect"; -import { SatpStage1Service } from "../../generated/proto/cacti/satp/v02/stage_1_connect"; -import { SatpStage2Service } from "../../generated/proto/cacti/satp/v02/stage_2_connect"; -import { SatpStage3Service } from "../../generated/proto/cacti/satp/v02/stage_3_connect"; -import { PromiseClient as PromiseConnectClient, Transport as ConnectTransport, PromiseClient } from "@connectrpc/connect"; -import { Session } from "inspector"; - -export interface ISATPManagerOptions { - logLevel?: LogLevelDesc; - instanceId: string; - sessions?: Map; - signer: JsObjectSigner; - supportedDLTs: SupportedGatewayImplementations[]; - connectClients: PromiseConnectClient[]; -} - -type SATPConnectHandler = (gateway: SATPGateway, service: SATPService) => (router: ConnectRouter) => void; - -export type SATPServiceClient = typeof SatpStage0Service | typeof SatpStage1Service | typeof SatpStage2Service | typeof SatpStage3Service; - -export class SATPManager { - public static readonly CLASS_NAME = "SATPManager"; - private readonly logger: Logger; - private readonly instanceId: string; - private endpoints: any[] | undefined; - private signer: JsObjectSigner; - private connectClients: PromiseConnectClient[]; - public supportedDLTs: SupportedGatewayImplementations[] = []; - private sessions: Map; - - private readonly satpServices: SATPService[] = []; - private readonly satpHandlers: SATPHandler[] = []; - - constructor( - public readonly options: ISATPManagerOptions, - ) { - const fnTag = `${SATPManager.CLASS_NAME}#constructor()`; - Checks.truthy(options, `${fnTag} arg options`); - - const level = this.options.logLevel || "DEBUG"; - const label = this.className; - this.logger = LoggerProvider.getOrCreate({ level, label }); - this.instanceId = options.instanceId; - this.logger.info(`Instantiated ${this.className} OK`); - this.supportedDLTs = options.supportedDLTs; - this.signer = options.signer; - - this.sessions = options.sessions || new Map(); - - this.connectClients = options.connectClients; - if (this.connectClients == undefined || this.connectClients.length == 0) { - this.logger.warn("Connect clients not provided"); - } - - const serviceClasses = [Stage1ServerService, Stage2ServerService, Stage3ServerService, Stage1ClientService, Stage2ClientService, Stage3ClientService]; - const satpServiceOptions: ISATPServiceOptions = { signer: this.signer, logLevel: level }; - this.satpServices = serviceClasses.map(ServiceClass => new ServiceClass(satpServiceOptions)); - - let mockSession = this.getOrCreateSession() - const stage1Handler = new Stage1SATPHandler(mockSession, this.getServiceByStage(SATPServiceType.Server, "stage-1"), this.getServiceByStage(SATPServiceType.Client, "stage-1"), this.supportedDLTs); - stage1Handler.setupRouter(router); - - - } - - public getServiceByStage(serviceType: SATPServiceType, stageId: string): any { - return this.satpServices.find(service => - service.serviceType === serviceType && - service.stage === stageId - ); - } - - public get className(): string { - return SATPManager.CLASS_NAME; - } - - public getSessions(): Map | undefined { - return this.sessions; - } - - public getSession(sessionId: string): SATPSession | undefined { - if (this.sessions == undefined) { - return undefined; - } - return this.sessions.get(sessionId); - } - - get SupportedDLTs(): SupportedGatewayImplementations[] { - return this.supportedDLTs; - } - - public getOrCreateSession(sessionId?: string, contextID?: string): SATPSession { - let session: SATPSession; - if (!sessionId) { - return this.createNewSession(contextID || "MOCK_CONTEXT_ID"); - return session; - } else { - let existingSession = this.sessions.get(sessionId); - return existingSession || this.createNewSession("MOCK_CONTEXT_ID"); - } - } - - private createNewSession(contextID: string): SATPSession { - let session = new SATPSession({ contextID: contextID }); - this.sessions?.set(session.getSessionData().id, session); - return session - } - - getOrCreateServices() { - const fnTag = `${SATPManager.CLASS_NAME}#getOrCreateServices()`; - this.logger.info( - `${fnTag}, Registering gRPCservices on instanceId=${this.instanceId}`, - ); - if (Array.isArray(this.endpoints)) { - return this.endpoints; - } - - this.endpoints = this.satpHandlers; - return this.endpoints; - } - - get StageHandlers() { - throw new Error("Not implemented yet"); - } -} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/satp-manager.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/satp-manager.ts new file mode 100644 index 0000000000..543c4a2291 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/gol/satp-manager.ts @@ -0,0 +1,254 @@ +import { + Checks, + JsObjectSigner, + LogLevelDesc, + Logger, + LoggerProvider, +} from "@hyperledger/cactus-common"; + +import { Stage1SATPHandler } from "../core/stage-handlers/stage1-handler"; +import { Stage1ServerService } from "../core/stage-services/server/stage1-server-service"; +// import { Stage2ServerService } from "../core/stage-services/server/stage2-server-service"; +// import { Stage3ServerService } from "../core/stage-services/server/stage3-server-service"; +import { SATPSession } from "../core/satp-session"; +import { SupportedChain } from "../core/types"; +import { Stage1ClientService } from "../core/stage-services/client/stage1-client-service"; +// import { Stage2ClientService } from "../core/stage-services/client/stage2-client-service"; +// import { Stage3ClientService } from "../core/stage-services/client/stage3-client-service"; +import { + SATPService, + SATPHandler, + SATPServiceType, + SATPHandlerOptions, +} from "../types/satp-protocol"; +import { ISATPServiceOptions } from "../core/stage-services/satp-service"; + +export interface ISATPManagerOptions { + logLevel?: LogLevelDesc; + instanceId: string; + sessions?: Map; + signer: JsObjectSigner; + supportedDLTs: SupportedChain[]; +} + +export class SATPManager { + public static readonly CLASS_NAME = "SATPManager"; + private readonly logger: Logger; + private readonly instanceId: string; + private endpoints: any[] | undefined; + private signer: JsObjectSigner; + public supportedDLTs: SupportedChain[] = []; + private sessions: Map; + + private readonly satpServices: SATPService[] = []; + private readonly satpHandlers: SATPHandler[] = []; + + constructor(public readonly options: ISATPManagerOptions) { + const fnTag = `${SATPManager.CLASS_NAME}#constructor()`; + Checks.truthy(options, `${fnTag} arg options`); + + const level = this.options.logLevel || "DEBUG"; + const label = this.className; + this.logger = LoggerProvider.getOrCreate({ level, label }); + this.instanceId = options.instanceId; + this.logger.info(`Instantiated ${this.className} OK`); + this.supportedDLTs = options.supportedDLTs; + this.signer = options.signer; + + this.sessions = options.sessions || new Map(); + const handlersClasses = [ + Stage1SATPHandler, + // Stage2SATPHandler, + // Stage3SATPHandler, + ]; + + const serviceClasses = [Stage1ServerService, Stage1ClientService]; + + const serviceOptions = this.initializeServiceOptions( + serviceClasses, + level, + label, + ); + this.satpServices = this.initializeServices(serviceClasses, serviceOptions); + + const mockSession = this.getOrCreateSession(); + + if (serviceClasses.length % 2 !== 0) { + throw new Error( + "Invalid number of service classes. Each handler needs one server and one client service.", + ); + } + const handlersOptions = this.initializeHandlerOptions( + serviceClasses, + level, + ); + + const handlers = this.initializeHandlers(handlersClasses, handlersOptions); + this.satpHandlers = handlers; + } + + public getServiceByStage( + serviceType: SATPServiceType, + stageId: string, + ): SATPService { + if (isNaN(Number(stageId))) { + throw new Error("Invalid stageId"); + } + + const service = this.satpServices.find( + (service) => + service.serviceType === serviceType && service.stage === stageId, + ); + if (service == undefined) { + throw new Error( + `Service not found for stageId=${stageId} and serviceType=${serviceType}`, + ); + } + return service; + } + + public get className(): string { + return SATPManager.CLASS_NAME; + } + + public getSessions(): Map | undefined { + return this.sessions; + } + + public getSession(sessionId: string): SATPSession | undefined { + if (this.sessions == undefined) { + return undefined; + } + return this.sessions.get(sessionId); + } + + get SupportedDLTs(): SupportedChain[] { + return this.supportedDLTs; + } + + public getOrCreateSession( + sessionId?: string, + contextID?: string, + ): SATPSession { + let session: SATPSession; + if (!sessionId) { + return this.createNewSession(contextID || "MOCK_CONTEXT_ID"); + return session; + } else { + const existingSession = this.sessions.get(sessionId); + return existingSession || this.createNewSession("MOCK_CONTEXT_ID"); + } + } + + private createNewSession(contextID: string): SATPSession { + const session = new SATPSession({ contextID: contextID }); + this.sessions?.set(session.getSessionData().id, session); + return session; + } + + getOrCreateServices() { + const fnTag = `${SATPManager.CLASS_NAME}#getOrCreateServices()`; + this.logger.info( + `${fnTag}, Registering gRPCservices on instanceId=${this.instanceId}`, + ); + if (Array.isArray(this.endpoints)) { + return this.endpoints; + } + + this.endpoints = this.satpHandlers; + return this.endpoints; + } + + get StageHandlers() { + throw new Error("Not implemented yet"); + } + + private initializeServiceOptions( + serviceClasses: (new (options: ISATPServiceOptions) => SATPService)[], + logLevel: LogLevelDesc, + label: string, + ): ISATPServiceOptions[] { + return serviceClasses.map((_, index) => ({ + signer: this.signer, + stage: index.toString() as "0" | "1" | "2" | "3", + loggerOptions: { level: logLevel, label }, + serviceName: `Service-${index}`, + serviceType: + index % 2 === 0 ? SATPServiceType.Server : SATPServiceType.Client, + })); + } + + private initializeServices( + serviceClasses: (new (options: ISATPServiceOptions) => SATPService)[], + serviceOptions: ISATPServiceOptions[], + ): SATPService[] { + return serviceClasses.map( + (ServiceClass, index) => new ServiceClass(serviceOptions[index]), + ); + } + + private initializeHandlerOptions( + serviceClasses: (new (options: ISATPServiceOptions) => SATPService)[], + level: LogLevelDesc = "DEBUG", + ): SATPHandlerOptions[] { + const handlersOptions: SATPHandlerOptions[] = []; + const mockSession = this.getOrCreateSession(); + + try { + for (let i = 0; i < serviceClasses.length / 2; i++) { + const serverService = this.getServiceByStage( + SATPServiceType.Server, + i.toString(), + ); + + const clientService = this.getServiceByStage( + SATPServiceType.Client, + i.toString(), + ); + + const handlerOptions: SATPHandlerOptions = { + session: mockSession, + serverService: serverService, + clientService: clientService, + supportedDLTs: this.supportedDLTs, + loggerOptions: { level: level, label: `SATPHandler-Stage${i}` }, + }; + handlersOptions.push(handlerOptions); + } + } catch (error) { + this.logger.error(`Error creating handler options: ${error}`); + } + + return handlersOptions; + } + + private initializeHandlers( + handlersClasses: (new (options: SATPHandlerOptions) => SATPHandler)[], + handlersOptions: SATPHandlerOptions[], + ): SATPHandler[] { + const handlers: SATPHandler[] = []; + if (handlersClasses.length === 0) { + throw new Error("No handlers provided"); + } + + if (handlersOptions.length === 0) { + throw new Error("No handler options provided"); + } + + if (handlersClasses.length !== handlersOptions.length) { + throw new Error( + "Number of handler classes and options do not match. Each handler class needs an options object.", + ); + } + + handlersOptions.forEach((options, index) => { + if (index < handlersClasses.length) { + const HandlerClass = handlersClasses[index]; + const handler = new HandlerClass(options); + handlers.push(handler); + } + }); + + return handlers; + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/chainid-list.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/chainid-list.ts index dfcefb553b..6e2e644d2d 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/chainid-list.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/chainid-list.ts @@ -1 +1 @@ -// TODO implement network identification draft \ No newline at end of file +// TODO implement network identification draft diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/resolve-gateway.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/resolve-gateway.ts index ef715f1588..f7df2e1659 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/resolve-gateway.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/network-identification/resolve-gateway.ts @@ -1,95 +1,86 @@ -import { GatewayIdentity, SupportedGatewayImplementations } from "../core/types"; +import { GatewayIdentity, SupportedChain } from "../core/types"; import { Logger } from "@hyperledger/cactus-common"; // gets an ID, queries a repository, returns a gateway identity -export async function resolveGatewayID(logger: Logger, ID: string): Promise { - const fnTag = `#resolveGatewayID()`; - logger.trace(`Entering ${fnTag}`); - logger.info(`Resolving gateway with ID: ${ID}`); +export async function resolveGatewayID( + logger: Logger, + ID: string, +): Promise { + const fnTag = `#resolveGatewayID()`; + logger.trace(`Entering ${fnTag}`); + logger.info(`Resolving gateway with ID: ${ID}`); + + const mockGatewayIdentity: GatewayIdentity[] = [ + { + id: "1", + name: "Gateway1", + version: [ + { + Core: "1.0", + Architecture: "1.0", + Crash: "1.0", + }, + ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], + proofID: "mockProofID1", + gatewayServerPort: 3011, + address: "http://localhost", + }, + { + id: "2", + name: "Gateway2", + version: [ + { + Core: "1.0", + Architecture: "1.0", + Crash: "1.0", + }, + ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], + proofID: "mockProofID1", + gatewayServerPort: 3012, + address: "http://localhost", + }, + ]; + return mockGatewayIdentity.filter((gateway) => gateway.id === ID)[0]; +} - const mockGatewayIdentity: GatewayIdentity[] = [ - { - id: "1", - name: "Gateway1", - version: [ - { - Core: "1.0", - Architecture: "1.0", - Crash: "1.0", - }, - ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], - proofID: "mockProofID1", - gatewayServerPort: 3011, - address: "http://localhost", - }, - { - id: "2", - name: "Gateway2", - version: [ - { - Core: "1.0", - Architecture: "1.0", - Crash: "1.0", - }, - ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], - proofID: "mockProofID1", - gatewayServerPort: 3012, - address: "http://localhost", - }, - ]; - return mockGatewayIdentity.filter((gateway) => gateway.id === ID)[0]; - } - // TODO! dummy implementation for testing; contains hardcoded gateways similar to Bitcoin seeds -export function getGatewaySeeds(logger: Logger): GatewayIdentity[] { - const fnTag = `#getGatewaySeeds()`; - logger.trace(`Entering ${fnTag}`); +export function getGatewaySeeds(logger: Logger): GatewayIdentity[] { + const fnTag = `#getGatewaySeeds()`; + logger.trace(`Entering ${fnTag}`); - const mockGatewayIdentity: GatewayIdentity[] = [ - { - id: "1", - name: "Gateway1", - version: [ - { - Core: "1.0", - Architecture: "1.0", - Crash: "1.0", - }, - ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], - proofID: "mockProofID1", - gatewayServerPort: 3011, - address: "http://localhost", - }, - { - id: "2", - name: "Gateway2", - version: [ - { - Core: "1.0", - Architecture: "1.0", - Crash: "1.0", - }, - ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], - proofID: "mockProofID1", - gatewayServerPort: 3014, - address: "http://localhost", - }, - ]; - return mockGatewayIdentity; - } \ No newline at end of file + const mockGatewayIdentity: GatewayIdentity[] = [ + { + id: "1", + name: "Gateway1", + version: [ + { + Core: "1.0", + Architecture: "1.0", + Crash: "1.0", + }, + ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], + proofID: "mockProofID1", + gatewayServerPort: 3011, + address: "http://localhost", + }, + { + id: "2", + name: "Gateway2", + version: [ + { + Core: "1.0", + Architecture: "1.0", + Crash: "1.0", + }, + ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], + proofID: "mockProofID1", + gatewayServerPort: 3014, + address: "http://localhost", + }, + ]; + return mockGatewayIdentity; +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/plugin-satp-hermes-gateway.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/plugin-satp-hermes-gateway.ts index bd8e872919..d271213457 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/plugin-satp-hermes-gateway.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/plugin-satp-hermes-gateway.ts @@ -23,20 +23,19 @@ import { SATPGatewayConfig, GatewayIdentity, ShutdownHook, - SupportedGatewayImplementations, + SupportedChain, } from "./core/types"; -import { GatewayOrchestrator, IGatewayOrchestratorOptions } from "./gol/gateway-orchestrator"; +import { + GatewayOrchestrator, + IGatewayOrchestratorOptions, +} from "./gol/gateway-orchestrator"; export { SATPGatewayConfig }; import express, { Express } from "express"; import http from "http"; -import { configureRoutes } from "./web-services/router"; import { DEFAULT_PORT_GATEWAY_CLIENT, - DEFAULT_PORT_GATEWAY_GRPC, DEFAULT_PORT_GATEWAY_SERVER, } from "./core/constants"; -import { SessionData } from "./generated/proto/cacti/satp/v02/common/session_pb"; -import { expressConnectMiddleware } from "@connectrpc/connect-express"; import { bufArray2HexStr } from "./gateway-utils"; import { ILocalLogRepository, @@ -44,11 +43,16 @@ import { } from "./repository/interfaces/repository"; import { SATPLedgerConnector } from "./types/blockchain-interaction"; import { BLODispatcher, BLODispatcherOptions } from "./blo/dispatcher"; -import fs from 'fs'; -import swaggerUi from 'swagger-ui-express'; +import fs from "fs"; +import swaggerUi, { JsonObject } from "swagger-ui-express"; import { SATPSession } from "./core/satp-session"; +import { + IPluginWebService, + ICactusPlugin, + IWebServiceEndpoint, +} from "@hyperledger/cactus-core-api"; -export class SATPGateway { +export class SATPGateway implements IPluginWebService, ICactusPlugin { // todo more checks; example port from config is between 3000 and 9000 @IsDefined() @IsNotEmptyObject() @@ -58,45 +62,39 @@ export class SATPGateway { @IsDefined() @IsNotEmptyObject() @IsObject() - // todo add decorators that check all fields are defined private readonly config: SATPGatewayConfig; @IsString() @Contains("Gateway") - public readonly label = "SATPGateway"; + public readonly className = "SATPGateway"; - private readonly shutdownHooks: ShutdownHook[]; - private gatewayConnectionManager: GatewayOrchestrator; + @IsString() + public readonly instanceId: string; + private supportedDltIDs: SupportedChain[]; + private gatewayOrchestrator: GatewayOrchestrator; - private gatewayApplication?: Express; - private gatewayServer?: http.Server; private BLOApplication?: Express; private BLOServer?: http.Server; private BLODispatcher?: BLODispatcher; + private readonly OAS: JsonObject; public OAPIServerEnabled: boolean = false; - private objectSigner: JsObjectSigner; - - // Instantiate connectors based on supported implementations - private supportedDltIDs: SupportedGatewayImplementations[]; - private connectors: SATPLedgerConnector[] = []; - - // TODO!: add logic to manage sessions (parallelization, user input, freeze, unfreeze, rollback, recovery) - private sessions: Map = new Map(); + private signer: JsObjectSigner; private _pubKey: string; public localRepository?: ILocalLogRepository; public remoteRepository?: IRemoteLogRepository; + private readonly shutdownHooks: ShutdownHook[]; constructor(public readonly options: SATPGatewayConfig) { - const fnTag = `${this.label}#constructor()`; + const fnTag = `${this.className}#constructor()`; Checks.truthy(options, `${fnTag} arg options`); this.config = SATPGateway.ProcessGatewayCoordinatorConfig(options); this.shutdownHooks = []; const level = options.logLevel || "INFO"; const logOptions: ILoggerOptions = { level: level, - label: this.label, + label: this.className, }; this.logger = LoggerProvider.getOrCreate(logOptions); this.logger.info("Initializing Gateway Coordinator"); @@ -109,34 +107,40 @@ export class SATPGateway { this.logger.info(`Gateway's public key: ${this._pubKey}`); - const objectSignerOptions: IJsObjectSignerOptions = { + const signerOptions: IJsObjectSignerOptions = { privateKey: bufArray2HexStr(this.config.keyPair.privateKey), logLevel: "debug", }; - this.objectSigner = new JsObjectSigner(objectSignerOptions); + this.signer = new JsObjectSigner(signerOptions); const gatewayOrchestratorOptions: IGatewayOrchestratorOptions = { logLevel: this.config.logLevel, - ourGateway: this.config.gid!, + localGateway: this.config.gid!, counterPartyGateways: this.config.counterPartyGateways, - signer: this.objectSigner!, + signer: this.signer!, }; - if (this.config.gid) { - this.logger.info("Initializing gateway connection manager with seed gateways"); - this.gatewayConnectionManager = new GatewayOrchestrator(gatewayOrchestratorOptions); + if (this.config.gid) { + this.logger.info( + "Initializing gateway connection manager with seed gateways", + ); + this.gatewayOrchestrator = new GatewayOrchestrator( + gatewayOrchestratorOptions, + ); } else { throw new Error("GatewayIdentity is not defined"); } + this.instanceId = uuidv4(); const dispatcherOps: BLODispatcherOptions = { logger: this.logger, logLevel: this.config.logLevel, instanceId: this.config.gid!.id, + orchestrator: this.gatewayOrchestrator, + signer: this.signer, }; - - this.supportedDltIDs = this.config.gid!.supportedChains; + this.supportedDltIDs = this.config.gid!.supportedDLTs; if (!this.config.gid || !dispatcherOps.instanceId) { throw new Error("Invalid configuration"); @@ -144,50 +148,83 @@ export class SATPGateway { this.BLODispatcher = new BLODispatcher(dispatcherOps); this.OAPIServerEnabled = this.config.enableOpenAPI ?? true; + + const specPath = path.join(__dirname, "../json/openapi-blo-bundled.json"); + this.OAS = JSON.parse(fs.readFileSync(specPath, "utf8")); + if (!this.OAS) { + this.logger.warn("Error loading OAS"); + } + } + + /* ICactus Plugin methods */ + + public getInstanceId(): string { + return this.instanceId; + } + + public getPackageName(): string { + return `@hyperledger/cactus-plugin-satp-hermes`; + } + + public async onPluginInit(): Promise { + const fnTag = `${this.className}#onPluginInit()`; + this.logger.trace(`Entering ${fnTag}`); + // resolve gateways on init + throw new Error("Not implemented"); + } + + /* IPluginWebService methods */ + async registerWebServices(app: Express): Promise { + const webServices = await this.getOrCreateWebServices(); + webServices.forEach((ws) => { + this.logger.debug(`Registering service ${ws.getPath()}`); + ws.registerExpress(app); + }); + return webServices; + } + + public async getOrCreateWebServices(): Promise { + const fnTag = `${this.className}#getOrCreateWebServices()`; + this.logger.trace(`Entering ${fnTag}`); + if (!this.BLODispatcher) { + throw new Error(`Cannot ${fnTag} because BLODispatcher is erroneous`); + } + return this.BLODispatcher?.getOrCreateWebServices(); } + /* Getters */ + public get Signer(): JsObjectSigner { - return this.objectSigner; + return this.signer; } - + public getSupportedDltIDs(): string[] { return this.supportedDltIDs; } - public get gatewaySigner(): JsObjectSigner { - return this.objectSigner; + return this.signer; } public get pubKey(): string { return this._pubKey; } - // todo load docs for gateway coordinator and expose them in a http gatewayApplication - - setupOpenAPI(): void { - if (!this.OAPIServerEnabled) { - this.logger.debug("OpenAPI server is disabled"); - return; - } + public getOpenApiSpec(): unknown { + return this.OAS; + } - if (!this.BLOApplication) { - this.logger.debug("BLOApplication is not defined. Not initializing OpenAPI server"); - return; + // TODO: keep getter; add an admin endpoint to get identity of connected gateway to BLO + public get Identity(): GatewayIdentity { + const fnTag = `${this.className}#getIdentity()`; + this.logger.trace(`Entering ${fnTag}`); + if (!this.config.gid) { + throw new Error("GatewayIdentity is not defined"); } - - const specPath = path.join(__dirname, "../json/openapi-blo-bundled.json"); - const OpenAPISpec = JSON.parse(fs.readFileSync(specPath, 'utf8')); - - // Type assertion here - this.BLOApplication.use( - "/api-docs", - swaggerUi.serve as express.RequestHandler[], - swaggerUi.setup(OpenAPISpec) as express.RequestHandler - ); + return this.config.gid!; } - // use builder pattern? + /* Gateway configuration helpers */ static ProcessGatewayCoordinatorConfig( pluginOptions: SATPGatewayConfig, ): SATPGatewayConfig { @@ -207,10 +244,7 @@ export class SATPGateway { Crash: "v02", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID1", gatewayServerPort: DEFAULT_PORT_GATEWAY_SERVER, gatewayClientPort: DEFAULT_PORT_GATEWAY_CLIENT, @@ -235,10 +269,10 @@ export class SATPGateway { ]; } - if (!pluginOptions.gid.supportedChains) { - pluginOptions.gid.supportedChains = [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, + if (!pluginOptions.gid.supportedDLTs) { + pluginOptions.gid.supportedDLTs = [ + SupportedChain.FABRIC, + SupportedChain.BESU, ]; } @@ -276,24 +310,19 @@ export class SATPGateway { /** * Startup Methods * ---------------- - * This section includes methods responsible for starting up the server and its associated services. + * This section includes methods responsible for starting up the server and its associated services independently of the existance of a Hyperledger Cacti Node. * It ensures that both the GatewayServer and BLOServer are initiated concurrently for efficient launch. */ - async startup(): Promise { - const fnTag = `${this.label}#startup()`; + public async startup(): Promise { + const fnTag = `${this.className}#startup()`; this.logger.trace(`Entering ${fnTag}`); - await Promise.all([ - this.startupGatewayServer(), - this.setupOpenAPI(), - ]); - - this.logger.info("Both GatewayServer and BLOServer have started"); + await Promise.all([this.startupBLOServer(), this.setupOpenAPIServer()]); } - async startupGatewayServer(): Promise { + protected async startupBLOServer(): Promise { // starts BOL - const fnTag = `${this.label}#startupGatewayServer()`; + const fnTag = `${this.className}#startupBLOServer()`; this.logger.trace(`Entering ${fnTag}`); this.logger.info("Starting BOL server"); const port = @@ -333,6 +362,29 @@ export class SATPGateway { }); } + public setupOpenAPIServer(): void { + if (!this.OAPIServerEnabled) { + this.logger.debug("OpenAPI server is disabled"); + return; + } + + if (!this.BLOApplication) { + this.logger.debug( + "BLOApplication is not defined. Not initializing OpenAPI server", + ); + return; + } + + if (!this.OAS) { + throw new Error("OpenAPI spec is not set"); + } + // Type assertion here + this.BLOApplication.use( + "/api-docs", + swaggerUi.serve as express.RequestHandler[], + swaggerUi.setup(this.OAS) as express.RequestHandler, + ); + } /** * Gateway Connection Methods * -------------------------- @@ -343,53 +395,39 @@ export class SATPGateway { // TODO: addGateways as an admin endpoint, simply calls orchestrator public async resolveAndAddGateways(IDs: string[]): Promise { - const fnTag = `${this.label}#resolveAndAddGateways()`; + const fnTag = `${this.className}#resolveAndAddGateways()`; this.logger.trace(`Entering ${fnTag}`); this.logger.info("Connecting to gateway"); - this.gatewayConnectionManager.resolveAndAddGateways(IDs); + this.gatewayOrchestrator.resolveAndAddGateways(IDs); // todo connect to gateway } public async addGateways(gateways: GatewayIdentity[]): Promise { - const fnTag = `${this.label}#addGateways()`; + const fnTag = `${this.className}#addGateways()`; this.logger.trace(`Entering ${fnTag}`); this.logger.info("Connecting to gateway"); - this.gatewayConnectionManager.addGateways(gateways); + this.gatewayOrchestrator.addGateways(gateways); // todo connect to gateway } - - // TODO: keep getter; add an admin endpoint to get identity of connected gateway to BLO - public get Identity(): GatewayIdentity { - const fnTag = `${this.label}#getIdentity()`; - this.logger.trace(`Entering ${fnTag}`); - if (!this.config.gid) { - throw new Error("GatewayIdentity is not defined"); - } - return this.config.gid!; - } - /** * Shutdown Methods * ----------------- * This section includes methods responsible for cleanly shutting down the server and its associated services. */ public onShutdown(hook: ShutdownHook): void { - const fnTag = `${this.label}#onShutdown()`; + const fnTag = `${this.className}#onShutdown()`; this.logger.trace(`Entering ${fnTag}`); this.logger.debug(`Adding shutdown hook: ${hook.name}`); this.shutdownHooks.push(hook); } - public async shutdown(): Promise { - const fnTag = `${this.label}#getGatewaySeeds()`; + public async shutdown(): Promise { + const fnTag = `${this.className}#getGatewaySeeds()`; this.logger.debug(`Entering ${fnTag}`); - this.logger.info("Shutting down Node server - Gateway"); - await this.shutdownGatewayServer(); - this.logger.info("Shutting down Node server - BOL"); await this.shutdownBLOServer(); @@ -400,34 +438,15 @@ export class SATPGateway { } this.logger.info("Shutting down Gateway Connection Manager"); - const connectionsClosed = - await this.gatewayConnectionManager.disconnectAll(); + const connectionsClosed = await this.gatewayOrchestrator.disconnectAll(); this.logger.info(`Closed ${connectionsClosed} connections`); this.logger.info("Gateway Coordinator shut down"); - return connectionsClosed; - } - - private async shutdownGatewayServer(): Promise { - const fnTag = `${this.label}#shutdownServer()`; - this.logger.debug(`Entering ${fnTag}`); - if (this.gatewayServer) { - try { - await this.gatewayServer.close(); - this.gatewayServer = undefined; - this.logger.info("Server shut down"); - } catch (error) { - this.logger.error( - `Error shutting down the gatewayApplication: ${error}`, - ); - } - } else { - this.logger.warn("Server is not running."); - } + return; } private async shutdownBLOServer(): Promise { - const fnTag = `${this.label}#shutdownBLOServer()`; + const fnTag = `${this.className}#shutdownBLOServer()`; this.logger.debug(`Entering ${fnTag}`); if (this.BLOServer) { try { @@ -443,5 +462,4 @@ export class SATPGateway { this.logger.warn("Server is not running."); } } - } 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 e491e34574..df70e959f4 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 @@ -1,7 +1,8 @@ // Gateway Client API export * from "./generated/gateway-client/typescript-axios"; -// Gateway Backend, not exported for now +// TODO: Should we export the gateway backend +// Gateway Backend /* // Exporting from the common directory export * from './generated/proto/cacti/satp/v02/common/health_connect'; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/types/satp-protocol.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/types/satp-protocol.ts index e8a63c3d25..cab98da467 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/types/satp-protocol.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/types/satp-protocol.ts @@ -1,46 +1,32 @@ -import { JsObjectSigner, LogLevelDesc, Logger } from "@hyperledger/cactus-common"; -import { SupportedGatewayImplementations } from "../core/types"; -import { SessionData } from "../generated/proto/cacti/satp/v02/common/session_pb"; -import { v4 as uuidV4 } from "uuid"; +import { + ILoggerOptions, + JsObjectSigner, + LogLevelDesc, + Logger, +} from "@hyperledger/cactus-common"; +import { SupportedChain } from "../core/types"; import { ConnectRouter } from "@connectrpc/connect"; - -/** - * Interface for SATP Services. - * Each service implementing this interface must provide one or more function(s) to handle specific stages of the SATP protocol. - * Implementations should ensure compliance with the defined asynchronous patterns essential for SATP protocol interactions. - */ -export interface SATPService { - readonly className: string; - readonly stage: string; - readonly log: Logger; - readonly serviceType: SATPServiceType; - getServiceIdentifier(): string; -} +import { SATPSession } from "../core/satp-session"; +import { + SATPService, + SATPServiceType, +} from "../core/stage-services/satp-service"; /** * Represents a handler for various stages of the SATP (Secure Asset Transfer Protocol). * Handlers implementing this interface must provide mechanisms to setup routes and handle * protocol-specific requests based on the stage they are designed for. - */ + */ export interface SATPHandler { setupRouter(router: ConnectRouter): void; getHandlerIdentifier(): string; } -export enum SATPServiceType { - Server, - Client, -} - -export type ISATPServiceOptions = { - logLevel: LogLevelDesc - signer: JsObjectSigner; -} - -export type ISATPServerServiceOptions = ISATPServiceOptions & { - -} - -export type ISATPClientServiceOptions = ISATPServiceOptions & { - +export interface SATPHandlerOptions { + session: SATPSession; + serverService: SATPService; + clientService: SATPService; + supportedDLTs: SupportedChain[]; + loggerOptions: ILoggerOptions; } +export { SATPService, SATPServiceType }; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/router.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/router.ts deleted file mode 100644 index 7922d8c4e8..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/router.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ConnectRouter } from "@connectrpc/connect"; - -/* -import { TestService } from "../generated/proto/test/message_connect"; -import { TestService2 } from "../generated/proto/test/message_connect"; - -import { TestImplementation } from "./test/test"; -import { TestImplementation2 } from "./test/test2"; - - -*/ -export const configureRoutes = (router: ConnectRouter): void => { - console.log(router); - // TODO: add all services and respective implementations - //router.service(TestService, TestImplementation); -}; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/stage-0/dummy-step.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/stage-0/dummy-step.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/stage-0/identity-verification.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/stage-0/identity-verification.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/blo/status-endpoint.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/status-endpoint.ts similarity index 90% rename from packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/blo/status-endpoint.ts rename to packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/status-endpoint.ts index 40bb86d859..e93d8a639c 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/blo/status-endpoint.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/web-services/status-endpoint.ts @@ -14,9 +14,9 @@ import { import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; -import OAS from "../../../json/openapi-blo-bundled.json"; -import { IRequestOptions } from "../../core/types"; -import { StatusRequest } from "../../generated/gateway-client/typescript-axios"; +import OAS from "../../json/openapi-blo-bundled.json"; +import { IRequestOptions } from "../core/types"; +import { StatusRequest } from "../generated/gateway-client/typescript-axios"; export class GetStatusEndpointV1 implements IWebServiceEndpoint { public static readonly CLASS_NAME = "GetStatusEndpointV1"; @@ -75,6 +75,8 @@ export class GetStatusEndpointV1 implements IWebServiceEndpoint { return this.handleRequest.bind(this); } + // TODO discover way to inherit OAS schema and have request types here + // parameter checks should be enforced by the type system public async handleRequest(req: Request, res: Response): Promise { const reqTag = `${this.getVerbLowerCase()} - ${this.getPath()}`; this.log.debug(reqTag); diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-blo-get-status.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-blo-get-status.test.ts index e7b4b9f447..a3404a7b10 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-blo-get-status.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-blo-get-status.test.ts @@ -12,7 +12,7 @@ import { import { SATPGatewayConfig, - SupportedGatewayImplementations, + SupportedChain, } from "../../../main/typescript/core/types"; import { createClient } from "../test-utils"; @@ -52,10 +52,7 @@ describe("GetStatus Endpoint and Functionality testing", () => { Crash: "v1", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", gatewayServerPort: 3010, gatewayClientPort: 3011, diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-init-startup.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-init-startup.test.ts index c5997c9e10..b4b9b8355c 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-init-startup.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/integration/gateway-init-startup.test.ts @@ -16,7 +16,7 @@ import { } from "@hyperledger/cactus-core-api"; import { ShutdownHook, - SupportedGatewayImplementations, + SupportedChain, } from "./../../../main/typescript/core/types"; const logLevel: LogLevelDesc = "INFO"; @@ -58,9 +58,9 @@ describe("SATPGateway initialization", () => { Crash: "v02", }, ]); - expect(identity.supportedChains).toEqual([ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, + expect(identity.supportedDLTs).toEqual([ + SupportedChain.FABRIC, + SupportedChain.BESU, ]); expect(identity.proofID).toBe("mockProofID1"); expect(identity.gatewayServerPort).toBe(3010); @@ -80,10 +80,7 @@ describe("SATPGateway initialization", () => { Crash: "v1", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", gatewayServerPort: 3010, address: "https://localhost", @@ -104,9 +101,9 @@ describe("SATPGateway initialization", () => { Crash: "v1", }, ]); - expect(identity.supportedChains).toEqual([ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, + expect(identity.supportedDLTs).toEqual([ + SupportedChain.FABRIC, + SupportedChain.BESU, ]); expect(identity.proofID).toBe("mockProofID10"); expect(identity.gatewayServerPort).toBe(3010); @@ -126,10 +123,7 @@ describe("SATPGateway initialization", () => { Crash: "v02", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", address: "https://localhost", }, @@ -158,10 +152,7 @@ describe("SATPGateway initialization", () => { Crash: "v02", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", gatewayServerPort: 3014, gatewayClientPort: 3015, @@ -205,7 +196,6 @@ describe("SATPGateway initialization", () => { }); }); - describe("SATPGateway startup", () => { it("initiates with default config", async () => { const options: SATPGatewayConfig = {}; @@ -224,9 +214,9 @@ describe("SATPGateway startup", () => { Crash: "v02", }, ]); - expect(identity.supportedChains).toEqual([ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, + expect(identity.supportedDLTs).toEqual([ + SupportedChain.FABRIC, + SupportedChain.BESU, ]); expect(identity.proofID).toBe("mockProofID1"); expect(identity.gatewayClientPort).toBe(3011); @@ -246,10 +236,7 @@ describe("SATPGateway startup", () => { Crash: "v1", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", gatewayClientPort: 3001, address: "https://localhost", @@ -270,9 +257,9 @@ describe("SATPGateway startup", () => { Crash: "v1", }, ]); - expect(identity.supportedChains).toEqual([ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, + expect(identity.supportedDLTs).toEqual([ + SupportedChain.FABRIC, + SupportedChain.BESU, ]); expect(identity.proofID).toBe("mockProofID10"); expect(identity.gatewayClientPort).toBe(3001); @@ -292,10 +279,7 @@ describe("SATPGateway startup", () => { Crash: "v02", }, ], - supportedChains: [ - SupportedGatewayImplementations.FABRIC, - SupportedGatewayImplementations.BESU, - ], + supportedDLTs: [SupportedChain.FABRIC, SupportedChain.BESU], proofID: "mockProofID10", gatewayClientPort: 3010, address: "https://localhost", @@ -307,7 +291,7 @@ describe("SATPGateway startup", () => { const identity = gateway.Identity; expect(identity.gatewayClientPort).toBe(3010); expect(identity.address).toBe("https://localhost"); - await gateway.startupGatewayServer(); + await gateway.startup(); await gateway.shutdown(); }); }); diff --git a/yarn.lock b/yarn.lock index 66f69410dc..9d2043bf7b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4406,13 +4406,20 @@ __metadata: languageName: node linkType: hard -"@bufbuild/protobuf@npm:1.8.0, @bufbuild/protobuf@npm:^1.6.0, @bufbuild/protobuf@npm:^1.7.2, @bufbuild/protobuf@npm:^1.8.0": +"@bufbuild/protobuf@npm:1.8.0, @bufbuild/protobuf@npm:^1.7.2, @bufbuild/protobuf@npm:^1.8.0": version: 1.8.0 resolution: "@bufbuild/protobuf@npm:1.8.0" checksum: 10/f91d60ff1609c023466500e99312d2e92ac09c163d615c315fa25d9e50f1e9b76a3a9cac776786a3dd5c5065bb7061bf29388587e2a1d27306f68ed98e57a892 languageName: node linkType: hard +"@bufbuild/protobuf@npm:1.9.0, @bufbuild/protobuf@npm:^1.6.0": + version: 1.9.0 + resolution: "@bufbuild/protobuf@npm:1.9.0" + checksum: 10/d55bd6acf54e7ec63550d6dc5d74e43bbe8d919a14f95b8039543818281564d2ba63c8fd5177bde220c2820d380063b36c561ff24b6125b6e4481f47d156ff09 + languageName: node + linkType: hard + "@bufbuild/protoc-gen-es@npm:1.7.2": version: 1.7.2 resolution: "@bufbuild/protoc-gen-es@npm:1.7.2" @@ -4458,7 +4465,7 @@ __metadata: languageName: node linkType: hard -"@bufbuild/protoplugin@npm:1.8.0, @bufbuild/protoplugin@npm:^1.6.0, @bufbuild/protoplugin@npm:^1.7.2": +"@bufbuild/protoplugin@npm:1.8.0, @bufbuild/protoplugin@npm:^1.7.2": version: 1.8.0 resolution: "@bufbuild/protoplugin@npm:1.8.0" dependencies: @@ -4469,6 +4476,17 @@ __metadata: languageName: node linkType: hard +"@bufbuild/protoplugin@npm:^1.6.0": + version: 1.9.0 + resolution: "@bufbuild/protoplugin@npm:1.9.0" + dependencies: + "@bufbuild/protobuf": "npm:1.9.0" + "@typescript/vfs": "npm:^1.4.0" + typescript: "npm:4.5.2" + checksum: 10/8b460b03efa7f9d9eb48ad9387ffe9277465968a40278c5f959a045fefa4d54272114ec5639cb76673b27cd9f4347251034f83cebc1523d8db190d4b53c7ac92 + languageName: node + linkType: hard + "@chainsafe/as-sha256@npm:^0.3.1": version: 0.3.1 resolution: "@chainsafe/as-sha256@npm:0.3.1" @@ -6373,6 +6391,17 @@ __metadata: languageName: node linkType: hard +"@ethereumjs/util@npm:^8.1.0": + version: 8.1.0 + resolution: "@ethereumjs/util@npm:8.1.0" + dependencies: + "@ethereumjs/rlp": "npm:^4.0.1" + ethereum-cryptography: "npm:^2.0.0" + micro-ftch: "npm:^0.3.1" + checksum: 10/cc35338932e49b15e54ca6e548b32a1f48eed7d7e1d34ee743e4d3600dd616668bd50f70139e86c5c35f55aac35fba3b6cc4e6f679cf650aeba66bf93016200c + languageName: node + linkType: hard + "@ethereumjs/util@npm:^9.0.0": version: 9.0.0 resolution: "@ethereumjs/util@npm:9.0.0" @@ -12964,14 +12993,14 @@ __metadata: linkType: hard "@quobix/vacuum@npm:^0.9.10": - version: 0.9.13 - resolution: "@quobix/vacuum@npm:0.9.13" + version: 0.9.16 + resolution: "@quobix/vacuum@npm:0.9.16" dependencies: node-fetch: "npm:^3.2.10" tar: "npm:^6.1.11" bin: vacuum: bin/vacuum.js - checksum: 10/330be4ac2af28d0e387f2eab77182ac5a37b44c456f76705d51c0b5b97d937295781ed514e905a313bb0a1cd4fa15e17112efa4fffbea5f203917c76a4be3d00 + checksum: 10/0e9d717f8c8c2accf39e333d12e101e543229c41b9b3c8e7717e6b00de24e792392437dcb40700113033686b542643c10ebb25b4389b059a4a461af0b4e9aa44 languageName: node linkType: hard @@ -16125,9 +16154,9 @@ __metadata: linkType: hard "@types/validator@npm:^13.11.8": - version: 13.11.9 - resolution: "@types/validator@npm:13.11.9" - checksum: 10/2d397c69293cc726e0cf1b4c74c563ca4e459b00f216f3ff0ac184c9648103be27169e8c67f85be9c6e7a3fcbb149c6add66a2547b185a1b25aa79e4b61261bd + version: 13.11.10 + resolution: "@types/validator@npm:13.11.10" + checksum: 10/5f074f7d0bb92ba035ebac28692599755d7285c6961aff2092e6c13e11b6a3f50101e602197bc15a3b1eb7f40d5d5efc485790e79c58e30042c7f915e74c85c5 languageName: node linkType: hard @@ -17243,20 +17272,6 @@ __metadata: languageName: node linkType: hard -"ajv-formats@npm:^3.0.1": - version: 3.0.1 - resolution: "ajv-formats@npm:3.0.1" - dependencies: - ajv: "npm:^8.0.0" - peerDependencies: - ajv: ^8.0.0 - peerDependenciesMeta: - ajv: - optional: true - checksum: 10/5679b9f9ced9d0213a202a37f3aa91efcffe59a6de1a6e3da5c873344d3c161820a1f11cc29899661fee36271fd2895dd3851b6461c902a752ad661d1c1e8722 - languageName: node - linkType: hard - "ajv-keywords@npm:^2.1.0": version: 2.1.1 resolution: "ajv-keywords@npm:2.1.1" @@ -26534,17 +26549,17 @@ __metadata: linkType: hard "fast-json-stringify@npm:^5.7.0, fast-json-stringify@npm:^5.8.0": - version: 5.14.1 - resolution: "fast-json-stringify@npm:5.14.1" + version: 5.13.0 + resolution: "fast-json-stringify@npm:5.13.0" dependencies: "@fastify/merge-json-schemas": "npm:^0.1.0" ajv: "npm:^8.10.0" - ajv-formats: "npm:^3.0.1" + ajv-formats: "npm:^2.1.1" fast-deep-equal: "npm:^3.1.3" fast-uri: "npm:^2.1.0" json-schema-ref-resolver: "npm:^1.0.1" rfdc: "npm:^1.2.0" - checksum: 10/41945db9f9da0468b2089a4fc8ba7cf620bbb573a4daa71950e97257cf8acce87ed0d9569b68336cda9ff087678c481eb96b7ec7576ee1365e7dd55c7fa37487 + checksum: 10/84820e26749481b7af929926453c77382fb187623f9f08da84102602f5e41301113501a2f0fc9f561673cc97e58a9247848b6574925644f7f54cf0bb6809a885 languageName: node linkType: hard @@ -34125,9 +34140,9 @@ __metadata: linkType: hard "libphonenumber-js@npm:^1.10.53": - version: 1.10.60 - resolution: "libphonenumber-js@npm:1.10.60" - checksum: 10/5fbae9dde13fdad9e14166dc652aae896ef16896b6c436563b8860eef8beda0b63286a54c962fc4e2345a6c4aef63d01aad9c1a81663d96566f9a764e70536d4 + version: 1.11.1 + resolution: "libphonenumber-js@npm:1.11.1" + checksum: 10/ce34fa0c35e5ee95042ee834918e10b01e37e9d95291a2da466458906a454cde0966dacaea98d3e94fa279e0cef9b613c2bbcdbf0bfd22f75e24f496cfc1c534 languageName: node linkType: hard @@ -34195,13 +34210,13 @@ __metadata: linkType: hard "light-my-request@npm:^5.11.0": - version: 5.13.0 - resolution: "light-my-request@npm:5.13.0" + version: 5.12.0 + resolution: "light-my-request@npm:5.12.0" dependencies: cookie: "npm:^0.6.0" process-warning: "npm:^3.0.0" set-cookie-parser: "npm:^2.4.1" - checksum: 10/29407ecd0fcc240fbc4ac53457247e7f796962aaa228e9c5057bb4a7d84fda4f14eaaf39212f2dbfe0869b78a2a42ec82ec4a597a181b9ee19ac23a636c0160d + checksum: 10/20fa6a468b32612d2eb041ba6510fec86cf786349af3fc66c11cdac2c6e9b572e141294dd90e040610284d724694d5bc1e7badfd41d0b180a10890034e00b9eb languageName: node linkType: hard @@ -35443,6 +35458,19 @@ __metadata: languageName: node linkType: hard +"merkletreejs@npm:0.3.11": + version: 0.3.11 + resolution: "merkletreejs@npm:0.3.11" + dependencies: + bignumber.js: "npm:^9.0.1" + buffer-reverse: "npm:^1.0.1" + crypto-js: "npm:^4.2.0" + treeify: "npm:^1.1.0" + web3-utils: "npm:^1.3.4" + checksum: 10/a93520ef768648d1e4ebd175182bd3d304270b8eb0700df5be99395fb3ad8805407bdaf3231d13b1649e87de799aa06d71c616db047ad039025764eb23b02244 + languageName: node + linkType: hard + "methods@npm:^1.1.2, methods@npm:~1.1.2": version: 1.1.2 resolution: "methods@npm:1.1.2" @@ -35450,6 +35478,13 @@ __metadata: languageName: node linkType: hard +"micro-ftch@npm:^0.3.1": + version: 0.3.1 + resolution: "micro-ftch@npm:0.3.1" + checksum: 10/a7ab07d25e28ec4ae492ce4542ea9b06eee85538742b3b1263b247366ee8872f2c5ce9c8651138b2f1d22c8212f691a7b8b5384fe86ead5aff1852e211f1c035 + languageName: node + linkType: hard + "micromatch@npm:^2.3.11": version: 2.3.11 resolution: "micromatch@npm:2.3.11" @@ -39337,7 +39372,7 @@ __metadata: languageName: node linkType: hard -"pino-abstract-transport@npm:^1.1.0": +"pino-abstract-transport@npm:v1.1.0": version: 1.1.0 resolution: "pino-abstract-transport@npm:1.1.0" dependencies: @@ -39355,13 +39390,13 @@ __metadata: linkType: hard "pino@npm:^8.17.0": - version: 8.20.0 - resolution: "pino@npm:8.20.0" + version: 8.19.0 + resolution: "pino@npm:8.19.0" dependencies: atomic-sleep: "npm:^1.0.0" fast-redact: "npm:^3.1.1" on-exit-leak-free: "npm:^2.1.0" - pino-abstract-transport: "npm:^1.1.0" + pino-abstract-transport: "npm:v1.1.0" pino-std-serializers: "npm:^6.0.0" process-warning: "npm:^3.0.0" quick-format-unescaped: "npm:^4.0.3" @@ -39371,7 +39406,7 @@ __metadata: thread-stream: "npm:^2.0.0" bin: pino: bin.js - checksum: 10/c236ad50ea6fa533b25275928ac1c3c96d6c06df08f79a70d91a571fcf1b6fe0570c6f4b00eb5ad201fa9b4a9292d4cfe21fd8af29fa1df44aa1963d35c1bf8b + checksum: 10/c98e8bedb7c9eca5c0e75c2dd910a58b0e470da282c5a4787873a591666cc7cce33561d9ba6d6a20cf6bc4bc8d15b7db84cf6156f262081a5c6b8de134285789 languageName: node linkType: hard @@ -45869,9 +45904,9 @@ __metadata: linkType: hard "swagger-ui-dist@npm:>=5.0.0": - version: 5.15.1 - resolution: "swagger-ui-dist@npm:5.15.1" - checksum: 10/5250fda8d2135edf485dc334f88fc42c05da568379ced81429b01f06c64cabc337a7a925e7bb3d0c9d5e5ef79ad07aa9d1392a3ddafefe6e83b03538db7334e7 + version: 5.17.7 + resolution: "swagger-ui-dist@npm:5.17.7" + checksum: 10/17fd7c632e040c8d6aa7ac77e9688e2d1f70037631864a60a8147d4cf528fe93f6b94b44c15466d1be78c587242b4b469e95db1b7bf9d0cdaaecf889c395b222 languageName: node linkType: hard @@ -48378,13 +48413,20 @@ __metadata: languageName: node linkType: hard -"validator@npm:^13.7.0, validator@npm:^13.9.0": +"validator@npm:^13.7.0": version: 13.11.0 resolution: "validator@npm:13.11.0" checksum: 10/4bf094641eb71729c06a42d669840e7189597ba655a8264adabac9bf03f95cd6fde5fbc894b0a13ee861bd4a852f56d2afdc9391aeaeb3fc0f9633a974140e12 languageName: node linkType: hard +"validator@npm:^13.9.0": + version: 13.12.0 + resolution: "validator@npm:13.12.0" + checksum: 10/db6eb0725e2b67d60d30073ae8573982713b5903195d031dc3c7db7e82df8b74e8c13baef8e2106d146d979599fd61a06cde1fec5c148e4abd53d52817ff0fd9 + languageName: node + linkType: hard + "value-or-promise@npm:1.0.11": version: 1.0.11 resolution: "value-or-promise@npm:1.0.11" @@ -50561,6 +50603,19 @@ __metadata: languageName: node linkType: hard +"web3-utils@npm:^4.0.3, web3-utils@npm:^4.2.3": + version: 4.2.3 + resolution: "web3-utils@npm:4.2.3" + dependencies: + ethereum-cryptography: "npm:^2.0.0" + eventemitter3: "npm:^5.0.1" + web3-errors: "npm:^1.1.4" + web3-types: "npm:^1.6.0" + web3-validator: "npm:^2.0.5" + checksum: 10/2a1a696ddd8f4318048913fd75af0f11599fa03ff731aeed72d1c7bc6577c99317bdc3529844e7ff1a74b18ec99a5e08f5695537f0d56f44e707477014ea2a11 + languageName: node + linkType: hard + "web3-utils@npm:^4.0.7": version: 4.0.7 resolution: "web3-utils@npm:4.0.7"