diff --git a/packages/cactus-plugin-satp-hermes/cache/solidity-files-cache.json b/packages/cactus-plugin-satp-hermes/cache/solidity-files-cache.json index 46372ef060..fd506e80f5 100644 --- a/packages/cactus-plugin-satp-hermes/cache/solidity-files-cache.json +++ b/packages/cactus-plugin-satp-hermes/cache/solidity-files-cache.json @@ -1 +1 @@ -{"_format":"","paths":{"artifacts":"src/solidity/generated","build_infos":"src/solidity/generated/build-info","sources":"src","tests":"test","scripts":"script","libraries":["lib","node_modules"]},"files":{"node_modules/@openzeppelin/contracts/access/Ownable.sol":{"lastModificationDate":1721844842602,"contentHash":"d3c790edc9ccf808a17c5a6cd13614fd","sourceName":"node_modules/@openzeppelin/contracts/access/Ownable.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/utils/Context.sol"],"versionRequirement":"^0.8.20","artifacts":{"Ownable":{"0.8.20":{"path":"Ownable.sol/Ownable.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/Context.sol":{"lastModificationDate":1721844842606,"contentHash":"67bfbc07588eb8683b3fd8f6f909563e","sourceName":"node_modules/@openzeppelin/contracts/utils/Context.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"Context":{"0.8.20":{"path":"Context.sol/Context.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/Strings.sol":{"lastModificationDate":1721844842616,"contentHash":"ba57ff4ddf1d9cae9d2009792795b7f6","sourceName":"node_modules/@openzeppelin/contracts/utils/Strings.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/utils/math/Math.sol","node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol"],"versionRequirement":"^0.8.20","artifacts":{"Strings":{"0.8.20":{"path":"Strings.sol/Strings.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/math/Math.sol":{"lastModificationDate":1721844842612,"contentHash":"718fa8ba0ff269c92e364c1429d9de57","sourceName":"node_modules/@openzeppelin/contracts/utils/math/Math.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"Math":{"0.8.20":{"path":"Math.sol/Math.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol":{"lastModificationDate":1721844842613,"contentHash":"b6c6bdc7aaca4fe5b680760a72e09d3e","sourceName":"node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"SignedMath":{"0.8.20":{"path":"SignedMath.sol/SignedMath.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"src/solidity/ITraceableContract.sol":{"lastModificationDate":1723214831340,"contentHash":"231f3764075b7c107364f860e71e2141","sourceName":"src/solidity/ITraceableContract.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":">=0.7.0","artifacts":{"ITraceableContract":{"0.8.20":{"path":"ITraceableContract.sol/ITraceableContract.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"src/solidity/satp-wrapper-without-json.sol":{"lastModificationDate":1723214831340,"contentHash":"6bf8a1d02b875a68cf65af7dcc0c9c46","sourceName":"src/solidity/satp-wrapper-without-json.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/access/Ownable.sol","node_modules/@openzeppelin/contracts/utils/Context.sol","node_modules/@openzeppelin/contracts/utils/Strings.sol","node_modules/@openzeppelin/contracts/utils/math/Math.sol","node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol","src/solidity/ITraceableContract.sol"],"versionRequirement":"^0.8.20","artifacts":{"SATPWrapperContract":{"0.8.20":{"path":"satp-wrapper-without-json.sol/SATPWrapperContract.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true},"src/solidity/satp-wrapper.sol":{"lastModificationDate":1723214831340,"contentHash":"3796cb4be7c06c5c8912e8137293b8a9","sourceName":"src/solidity/satp-wrapper.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/access/Ownable.sol","node_modules/@openzeppelin/contracts/utils/Context.sol","node_modules/@openzeppelin/contracts/utils/Strings.sol","node_modules/@openzeppelin/contracts/utils/math/Math.sol","node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol","src/solidity/ITraceableContract.sol"],"versionRequirement":"^0.8.20","artifacts":{"SATPWrapperContract":{"0.8.20":{"path":"satp-wrapper.sol/SATPWrapperContract.json","build_id":"26ba0bad9cd6a2a223b826c990b4cd8e"}}},"seenByCompiler":true}},"builds":["26ba0bad9cd6a2a223b826c990b4cd8e"]} \ No newline at end of file +{"_format":"","paths":{"artifacts":"src/test/solidity/generated","build_infos":"src/test/solidity/generated/build-info","sources":"src","tests":"test","scripts":"script","libraries":["lib","node_modules"]},"files":{"node_modules/@openzeppelin/contracts/access/AccessControl.sol":{"lastModificationDate":1722543467180,"contentHash":"4c80b7fdf559a9a348e832a57d072a0b","sourceName":"node_modules/@openzeppelin/contracts/access/AccessControl.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/access/IAccessControl.sol","node_modules/@openzeppelin/contracts/utils/Context.sol","node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol","node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol"],"versionRequirement":"^0.8.20","artifacts":{"AccessControl":{"0.8.20":{"path":"AccessControl.sol/AccessControl.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/access/IAccessControl.sol":{"lastModificationDate":1722543467188,"contentHash":"e3a14b0714caaaa82d58fa0bc3756079","sourceName":"node_modules/@openzeppelin/contracts/access/IAccessControl.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"IAccessControl":{"0.8.20":{"path":"IAccessControl.sol/IAccessControl.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol":{"lastModificationDate":1722543467228,"contentHash":"4aefc698f77ecbace7f401257dfe182d","sourceName":"node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"IERC1155Errors":{"0.8.20":{"path":"draft-IERC6093.sol/IERC1155Errors.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}},"IERC20Errors":{"0.8.20":{"path":"draft-IERC6093.sol/IERC20Errors.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}},"IERC721Errors":{"0.8.20":{"path":"draft-IERC6093.sol/IERC721Errors.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol":{"lastModificationDate":1722543467264,"contentHash":"c6375ef25e84c90b3d15f9ec4eef218f","sourceName":"node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol","node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol","node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol","node_modules/@openzeppelin/contracts/utils/Context.sol"],"versionRequirement":"^0.8.20","artifacts":{"ERC20":{"0.8.20":{"path":"ERC20.sol/ERC20.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol":{"lastModificationDate":1722543467288,"contentHash":"5517c8678c18eb1a8ba58810e7ca39ca","sourceName":"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"IERC20":{"0.8.20":{"path":"IERC20.sol/IERC20.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"lastModificationDate":1722543467280,"contentHash":"4c02fa6f7ae7b6c289cef80424f0c875","sourceName":"node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol"],"versionRequirement":"^0.8.20","artifacts":{"IERC20Metadata":{"0.8.20":{"path":"IERC20Metadata.sol/IERC20Metadata.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/Context.sol":{"lastModificationDate":1722543467200,"contentHash":"67bfbc07588eb8683b3fd8f6f909563e","sourceName":"node_modules/@openzeppelin/contracts/utils/Context.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"Context":{"0.8.20":{"path":"Context.sol/Context.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/Strings.sol":{"lastModificationDate":1722543467216,"contentHash":"ba57ff4ddf1d9cae9d2009792795b7f6","sourceName":"node_modules/@openzeppelin/contracts/utils/Strings.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/utils/math/Math.sol","node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol"],"versionRequirement":"^0.8.20","artifacts":{"Strings":{"0.8.20":{"path":"Strings.sol/Strings.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol":{"lastModificationDate":1722543467204,"contentHash":"6a55c353946e471d9792965d06208295","sourceName":"node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol"],"versionRequirement":"^0.8.20","artifacts":{"ERC165":{"0.8.20":{"path":"ERC165.sol/ERC165.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol":{"lastModificationDate":1722543467208,"contentHash":"de0163561b417b800d01749cbbe2147e","sourceName":"node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"IERC165":{"0.8.20":{"path":"IERC165.sol/IERC165.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/math/Math.sol":{"lastModificationDate":1722543467208,"contentHash":"718fa8ba0ff269c92e364c1429d9de57","sourceName":"node_modules/@openzeppelin/contracts/utils/math/Math.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"Math":{"0.8.20":{"path":"Math.sol/Math.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol":{"lastModificationDate":1722543467208,"contentHash":"b6c6bdc7aaca4fe5b680760a72e09d3e","sourceName":"node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":"^0.8.20","artifacts":{"SignedMath":{"0.8.20":{"path":"SignedMath.sol/SignedMath.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"src/test/solidity/contracts/ITraceableContract.sol":{"lastModificationDate":1722542120772,"contentHash":"231f3764075b7c107364f860e71e2141","sourceName":"src/test/solidity/contracts/ITraceableContract.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":">=0.7.0","artifacts":{"ITraceableContract":{"0.8.20":{"path":"ITraceableContract.sol/ITraceableContract.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"src/test/solidity/contracts/satp-contract-interface.sol":{"lastModificationDate":1722542120772,"contentHash":"2411a0d6a3ea8e5f85c97e6ae77fead4","sourceName":"src/test/solidity/contracts/satp-contract-interface.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":[],"versionRequirement":">=0.7.0","artifacts":{"SATPContractInterface":{"0.8.20":{"path":"satp-contract-interface.sol/SATPContractInterface.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true},"src/test/solidity/contracts/satp-erc20.sol":{"lastModificationDate":1722542120772,"contentHash":"5ecdb78db9a7b063ee9e0a5702733bd6","sourceName":"src/test/solidity/contracts/satp-erc20.sol","compilerSettings":{"solc":{"optimizer":{"enabled":true,"runs":200},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"paris","viaIR":false,"libraries":{}},"vyper":{"evmVersion":"paris","outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode"]}}}},"imports":["node_modules/@openzeppelin/contracts/access/AccessControl.sol","node_modules/@openzeppelin/contracts/access/IAccessControl.sol","node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol","node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol","node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol","node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol","node_modules/@openzeppelin/contracts/utils/Context.sol","node_modules/@openzeppelin/contracts/utils/Strings.sol","node_modules/@openzeppelin/contracts/utils/introspection/ERC165.sol","node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol","node_modules/@openzeppelin/contracts/utils/math/Math.sol","node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol","src/test/solidity/contracts/ITraceableContract.sol","src/test/solidity/contracts/satp-contract-interface.sol"],"versionRequirement":"^0.8.20","artifacts":{"SATPContract":{"0.8.20":{"path":"satp-erc20.sol/SATPContract.json","build_id":"1850d4b29fc5f56323d9fed285466abb"}}},"seenByCompiler":true}},"builds":["1850d4b29fc5f56323d9fed285466abb"]} \ No newline at end of file diff --git a/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/common/session.proto b/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/common/session.proto index f5ac206ea0..ec33400858 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/common/session.proto +++ b/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/common/session.proto @@ -68,6 +68,7 @@ message SessionData { string server_transfer_number = 58; uint64 lock_assertion_expiration = 59; cacti.satp.v02.common.AssetProfile asset_profile = 60; + string resource_url = 61; } diff --git a/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/stage_1.proto b/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/stage_1.proto index 8a36c5c6f4..02a18bac5b 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/stage_1.proto +++ b/packages/cactus-plugin-satp-hermes/src/main/proto/cacti/satp/v02/stage_1.proto @@ -19,7 +19,7 @@ message TransferProposalReceiptMessage { string hash_transfer_init_claims = 2; cacti.satp.v02.common.TransferClaims transfer_counter_claims = 3; string timestamp = 4; - string server_signature = 5; + string server_signature = 6; } message TransferCommenceRequestMessage { 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 626e05ea1c..5a6589b2e4 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 @@ -1,4 +1,4 @@ -import { GetStatusError } from "../../core/errors"; +import { GetStatusError } from "../../core/errors/satp-errors"; import { StatusRequest, StatusResponse, diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/bridge-erros.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/bridge-erros.ts new file mode 100644 index 0000000000..448775cb53 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/bridge-erros.ts @@ -0,0 +1,35 @@ +export class BridgeInternalError extends Error { + constructor( + public message: string, + // TODO internal error codes + public code: number = 500, + public traceID?: 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 + //this.stack = trace || new Error().stack; + } +} + +export class OntologyError extends BridgeInternalError { + constructor(tag: string) { + super( + `${tag}, undefined Ontology, ontology is required to interact with tokens`, + 500, + ); + } +} + +export class TransactionError extends BridgeInternalError { + constructor(tag: string) { + super(`${tag}, Transaction failed`, 500); + } +} + +export class TransactionIdUndefinedError extends BridgeInternalError { + constructor(tag: string) { + super(`${tag}, Transaction id undefined`, 500); + } +} 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/satp-errors.ts similarity index 96% rename from packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts rename to packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-errors.ts index 9a3f4ebe54..8c6f4bb9e2 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-errors.ts @@ -9,7 +9,7 @@ export class SATPInternalError extends Error { super(message); this.name = this.constructor.name; Object.setPrototypeOf(this, new.target.prototype); // make sure prototype chain is set to error - this.stack = trace || new Error().stack; + //this.stack = trace || new Error().stack; } } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-handler-errors.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-handler-errors.ts new file mode 100644 index 0000000000..04e2ad1a01 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-handler-errors.ts @@ -0,0 +1,25 @@ +import { SATPInternalError } from "./satp-errors"; + +export class SessionNotFoundError extends SATPInternalError { + constructor(tag: string) { + super(`${tag}, session not found`, 500); + } +} + +export class SessionIdNotFoundError extends SATPInternalError { + constructor(tag: string) { + super(`${tag}, session id not found`, 500); + } +} + +export class FailedToCreateMessageError extends SATPInternalError { + constructor(tag: string, message: string) { + super(`${tag}, failed to create message: ${message}`, 500); + } +} + +export class FailedToProcessError extends SATPInternalError { + constructor(tag: string, message: string) { + super(`${tag}, failed to process: ${message}`, 500); + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-service-errors.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-service-errors.ts new file mode 100644 index 0000000000..c5962c983f --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/errors/satp-service-errors.ts @@ -0,0 +1,168 @@ +import { SATPInternalError } from "./satp-errors"; + +export class SatpCommonBodyError extends SATPInternalError { + constructor(fnTag: string, data: string) { + super( + `${fnTag}, message satp common body is missing or is missing required fields \n ${data}`, + 400, + ); + } +} +export class SessionError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, session undefined`, 500); + } +} + +export class SessionDataNotLoadedCorrectlyError extends SATPInternalError { + constructor(fnTag: string, data: string) { + super(`${fnTag}, session data was not loaded correctly \n ${data}`, 500); + } +} + +export class SessionCompletedError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, session data already completed`, 500); + } +} + +export class SATPVersionError extends SATPInternalError { + constructor(fnTag: string, unsupported: string, supported: string) { + super( + `${fnTag}, unsupported SATP version \n received: ${unsupported}, supported: ${supported}`, + 400, + ); + } +} + +export class SignatureVerificationError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, message signature verification failed`, 400); + } +} + +export class SignatureMissingError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, message signature missing`, 400); + } +} + +export class MessageTypeError extends SATPInternalError { + constructor(fnTag: string, received: string, expected: string) { + super( + `${fnTag}, message type miss match \n received: ${received} \n expected: ${expected}`, + 400, + ); + } +} + +export class TransferInitClaimsError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, transferInitClaims missing or faulty`, 400); + } +} + +export class TransferInitClaimsHashError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, transferInitClaims hash missing or missmatch`, 400); + } +} + +export class NetworkCapabilitiesError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, NetworkCapabilitiesError missing or faulty`, 400); + } +} + +export class DLTNotSupportedError extends SATPInternalError { + constructor(fnTag: string, dlt: string) { + super(`${fnTag}, DLT not supported \n received: ${dlt}`, 400); + } +} + +export class ServerGatewayPubkeyError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, serverGatewayPubkey missing or missmatch`, 400); + } +} + +export class ClientGatewayPubkeyError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, clientGatewayPubkey missing or missmatch`, 400); + } +} + +export class SequenceNumberError extends SATPInternalError { + constructor(fnTag: string, received: bigint, expected: bigint) { + super( + `${fnTag}, sequence number missmatch \n received: ${received} \n expected: ${expected}`, + 400, + ); + } +} + +export class HashError extends SATPInternalError { + constructor(fnTag: string, received: string, expected: string) { + super( + `${fnTag}, hash missmatch \n received: ${received} \n expected: ${expected}`, + 400, + ); + } +} + +export class TransferContextIdError extends SATPInternalError { + constructor(fnTag: string, received: string, expected: string) { + super( + `${fnTag}, transferContextId missing or missmatch \n received: ${received} \n expected: ${expected}`, + 400, + ); + } +} + +export class MissingBridgeManagerError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, bridge manager missing`, 400); + } +} + +export class LockAssertionClaimError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, lockAssertionClaim missing or faulty`, 400); + } +} + +export class LockAssertionClaimFormatError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, lockAssertionClaimFormat missing`, 400); + } +} + +export class LockAssertionExpirationError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, lockAssertionExpiration missing or faulty`, 400); + } +} + +export class BurnAssertionClaimError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, burnAssertionClaim missing or faulty`, 400); + } +} + +export class MintAssertionClaimError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, mintAssertionClaim missing or faulty`, 400); + } +} + +export class AssignmentAssertionClaimError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, assignmentAssertionClaim missing or faulty`, 400); + } +} + +export class ResourceUrlError extends SATPInternalError { + constructor(fnTag: string) { + super(`${fnTag}, resourceUrl missing or missmatch`, 400); + } +} 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 db3b168121..432f3c6cdf 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 @@ -14,6 +14,14 @@ import { Stage3Signatures, Stage3Timestamps, } from "../generated/proto/cacti/satp/v02/common/session_pb"; +import { + SATPVersionError, + SessionCompletedError, + SessionDataNotLoadedCorrectlyError, +} from "./errors/satp-service-errors"; +import { SATP_VERSION } from "./constants"; +import { LockType } from "../generated/proto/cacti/satp/v02/common/message_pb"; +import { SessionType } from "./session-utils"; // Define interface on protos export interface ISATPSessionOptions { @@ -75,11 +83,21 @@ export class SATPSession { sessionData.signatures.stage3 = new Stage3Signatures(); } - public getServerSessionData(): SessionData | undefined { + public getServerSessionData(): SessionData { + if (this.serverSessionData == undefined) { + throw new Error( + `${SATPSession.CLASS_NAME}#getServerSessionData(), serverSessionData is undefined`, + ); + } return this.serverSessionData; } - public getClientSessionData(): SessionData | undefined { + public getClientSessionData(): SessionData { + if (this.clientSessionData == undefined) { + throw new Error( + `${SATPSession.CLASS_NAME}#getClientSessionData(), clientSessionData is undefined`, + ); + } return this.clientSessionData; } @@ -94,4 +112,58 @@ export class SATPSession { public getSessionId(): string { return this.serverSessionData?.id || this.clientSessionData?.id || ""; } + + public verify(tag: string, type: SessionType): void { + let sessionData: SessionData | undefined; + if (type == SessionType.SERVER) { + sessionData = this.getServerSessionData(); + } else if (type == SessionType.CLIENT) { + sessionData = this.getClientSessionData(); + } else { + throw new Error( + `${SATPSession.CLASS_NAME}#verify(), sessionData type is not valid`, + ); + } + + if (sessionData == undefined) { + throw new SessionDataNotLoadedCorrectlyError(tag, "undefined"); + } + + if (sessionData.completed) { + throw new SessionCompletedError("Session already completed"); + } + + if ( + sessionData.version == "" || + sessionData.id == "" || + sessionData.digitalAssetId == "" || + sessionData.originatorPubkey == "" || + sessionData.beneficiaryPubkey == "" || + sessionData.senderGatewayNetworkId == "" || + sessionData.recipientGatewayNetworkId == "" || + sessionData.clientGatewayPubkey == "" || + sessionData.serverGatewayPubkey == "" || + sessionData.senderGatewayOwnerId == "" || + sessionData.receiverGatewayOwnerId == "" || + // sessionData.maxRetries == undefined || + // sessionData.maxTimeout == undefined || + sessionData.senderGatewayNetworkId == "" || + sessionData.signatureAlgorithm == undefined || + sessionData.lockType == LockType.UNSPECIFIED || + sessionData.lockExpirationTime == BigInt(0) || + sessionData.credentialProfile == undefined || + sessionData.loggingProfile == "" || + sessionData.accessControlProfile == "" || + // sessionData.lastSequenceNumber == BigInt(0) || + sessionData.transferContextId == "" + ) { + throw new SessionDataNotLoadedCorrectlyError( + tag, + JSON.stringify(sessionData), + ); + } + if (sessionData.version != SATP_VERSION) { + throw new SATPVersionError(tag, sessionData.version, SATP_VERSION); + } + } } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/session-utils.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/session-utils.ts index aed061f862..c0065f88c6 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/session-utils.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/session-utils.ts @@ -292,6 +292,47 @@ export function saveSignature( } } +export function getPreviousMessageType( + sessionData: SessionData | undefined, + type: MessageType, +): MessageType { + if (sessionData == undefined) { + throw new Error("No session data provided"); + } + + switch (type) { + case MessageType.INIT_PROPOSAL: + MessageType.UNSPECIFIED; + case MessageType.INIT_RECEIPT: + return MessageType.INIT_PROPOSAL; + case MessageType.INIT_REJECT: + return MessageType.INIT_PROPOSAL; + case MessageType.TRANSFER_COMMENCE_REQUEST: + if (sessionData.hashes?.stage1?.transferProposalRejectMessageHash) { + return MessageType.INIT_REJECT; + } + return MessageType.INIT_RECEIPT; + case MessageType.TRANSFER_COMMENCE_RESPONSE: + return MessageType.TRANSFER_COMMENCE_REQUEST; + case MessageType.LOCK_ASSERT: + return MessageType.TRANSFER_COMMENCE_RESPONSE; + case MessageType.ASSERTION_RECEIPT: + return MessageType.LOCK_ASSERT; + case MessageType.COMMIT_PREPARE: + return MessageType.ASSERTION_RECEIPT; + case MessageType.COMMIT_READY: + return MessageType.COMMIT_PREPARE; + case MessageType.COMMIT_FINAL: + return MessageType.COMMIT_READY; + case MessageType.ACK_COMMIT_FINAL: + return MessageType.COMMIT_FINAL; + case MessageType.COMMIT_TRANSFER_COMPLETE: + return MessageType.ACK_COMMIT_FINAL; + default: + throw new Error("Message type not found"); + } +} + export function getMessageHash( sessionData: SessionData | undefined, messageType: MessageType, @@ -399,34 +440,3 @@ export function getMessageTimestamp( throw new Error("Message hash not found"); } } - -export function checkSessionData(sessionData: SessionData): boolean { - if ( - sessionData.version == undefined || - sessionData.id == undefined || - sessionData.digitalAssetId == undefined || - sessionData.originatorPubkey == undefined || - sessionData.beneficiaryPubkey == undefined || - sessionData.senderGatewayNetworkId == undefined || - sessionData.recipientGatewayNetworkId == undefined || - sessionData.clientGatewayPubkey == undefined || - sessionData.serverGatewayPubkey == undefined || - sessionData.senderGatewayOwnerId == undefined || - sessionData.receiverGatewayOwnerId == undefined || - // sessionData.maxRetries == undefined || - // sessionData.maxTimeout == undefined || - sessionData.senderGatewayNetworkId == undefined || - sessionData.signatureAlgorithm == undefined || - sessionData.lockType == undefined || - sessionData.lockExpirationTime == undefined || - sessionData.credentialProfile == undefined || - sessionData.loggingProfile == undefined || - sessionData.accessControlProfile == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.multipleClaimsAllowed == undefined || - sessionData.multipleCancelsAllowed == undefined - ) { - return false; - } - return true; -} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/handler-utils.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/handler-utils.ts new file mode 100644 index 0000000000..9b7190cc14 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-handlers/handler-utils.ts @@ -0,0 +1,8 @@ +import { SessionIdNotFoundError } from "../errors/satp-handler-errors"; + +export function getSessionId(obj: any): string { + if (!obj.common.sessionId) { + throw new SessionIdNotFoundError("getSessionId"); + } + return obj.common.sessionId; +} 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 3e9514c9f0..fe3529803f 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 @@ -16,6 +16,12 @@ import { SATPHandlerType, } from "../../types/satp-protocol"; import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; +import { + FailedToCreateMessageError, + FailedToProcessError, + SessionNotFoundError, +} from "../errors/satp-handler-errors"; +import { getSessionId } from "./handler-utils"; export class Stage1SATPHandler implements SATPHandler { public static readonly CLASS_NAME = SATPHandlerType.STAGE1; @@ -56,34 +62,30 @@ export class Stage1SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Transfer Proposal...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkTransferProposalRequestMessage( - req, - session, - this.supportedDLTs, - ); + await this.serverService.checkTransferProposalRequestMessage( + req, + session, + this.supportedDLTs, + ); + const message = await this.serverService.transferProposalResponse( req, session, ); + this.Log.debug(`${fnTag}, Returning response: ${message}`); - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); if (!message) { - throw new Error(`${fnTag}, Failed to create TransferProposalReceipt`); + throw new FailedToCreateMessageError(fnTag, "TransferProposalReceipt"); } return message; } catch (error) { - throw new Error(`${fnTag}, Failed to process TransferProposal ${error}`); + throw new FailedToProcessError(fnTag, "TransferProposalRequest"); } } @@ -97,35 +99,27 @@ export class Stage1SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Transfer Commence...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkTransferCommenceRequestMessage( - req, - session, - ); + await this.serverService.checkTransferCommenceRequestMessage( + req, + session, + ); const message = await this.serverService.transferCommenceResponse( req, session, ); this.Log.debug(`${fnTag}, Returning response: ${message}`); - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); if (!message) { - throw new Error(`${fnTag}, Failed to create TransferCommenceResponse`); + throw new FailedToCreateMessageError(fnTag, "TransferCommenceResponse"); } return message; } catch (error) { - throw new Error( - `${fnTag}, Failed to process TransferCommenceRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferCommenceResponse"); } } @@ -157,13 +151,11 @@ export class Stage1SATPHandler implements SATPHandler { ); if (!requestTransferProposal) { - throw new Error(`${fnTag}, Failed to create TransferProposalRequest`); + throw new FailedToCreateMessageError(fnTag, "TransferProposalRequest"); } return requestTransferProposal; } catch (error) { - throw new Error( - `${fnTag}, Failed to process TransferProposalRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferProposalRequest"); } } @@ -181,7 +173,7 @@ export class Stage1SATPHandler implements SATPHandler { throw new Error(`${fnTag}, Session Id not found`); } - const session = this.sessions.get(response.common?.sessionId); + const session = this.sessions.get(getSessionId(response)); if (!session) { throw new Error(`${fnTag}, Session not found`); } @@ -195,14 +187,12 @@ export class Stage1SATPHandler implements SATPHandler { await this.clientService.transferCommenceRequest(response, session); if (!requestTransferCommence) { - throw new Error(`${fnTag}, Failed to create TransferCommenceRequest`); + throw new FailedToCreateMessageError(fnTag, "TransferCommenceRequest"); } return requestTransferCommence; } catch (error) { - throw new Error( - `${fnTag}, Failed to process TransferCommenceRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferCommenceRequest"); } } } 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 d9bf680194..aa5cd93b49 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 @@ -15,6 +15,12 @@ import { } from "../../generated/proto/cacti/satp/v02/stage_2_pb"; import { Stage2ClientService } from "../stage-services/client/stage2-client-service"; import { TransferCommenceResponseMessage } from "../../generated/proto/cacti/satp/v02/stage_1_pb"; +import { + FailedToCreateMessageError, + FailedToProcessError, + SessionNotFoundError, +} from "../errors/satp-handler-errors"; +import { getSessionId } from "./handler-utils"; export class Stage2SATPHandler implements SATPHandler { public static readonly CLASS_NAME = SATPHandlerType.STAGE2; private sessions: Map; @@ -54,30 +60,29 @@ export class Stage2SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Lock Assertion...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkLockAssertionRequestMessage(req, session); + await this.serverService.checkLockAssertionRequestMessage(req, session); + const message = await this.serverService.lockAssertionResponse( req, session, ); + this.Log.debug(`${fnTag}, Returning response: ${message}`); - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); if (!message) { - throw new Error(`${fnTag}, Failed to create LockAssertionReceipt`); + throw new FailedToCreateMessageError( + fnTag, + "LockAssertionImplementation", + ); } return message; } catch (error) { - throw new Error(`${fnTag}, Failed to process LockAssertion ${error}`); + throw new FailedToProcessError(fnTag, "LockAssertionImplementation"); } } @@ -97,13 +102,9 @@ export class Stage2SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Lock Assertion Request Message...`); this.Log.debug(`${fnTag}, Response: ${response}`); - if (!response.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(response.common?.sessionId); + const session = this.sessions.get(getSessionId(response)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } await this.clientService.checkTransferCommenceResponseMessage( @@ -119,13 +120,11 @@ export class Stage2SATPHandler implements SATPHandler { ); if (!request) { - throw new Error(`${fnTag}, Failed to create LockAssertionRequest`); + throw new FailedToCreateMessageError(fnTag, "LockAssertionRequest"); } return request; } catch (error) { - throw new Error( - `${fnTag}, Failed to process LockAssertionRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "LockAssertionRequest"); } } } 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 a24e083c8f..1290d632b6 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 @@ -18,6 +18,12 @@ import { import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; import { Empty } from "@bufbuild/protobuf"; import { Stage3ClientService } from "../stage-services/client/stage3-client-service"; +import { getSessionId } from "./handler-utils"; +import { + FailedToCreateMessageError, + FailedToProcessError, + SessionNotFoundError, +} from "../errors/satp-handler-errors"; export class Stage3SATPHandler implements SATPHandler { public static readonly CLASS_NAME = SATPHandlerType.STAGE3; @@ -58,34 +64,29 @@ export class Stage3SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Commit Preparation...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkCommitPreparationRequestMessage( - req, - session, - ); + await this.serverService.checkCommitPreparationRequestMessage( + req, + session, + ); await this.serverService.mintAsset(session); const message = await this.serverService.commitReady(req, session); this.Log.debug(`${fnTag}, Returning response: ${message}`); - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); - const response = new CommitReadyResponseMessage(); - return response; + if (!message) { + throw new FailedToCreateMessageError(fnTag, "CommitPreparationRequest"); + } + + return message; } catch (error) { - throw new Error( - `${fnTag}, Failed to process CommitPreparationRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "CommitPreparationRequest"); } } @@ -99,20 +100,15 @@ export class Stage3SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Commit Final Assertion...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkCommitFinalAssertionRequestMessage( - req, - session, - ); + await this.serverService.checkCommitFinalAssertionRequestMessage( + req, + session, + ); await this.serverService.assignAsset(session); @@ -121,15 +117,19 @@ export class Stage3SATPHandler implements SATPHandler { req, session, ); + this.Log.debug(`${fnTag}, Returning response: ${message}`); - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); - const response = new CommitFinalAcknowledgementReceiptResponseMessage(); - return response; + if (!message) { + throw new FailedToCreateMessageError( + fnTag, + "CommitFinalAssertionRequest", + ); + } + + return message; } catch (error) { - throw new Error( - `${fnTag}, Failed to process CommitFinalAssertionRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "CommitFinalAssertionRequest"); } } @@ -143,28 +143,19 @@ export class Stage3SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Transfer Complete...`); this.Log.debug(`${fnTag}, Request: ${req}, Context: ${context}`); - if (!req.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(req.common?.sessionId); + const session = this.sessions.get(getSessionId(req)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } - const sessionData = - await this.serverService.checkTransferCompleteRequestMessage( - req, - session, - ); - - this.Log.debug(`${fnTag}, Session Data: ${sessionData}`); + await this.serverService.checkTransferCompleteRequestMessage( + req, + session, + ); return new Empty({}); } catch (error) { - throw new Error( - `${fnTag}, Failed to process TransferCompleteRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferCompleteRequest"); } } @@ -187,13 +178,9 @@ export class Stage3SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Commit Preparation Request...`); this.Log.debug(`${fnTag}, Response: ${response}`); - if (!response.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(response.common?.sessionId); + const session = this.sessions.get(getSessionId(response)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } await this.clientService.checkCommitReadyResponseMessage( @@ -207,13 +194,11 @@ export class Stage3SATPHandler implements SATPHandler { ); if (!request) { - throw new Error(`${fnTag}, Failed to create TransferProposalRequest`); + throw new FailedToCreateMessageError(fnTag, "TransferProposalRequest"); } return request; } catch (error) { - throw new Error( - `${fnTag}, Failed to process commitPreparationRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferProposalRequest"); } } @@ -223,16 +208,12 @@ export class Stage3SATPHandler implements SATPHandler { const stepTag = `CommitFinalAssertionRequest()`; const fnTag = `${this.getHandlerIdentifier()}#${stepTag}`; try { - this.Log.debug(`${fnTag}, Commit Preparation Request...`); + this.Log.debug(`${fnTag}, Commit Final Assertion Request...`); this.Log.debug(`${fnTag}, Response: ${response}`); - if (!response.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(response.common?.sessionId); + const session = this.sessions.get(getSessionId(response)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } await this.clientService.checkCommitReadyResponseMessage( @@ -248,15 +229,14 @@ export class Stage3SATPHandler implements SATPHandler { ); if (!request) { - throw new Error( - `${fnTag}, Failed to create CommitFinalAssertionRequest`, + throw new FailedToCreateMessageError( + fnTag, + "CommitFinalAssertionRequest", ); } return request; } catch (error) { - throw new Error( - `${fnTag}, Failed to process CommitFinalAssertionRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "CommitFinalAssertionRequest"); } } @@ -269,13 +249,9 @@ export class Stage3SATPHandler implements SATPHandler { this.Log.debug(`${fnTag}, Transfer Complete Request...`); this.Log.debug(`${fnTag}, Response: ${response}`); - if (!response.common?.sessionId) { - throw new Error(`${fnTag}, Session Id not found`); - } - - const session = this.sessions.get(response.common?.sessionId); + const session = this.sessions.get(getSessionId(response)); if (!session) { - throw new Error(`${fnTag}, Session not found`); + throw new SessionNotFoundError(fnTag); } await this.clientService.checkCommitFinalAcknowledgementReceiptResponseMessage( @@ -289,13 +265,11 @@ export class Stage3SATPHandler implements SATPHandler { ); if (!request) { - throw new Error(`${fnTag}, Failed to create TransferCompleteRequest`); + throw new FailedToCreateMessageError(fnTag, "TransferCompleteRequest"); } return request; } catch (error) { - throw new Error( - `${fnTag}, Failed to process TransferCompleteRequest ${error}`, - ); + throw new FailedToProcessError(fnTag, "TransferCompleteRequest"); } } } diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage0-client-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage0-client-service.ts index 786c693aa7..9bd9a8b6de 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage0-client-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/client/stage0-client-service.ts @@ -1,29 +1,3 @@ -import { - TransferCommenceRequestMessage, - TransferProposalRequestMessage, - TransferProposalReceiptMessage, -} from "../../../generated/proto/cacti/satp/v02/stage_1_pb"; -import { - MessageType, - CommonSatp, - TransferClaims, - NetworkCapabilities, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SATP_VERSION } from "../../constants"; -import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { - getMessageHash, - saveHash, - saveSignature, - checkSessionData, -} from "../../session-utils"; -import { SupportedChain } from "../../types"; -import { SATPSession } from "../../../core/satp-session"; import { SATPService, SATPServiceType, @@ -48,361 +22,4 @@ export class Stage0ClientService extends SATPService { }; super(commonOptions); } - - async transferProposalRequest( - sessionID: string, - session: SATPSession, - supportedDLTs: SupportedChain[], - ): Promise { - const stepTag = `transferProposalRequest()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - const sessionData = session.getClientSessionData(); - - if (sessionData == undefined || !checkSessionData(sessionData)) { - throw new Error(`${fnTag}, session data is not correctly initialized`); - } - - if ( - !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`, - ); - } - - if (sessionData.version != SATP_VERSION) { - throw new Error(`${fnTag}, unsupported SATP version`); - } - - const commonBody = new CommonSatp(); - commonBody.version = sessionData.version; - commonBody.messageType = MessageType.PRE_INIT_PROPOSAL; - commonBody.sessionId = sessionData.id; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - commonBody.resourceUrl = ""; - - if (sessionData.transferContextId != undefined) { - commonBody.transferContextId = sessionData.transferContextId; - } - - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - commonBody.hashPreviousMessage = ""; - - const transferInitClaims = new TransferClaims(); - transferInitClaims.digitalAssetId = sessionData.digitalAssetId; - transferInitClaims.assetProfileId = sessionData.assetProfileId; - transferInitClaims.verifiedOriginatorEntityId = - sessionData.verifiedOriginatorEntityId; - transferInitClaims.verifiedBeneficiaryEntityId = - sessionData.verifiedBeneficiaryEntityId; - transferInitClaims.originatorPubkey = sessionData.originatorPubkey; - transferInitClaims.beneficiaryPubkey = sessionData.beneficiaryPubkey; - transferInitClaims.senderGatewayNetworkId = - sessionData.senderGatewayNetworkId; - transferInitClaims.recipientGatewayNetworkId = - sessionData.recipientGatewayNetworkId; - transferInitClaims.clientGatewayPubkey = sessionData.clientGatewayPubkey; - transferInitClaims.serverGatewayPubkey = sessionData.serverGatewayPubkey; - transferInitClaims.senderGatewayOwnerId = sessionData.senderGatewayOwnerId; - transferInitClaims.receiverGatewayOwnerId = - sessionData.receiverGatewayOwnerId; - - sessionData.hashTransferInitClaims = getHash(transferInitClaims); - - const networkCapabilities = new NetworkCapabilities(); - networkCapabilities.senderGatewayNetworkId = - sessionData.senderGatewayNetworkId; - networkCapabilities.signatureAlgorithm = sessionData.signatureAlgorithm; - networkCapabilities.lockType = sessionData.lockType; - networkCapabilities.lockExpirationTime = sessionData.lockExpirationTime; - networkCapabilities.credentialProfile = sessionData.credentialProfile; - networkCapabilities.loggingProfile = sessionData.loggingProfile; - networkCapabilities.accessControlProfile = sessionData.accessControlProfile; - - if (sessionData.permissions != undefined) { - this.Log.info(`${fnTag}, Optional variable loaded: permissions...`); - networkCapabilities.permissions = sessionData.permissions; - } - - if (sessionData.developerUrn != undefined) { - this.Log.info(`${fnTag}, Optional variable loaded: developerUrn...`); - networkCapabilities.developerUrn = sessionData.developerUrn; - } - - if (sessionData.applicationProfile != undefined) { - this.Log.info( - `${fnTag}, Optional variable loaded: applicationProfile...`, - ); - networkCapabilities.applicationProfile = sessionData.applicationProfile; - } - - if (sessionData.subsequentCalls != undefined) { - this.Log.info(`${fnTag}, Optional variable loaded: subsequentCalls...`); - networkCapabilities.subsequentCalls = sessionData.subsequentCalls; - } - - if (sessionData.history != undefined) { - this.Log.info(`${fnTag}, Optional variable loaded: history...`); - networkCapabilities.history = sessionData.history; - } - - const transferProposalRequestMessage = new TransferProposalRequestMessage(); - transferProposalRequestMessage.common = commonBody; - transferProposalRequestMessage.transferInitClaims = transferInitClaims; - transferProposalRequestMessage.networkCapabilities = networkCapabilities; - - if (sessionData.transferClaimsFormat != undefined) { - this.Log.info( - `${fnTag}, Optional variable loaded: transferInitClaimsFormat...`, - ); - transferProposalRequestMessage.transferInitClaimsFormat = - sessionData.transferClaimsFormat; - } - if (sessionData.multipleCancelsAllowed != undefined) { - this.Log.info( - `${fnTag}, Optional variable loaded: multipleCancelsAllowed...`, - ); - transferProposalRequestMessage.multipleCancelsAllowed = - sessionData.multipleCancelsAllowed; - } - if (sessionData.multipleClaimsAllowed != undefined) { - this.Log.info( - `${fnTag}, Optional variable loaded: multipleClaimsAllowed...`, - ); - transferProposalRequestMessage.multipleClaimsAllowed = - sessionData.multipleClaimsAllowed; - } - - const messageSignature = bufArray2HexStr( - sign(this.Signer, JSON.stringify(transferProposalRequestMessage)), - ); - - transferProposalRequestMessage.clientSignature = messageSignature; - - saveSignature(sessionData, MessageType.INIT_PROPOSAL, messageSignature); - - saveHash( - sessionData, - MessageType.INIT_PROPOSAL, - getHash(transferProposalRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionID, - type: "transferProposalRequest", - operation: "validate", - data: JSON.stringify(sessionData), - }); - */ - this.Log.info(`${fnTag}, sending TransferProposalRequest...`); - - return transferProposalRequestMessage; - } - - async transferCommenceRequest( - response: TransferProposalReceiptMessage, - session: SATPSession, - ): Promise { - const stepTag = `transferCommenceRequest()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - if (!response || !response.common) { - throw new Error("Response or response.common is undefined"); - } - - const sessionData = session.getClientSessionData(); - - if (sessionData == undefined) { - throw new Error("Session data not loaded successfully"); - } - - const commonBody = new CommonSatp(); - commonBody.version = sessionData.version; - commonBody.messageType = MessageType.TRANSFER_COMMENCE_REQUEST; - commonBody.sequenceNumber = response.common.sequenceNumber + BigInt(1); - - //todo check when reject - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.INIT_RECEIPT, - ); - - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - commonBody.sessionId = sessionData.id; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const transferCommenceRequestMessage = new TransferCommenceRequestMessage(); - transferCommenceRequestMessage.common = commonBody; - transferCommenceRequestMessage.hashTransferInitClaims = - sessionData.hashTransferInitClaims; - - // transferCommenceRequestMessage.clientTransferNumber = sessionData.clientTransferNumber; - - const messageSignature = bufArray2HexStr( - sign(this.Signer, JSON.stringify(transferCommenceRequestMessage)), - ); - - transferCommenceRequestMessage.clientSignature = messageSignature; - - saveSignature( - sessionData, - MessageType.TRANSFER_COMMENCE_REQUEST, - messageSignature, - ); - - saveHash( - sessionData, - MessageType.TRANSFER_COMMENCE_REQUEST, - getHash(transferCommenceRequestMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "transferCommenceRequest", - operation: "validate", - data: JSON.stringify(sessionData), - }); - */ - this.Log.info(`${fnTag}, sending TransferCommenceRequest...`); - - return transferCommenceRequestMessage; - } - - async checkTransferProposalReceiptMessage( - response: TransferProposalReceiptMessage, - session: SATPSession, - ): Promise { - const stepTag = `checkTransferProposalReceiptMessage()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - if (response.common == undefined) { - throw new Error(`${fnTag}, message has no satp common body`); - } - - if ( - response.common.version == undefined || - response.common.sequenceNumber == undefined || - response.common.hashPreviousMessage == undefined || - response.timestamp == undefined - ) { - throw new Error(`${fnTag}, satp common body is missing required fields`); - } - - // const sessionId = response.common.sessionId; - - const sessionData = session.getClientSessionData(); - - 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 loaded correctly`); - } - - if (response.common.version != sessionData.version) { - throw new Error(`${fnTag}, TransferCommenceRequest version mismatch`); - } - - if ( - response.common.messageType != MessageType.INIT_RECEIPT && - response.common.messageType != MessageType.INIT_REJECT - ) { - throw new Error( - `${fnTag}, wrong message type for TransferCommenceRequest()`, - ); - } - - if ( - response.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt Message sequence number is wrong`, - ); - } - - if ( - response.common.hashPreviousMessage == undefined || - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.INIT_PROPOSAL) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt previous message hash does not match the one that was sent`, - ); - } - - if ( - response.common.serverGatewayPubkey != sessionData.serverGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt serverIdentity public key does not match the one that was sent`, - ); - } - - if ( - response.common.clientGatewayPubkey != sessionData.clientGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt clientIdentity public key does not match the one that was sent`, - ); - } - - if ( - !verifySignature(this.Signer, response, sessionData.serverGatewayPubkey) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt message signature verification failed`, - ); - } - - if ( - response.common.messageType == MessageType.INIT_REJECT && - response.transferCounterClaims == undefined - ) { - sessionData.completed = true; - return false; - } else if ( - response.common.messageType == MessageType.INIT_REJECT && - response.transferCounterClaims != undefined - ) { - if ( - await this.checkProposedTransferClaims(response.transferCounterClaims) - ) { - sessionData.proposedTransferInitClaims = getHash( - response.transferCounterClaims, - ); - return true; - } else { - this.Log.info( - `TransferProposalReceipt proposedTransferClaims were rejected`, - ); - sessionData.completed = true; - return false; - } - } - this.Log.info(`TransferProposalReceipt passed all checks.`); - return true; - } - - async checkProposedTransferClaims( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - counterTransfer: TransferClaims, - ): Promise { - //const fnTag = `${this.className}#checkCounterTransferClaims()`; - //todo - return true; - } } 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 2d6caeaa19..c371aecaaf 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 @@ -9,18 +9,12 @@ import { TransferClaims, NetworkCapabilities, } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SATP_VERSION } from "../../constants"; -import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; +import { bufArray2HexStr, getHash, sign } from "../../../gateway-utils"; import { getMessageHash, saveHash, saveSignature, - checkSessionData, + SessionType, } from "../../session-utils"; import { SupportedChain } from "../../types"; import { SATPSession } from "../../../core/satp-session"; @@ -30,6 +24,9 @@ import { ISATPClientServiceOptions, ISATPServiceOptions, } from "../satp-service"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; +import { ACCEPTANCE } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; +import { SessionError } from "../../errors/satp-service-errors"; export class Stage1ClientService extends SATPService { public static readonly SATP_STAGE = "1"; @@ -57,12 +54,14 @@ export class Stage1ClientService extends SATPService { const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, transferProposalRequest...`); - const sessionData = session.getClientSessionData(); - - if (sessionData == undefined || !checkSessionData(sessionData)) { - throw new Error(`${fnTag}, session data is not correctly initialized`); + if (session == undefined) { + throw new SessionError(fnTag); } + session.verify(fnTag, SessionType.CLIENT); + + const sessionData = session.getClientSessionData(); + if ( !supportedDLTs.includes( sessionData.senderGatewayNetworkId as SupportedChain, @@ -73,17 +72,13 @@ export class Stage1ClientService extends SATPService { ); } - if (sessionData.version != SATP_VERSION) { - throw new Error(`${fnTag}, unsupported SATP version`); - } - const commonBody = new CommonSatp(); commonBody.version = sessionData.version; commonBody.messageType = MessageType.INIT_PROPOSAL; commonBody.sessionId = sessionData.id; commonBody.sequenceNumber = sessionData.lastSequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - commonBody.resourceUrl = ""; + commonBody.resourceUrl = sessionData.resourceUrl; if (sessionData.transferContextId != undefined) { commonBody.transferContextId = sessionData.transferContextId; @@ -213,20 +208,18 @@ export class Stage1ClientService extends SATPService { const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, transferCommenceRequest...`); - if (!response || !response.common) { - throw new Error("Response or response.common is undefined"); + if (session == undefined) { + throw new SessionError(fnTag); } - const sessionData = session.getClientSessionData(); + session.verify(fnTag, SessionType.CLIENT); - if (sessionData == undefined) { - throw new Error("Session data not loaded successfully"); - } + const sessionData = session.getClientSessionData(); const commonBody = new CommonSatp(); commonBody.version = sessionData.version; commonBody.messageType = MessageType.TRANSFER_COMMENCE_REQUEST; - commonBody.sequenceNumber = response.common.sequenceNumber + BigInt(1); + commonBody.sequenceNumber = response.common!.sequenceNumber + BigInt(1); //todo check when reject commonBody.hashPreviousMessage = getMessageHash( @@ -238,6 +231,7 @@ export class Stage1ClientService extends SATPService { commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; commonBody.sessionId = sessionData.id; commonBody.transferContextId = sessionData.transferContextId; + commonBody.resourceUrl = sessionData.resourceUrl; sessionData.lastSequenceNumber = commonBody.sequenceNumber; @@ -246,8 +240,6 @@ export class Stage1ClientService extends SATPService { transferCommenceRequestMessage.hashTransferInitClaims = sessionData.hashTransferInitClaims; - // transferCommenceRequestMessage.clientTransferNumber = sessionData.clientTransferNumber; - const messageSignature = bufArray2HexStr( sign(this.Signer, JSON.stringify(transferCommenceRequestMessage)), ); @@ -286,102 +278,42 @@ export class Stage1ClientService extends SATPService { const stepTag = `checkTransferProposalReceiptMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkTransferProposalReceiptMessage...`); - if (response.common == undefined) { - throw new Error(`${fnTag}, message has no satp common body`); - } - if ( - response.common.version == undefined || - response.common.sequenceNumber == undefined || - response.common.hashPreviousMessage == undefined || - response.timestamp == undefined - ) { - throw new Error(`${fnTag}, satp common body is missing required fields`); + if (session == undefined) { + throw new SessionError(fnTag); } - // const sessionId = response.common.sessionId; + session.verify(fnTag, SessionType.CLIENT); const sessionData = session.getClientSessionData(); - 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 loaded correctly`); - } - - if (response.common.version != sessionData.version) { - throw new Error(`${fnTag}, TransferCommenceRequest version mismatch`); - } - - if ( - response.common.messageType != MessageType.INIT_RECEIPT && - response.common.messageType != MessageType.INIT_REJECT - ) { - throw new Error( - `${fnTag}, wrong message type for TransferCommenceRequest()`, - ); - } - - if ( - response.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt Message sequence number is wrong got: ${response.common.sequenceNumber} expected to be ${sessionData.lastSequenceNumber + BigInt(1)}`, - ); - } - - if ( - response.common.hashPreviousMessage == undefined || - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.INIT_PROPOSAL) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt previous message hash does not match the one that was sent`, - ); - } - - if ( - response.common.serverGatewayPubkey != sessionData.serverGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt serverIdentity public key does not match the one that was sent`, - ); - } - - if ( - response.common.clientGatewayPubkey != sessionData.clientGatewayPubkey - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt clientIdentity public key does not match the one that was sent`, - ); - } + commonBodyVerifier( + fnTag, + response.common, + sessionData, + MessageType.INIT_RECEIPT, + MessageType.INIT_REJECT, + ); - if ( - !verifySignature(this.Signer, response, sessionData.serverGatewayPubkey) - ) { - throw new Error( - `${fnTag}, TransferProposalReceipt message signature verification failed`, - ); - } + signatureVerifier(fnTag, this.Signer, response, sessionData); if ( - response.common.messageType == MessageType.INIT_REJECT && + response.common!.messageType == MessageType.INIT_REJECT && response.transferCounterClaims == undefined ) { + this.Log.info( + `${fnTag}, TransferProposalReceipt proposedTransferClaims were rejected`, + ); + sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_REJECTED; sessionData.completed = true; + saveHash(sessionData, MessageType.INIT_REJECT, getHash(response)); return false; } else if ( - response.common.messageType == MessageType.INIT_REJECT && + response.common!.messageType == MessageType.INIT_REJECT && response.transferCounterClaims != undefined ) { + sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_CONDITIONAL; + saveHash(sessionData, MessageType.INIT_REJECT, getHash(response)); if ( await this.checkProposedTransferClaims(response.transferCounterClaims) ) { @@ -391,13 +323,14 @@ export class Stage1ClientService extends SATPService { return true; } else { this.Log.info( - `${fnTag}, TransferProposalReceipt proposedTransferClaims were rejected`, + `${fnTag}, TransferProposalReceipt proposedTransferClaims were rejected conditional`, ); sessionData.completed = true; return false; } } + sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_ACCEPTED; saveHash(sessionData, MessageType.INIT_RECEIPT, getHash(response)); this.Log.info(`${fnTag}, TransferProposalReceipt passed all checks.`); 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 33e7122a9f..7a5a96a137 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,5 +1,4 @@ import { TransferCommenceResponseMessage } from "../../../generated/proto/cacti/satp/v02/stage_1_pb"; -import { SATP_VERSION } from "../../constants"; import { CommonSatp, LockAssertionClaim, @@ -7,13 +6,13 @@ import { 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 } from "../../../gateway-utils"; import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; + getMessageHash, + saveHash, + saveSignature, + SessionType, +} from "../../session-utils"; import { SATPSession } from "../../../core/satp-session"; import { SATPService, @@ -22,23 +21,14 @@ import { } from "../satp-service"; import { ISATPServiceOptions } from "../satp-service"; import { SATPBridgesManager } from "../../../gol/satp-bridges-manager"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; import { - HashMissMatch, - MessageTypeMissMatch, - MissingBridgeManager, - MissingClientGatewayPubkey, - MissingLockAssertionClaim, - MissingLockAssertionClaimFormat, - MissingLockAssertionExpiration, - MissingSatpCommonBody, - MissingServerGatewayPubkey, - SATPVersionUnsupported, - SequenceNumberMissMatch, - SessionDataNotLoadedCorrectly, - SessionUndefined, - SignatureVerificationFailed, - TransferContextIdMissMatch, -} from "../errors"; + LockAssertionExpirationError, + MissingBridgeManagerError, + LockAssertionClaimError, + LockAssertionClaimFormatError, + SessionError, +} from "../../errors/satp-service-errors"; export class Stage2ClientService extends SATPService { public static readonly SATP_STAGE = "2"; @@ -59,7 +49,9 @@ export class Stage2ClientService extends SATPService { super(commonOptions); if (ops.bridgeManager == undefined) { - throw MissingBridgeManager(`${this.getServiceIdentifier()}#constructor`); + throw new MissingBridgeManagerError( + `${this.getServiceIdentifier()}#constructor`, + ); } this.bridgeManager = ops.bridgeManager; } @@ -73,50 +65,49 @@ export class Stage2ClientService extends SATPService { this.Log.debug(`${fnTag}, lockAssertionRequest...`); if (session == undefined) { - throw SessionUndefined(`${fnTag}`); + throw new SessionError(fnTag); } - if (response.common == undefined) { - throw MissingSatpCommonBody(`${fnTag}`); - } + session.verify(fnTag, SessionType.CLIENT); const sessionData = session.getClientSessionData(); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(`${fnTag}`); - } - const commonBody = new CommonSatp(); commonBody.version = sessionData.version; commonBody.messageType = MessageType.LOCK_ASSERT; sessionData.lastSequenceNumber = commonBody.sequenceNumber = - response.common.sequenceNumber + BigInt(1); + response.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE, ); - commonBody.sessionId = response.common.sessionId; + //response was already verified in the check function so we can use ! to tell TS to trust us + commonBody.sessionId = response.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; const lockAssertionRequestMessage = new LockAssertionRequestMessage(); lockAssertionRequestMessage.common = commonBody; if (sessionData.lockAssertionClaim == undefined) { - throw MissingLockAssertionClaim(fnTag); + throw new LockAssertionClaimError(fnTag); } lockAssertionRequestMessage.lockAssertionClaim = sessionData.lockAssertionClaim; if (sessionData.lockAssertionClaimFormat == undefined) { - throw MissingLockAssertionClaimFormat(fnTag); + throw new LockAssertionClaimFormatError(fnTag); } lockAssertionRequestMessage.lockAssertionClaimFormat = sessionData.lockAssertionClaimFormat; - if (sessionData.lockAssertionExpiration == undefined) { - throw MissingLockAssertionExpiration(fnTag); + if ( + sessionData.lockAssertionExpiration == undefined || + sessionData.lockAssertionExpiration == BigInt(0) + ) { + throw new LockAssertionExpirationError(fnTag); } lockAssertionRequestMessage.lockAssertionExpiration = @@ -158,106 +149,30 @@ export class Stage2ClientService extends SATPService { return lockAssertionRequestMessage; } - checkTransferCommenceResponseMessage( + async checkTransferCommenceResponseMessage( response: TransferCommenceResponseMessage, session: SATPSession, - ): void { + ): Promise { const stepTag = `checkTransferCommenceResponseMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkTransferCommenceResponseMessage...`); - if ( - response.common == undefined || - response.common.version == undefined || - response.common.messageType == undefined || - response.common.sessionId == undefined || - response.common.sequenceNumber == undefined || - response.common.resourceUrl == undefined || - response.serverSignature == undefined || - response.common.clientGatewayPubkey == undefined || - response.common.serverGatewayPubkey == undefined || - response.common.hashPreviousMessage == undefined - ) { - throw MissingSatpCommonBody(fnTag); + if (session == undefined) { + throw new SessionError(fnTag); } - if (response.common.version != SATP_VERSION) { - throw SATPVersionUnsupported( - fnTag, - response.common.version, - SATP_VERSION, - ); - } + session.verify(fnTag, SessionType.CLIENT); const sessionData = session.getClientSessionData(); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if ( - response.common.serverGatewayPubkey != sessionData.serverGatewayPubkey - ) { - throw MissingServerGatewayPubkey(fnTag); - } - - if ( - response.common.clientGatewayPubkey != sessionData.clientGatewayPubkey - ) { - throw MissingClientGatewayPubkey(fnTag); - } - - if ( - !verifySignature( - this.Signer, - response, - response.common.serverGatewayPubkey, - ) - ) { - throw SignatureVerificationFailed(fnTag); - } - - if (response.common.messageType != MessageType.TRANSFER_COMMENCE_RESPONSE) { - throw MessageTypeMissMatch( - fnTag, - response.common.messageType.toString(), - MessageType.TRANSFER_COMMENCE_RESPONSE.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber == undefined || - response.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw SequenceNumberMissMatch( - fnTag, - response.common.sequenceNumber, - sessionData.lastSequenceNumber, - ); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_REQUEST) - ) { - throw HashMissMatch( - fnTag, - response.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_REQUEST), - ); - } + commonBodyVerifier( + fnTag, + response.common, + sessionData, + MessageType.TRANSFER_COMMENCE_RESPONSE, + ); - if ( - sessionData.transferContextId != undefined && - response.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - response.common.transferContextId, - sessionData.transferContextId, - ); - } + signatureVerifier(fnTag, this.Signer, response, sessionData); if (response.serverTransferNumber != undefined) { this.Log.info( @@ -280,12 +195,17 @@ export class Stage2ClientService extends SATPService { const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; try { this.Log.info(`${fnTag}, Locking Asset...`); - const sessionData = session.getClientSessionData(); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); + + if (session == undefined) { + throw new SessionError(fnTag); } - const assetId = sessionData.transferInitClaims?.digitalAssetId; - const amount = sessionData.transferInitClaims?.amountFromOriginator; + + session.verify(fnTag, SessionType.CLIENT); + + const sessionData = session.getClientSessionData(); + + const assetId = sessionData?.transferInitClaims?.digitalAssetId; + const amount = sessionData?.transferInitClaims?.amountFromOriginator; this.Log.debug(`${fnTag}, Lock Asset ID: ${assetId} amount: ${amount}`); if (assetId == undefined) { 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 f19cb6877f..e7674a09b3 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 @@ -11,13 +11,13 @@ import { CommitReadyResponseMessage, TransferCompleteRequestMessage, } from "../../../generated/proto/cacti/satp/v02/stage_3_pb"; +import { bufArray2HexStr, getHash, sign } from "../../../gateway-utils"; import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; + getMessageHash, + saveHash, + saveSignature, + SessionType, +} from "../../session-utils"; import { SATPService, ISATPClientServiceOptions, @@ -27,23 +27,14 @@ import { import { SATPSession } from "../../satp-session"; import { LockAssertionReceiptMessage } from "../../../generated/proto/cacti/satp/v02/stage_2_pb"; import { SATPBridgesManager } from "../../../gol/satp-bridges-manager"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; import { - HashMissMatch, - MessageTypeMissMatch, - MissingAssignmentAssertionClaim, - MissingBridgeManager, - MissingBurnAssertionClaim, - MissingClientGatewayPubkey, - MissingMintAssertionClaim, - MissingSatpCommonBody, - MissingServerGatewayPubkey, - SATPVersionUnsupported, - SequenceNumberMissMatch, - SessionDataNotLoadedCorrectly, - SessionUndefined, - SignatureVerificationFailed, - TransferContextIdMissMatch, -} from "../errors"; + AssignmentAssertionClaimError, + BurnAssertionClaimError, + MintAssertionClaimError, + MissingBridgeManagerError, + SessionError, +} from "../../errors/satp-service-errors"; export class Stage3ClientService extends SATPService { public static readonly SATP_STAGE = "3"; @@ -64,7 +55,9 @@ export class Stage3ClientService extends SATPService { super(commonOptions); if (ops.bridgeManager == undefined) { - throw MissingBridgeManager(`${this.getServiceIdentifier()}#constructor`); + throw new MissingBridgeManagerError( + `${this.getServiceIdentifier()}#constructor`, + ); } this.bridgeManager = ops.bridgeManager; } @@ -78,31 +71,26 @@ export class Stage3ClientService extends SATPService { this.Log.debug(`${fnTag}, CommitPreparation...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getClientSessionData(); + session.verify(fnTag, SessionType.CLIENT); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getClientSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.COMMIT_PREPARE; sessionData.lastSequenceNumber = commonBody.sequenceNumber = - response.common.sequenceNumber + BigInt(1); + response.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.ASSERTION_RECEIPT, ); - commonBody.sessionId = response.common.sessionId; + commonBody.sessionId = response.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; const commitPreparationRequestMessage = new CommitPreparationRequestMessage(); @@ -155,39 +143,34 @@ export class Stage3ClientService extends SATPService { this.Log.debug(`${fnTag}, CommitFinalAssertion...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getClientSessionData(); + session.verify(fnTag, SessionType.CLIENT); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getClientSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.COMMIT_FINAL; sessionData.lastSequenceNumber = commonBody.sequenceNumber = - response.common.sequenceNumber + BigInt(1); + response.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.COMMIT_READY, ); - commonBody.sessionId = response.common.sessionId; + commonBody.sessionId = response.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; const commitFinalAssertionRequestMessage = new CommitFinalAssertionRequestMessage(); commitFinalAssertionRequestMessage.common = commonBody; if (sessionData.burnAssertionClaim == undefined) { - throw MissingBurnAssertionClaim(fnTag); + throw new BurnAssertionClaimError(fnTag); } commitFinalAssertionRequestMessage.burnAssertionClaim = @@ -244,31 +227,27 @@ export class Stage3ClientService extends SATPService { this.Log.debug(`${fnTag}, TransferComplete...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getClientSessionData(); + session.verify(fnTag, SessionType.CLIENT); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getClientSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.COMMIT_TRANSFER_COMPLETE; + commonBody.resourceUrl = sessionData.resourceUrl; + sessionData.lastSequenceNumber = commonBody.sequenceNumber = - response.common.sequenceNumber + BigInt(1); + response.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.ACK_COMMIT_FINAL, ); - commonBody.sessionId = response.common.sessionId; + commonBody.sessionId = response.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; @@ -322,112 +301,30 @@ export class Stage3ClientService extends SATPService { return transferCompleteRequestMessage; } - checkLockAssertionReceiptMessage( + async checkLockAssertionReceiptMessage( response: LockAssertionReceiptMessage, session: SATPSession, - ): void { + ): Promise { const stepTag = `checkLockAssertionReceiptMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, CheckLockAssertionReceiptMessage...`); if (session == undefined) { - throw SessionUndefined(fnTag); - } - - const sessionData = session.getClientSessionData(); - - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (response.common.version != SATP_VERSION) { - throw SATPVersionUnsupported( - fnTag, - response.common.version, - SATP_VERSION, - ); - } - - if (response.common.messageType != MessageType.ASSERTION_RECEIPT) { - throw MessageTypeMissMatch( - fnTag, - response.common.messageType.toString(), - MessageType.ASSERTION_RECEIPT.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( - fnTag, - response.common.sequenceNumber, - sessionData.lastSequenceNumber + BigInt(1), - ); + throw new SessionError(fnTag); } - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.LOCK_ASSERT) - ) { - throw HashMissMatch( - fnTag, - response.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.LOCK_ASSERT), - ); - } + session.verify(fnTag, SessionType.CLIENT); - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw MissingClientGatewayPubkey(fnTag); - } - - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw MissingClientGatewayPubkey(fnTag); - } + const sessionData = session.getClientSessionData(); - if ( - !verifySignature( - this.Signer, - response, - response.common.serverGatewayPubkey, - ) - ) { - throw SignatureVerificationFailed(fnTag); - } + commonBodyVerifier( + fnTag, + response.common, + sessionData, + MessageType.ASSERTION_RECEIPT, + ); - if ( - sessionData.transferContextId != undefined && - response.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - response.common.transferContextId, - sessionData.transferContextId, - ); - } - - if ( - sessionData.serverTransferNumber != undefined && - response.serverTransferNumber != sessionData.serverTransferNumber - ) { - // This does not throw an error because the serverTransferNumber is only meaningful to the server. - this.Log.info( - `${fnTag}, serverTransferNumber does not match the one that was sent`, - ); - } + signatureVerifier(fnTag, this.Signer, response, sessionData); if ( sessionData.serverTransferNumber != undefined && @@ -444,91 +341,30 @@ export class Stage3ClientService extends SATPService { this.Log.info(`${fnTag}, LockAssertionReceiptMessage passed all checks.`); } - checkCommitReadyResponseMessage( + async checkCommitReadyResponseMessage( response: CommitReadyResponseMessage, session: SATPSession, - ): void { + ): Promise { const stepTag = `checkCommitReadyResponseMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, CommitReadyResponse...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getClientSessionData(); + session.verify(fnTag, SessionType.CLIENT); - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (response.common.version != SATP_VERSION) { - throw SATPVersionUnsupported( - fnTag, - response.common.version, - SATP_VERSION, - ); - } - - if (response.common.messageType != MessageType.COMMIT_READY) { - throw MessageTypeMissMatch( - fnTag, - response.common.messageType.toString(), - MessageType.COMMIT_READY.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( - fnTag, - response.common.sequenceNumber, - sessionData.lastSequenceNumber + BigInt(1), - ); - } - - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.COMMIT_PREPARE) - ) { - throw HashMissMatch( - fnTag, - response.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.COMMIT_PREPARE), - ); - } - - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw MissingClientGatewayPubkey(fnTag); - } + const sessionData = session.getClientSessionData(); - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw MissingServerGatewayPubkey(fnTag); - } + commonBodyVerifier( + fnTag, + response.common, + sessionData, + MessageType.COMMIT_READY, + ); - if ( - !verifySignature( - this.Signer, - response, - response.common.serverGatewayPubkey, - ) - ) { - throw SignatureVerificationFailed(fnTag); - } + signatureVerifier(fnTag, this.Signer, response, sessionData); if (response.mintAssertionClaimFormat != undefined) { //todo @@ -540,22 +376,11 @@ export class Stage3ClientService extends SATPService { if (response.mintAssertionClaim == undefined) { //todo - throw MissingMintAssertionClaim(fnTag); + throw new MintAssertionClaimError(fnTag); } sessionData.mintAssertionClaim = response.mintAssertionClaim; - if ( - sessionData.transferContextId != undefined && - response.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - response.common.transferContextId, - sessionData.transferContextId, - ); - } - if ( sessionData.serverTransferNumber != undefined && response.serverTransferNumber != sessionData.serverTransferNumber @@ -571,105 +396,33 @@ export class Stage3ClientService extends SATPService { this.Log.info(`${fnTag}, CommitReadyResponseMessage passed all checks.`); } - checkCommitFinalAcknowledgementReceiptResponseMessage( + async checkCommitFinalAcknowledgementReceiptResponseMessage( response: CommitFinalAcknowledgementReceiptResponseMessage, session: SATPSession, - ): void { + ): Promise { const stepTag = `checkCommitFinalAcknowledgementReceiptResponseMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, CommitFinalAcknowledgementReceipt...`); if (session == undefined) { - throw SessionUndefined(fnTag); - } - - const sessionData = session.getClientSessionData(); - - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (response.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (response.common.version != SATP_VERSION) { - throw SATPVersionUnsupported( - fnTag, - response.common.version, - SATP_VERSION, - ); - } - - if (response.common.messageType != MessageType.ACK_COMMIT_FINAL) { - throw MessageTypeMissMatch( - fnTag, - response.common.messageType.toString(), - MessageType.ACK_COMMIT_FINAL.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - response.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( - fnTag, - response.common.sequenceNumber, - sessionData.lastSequenceNumber + BigInt(1), - ); + throw new SessionError(fnTag); } - if ( - response.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.COMMIT_FINAL) - ) { - throw HashMissMatch( - fnTag, - response.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.COMMIT_FINAL), - ); - } - - if ( - sessionData.clientGatewayPubkey != response.common.clientGatewayPubkey - ) { - throw MissingClientGatewayPubkey(fnTag); - } + session.verify(fnTag, SessionType.CLIENT); - if ( - sessionData.serverGatewayPubkey != response.common.serverGatewayPubkey - ) { - throw MissingServerGatewayPubkey(fnTag); - } + const sessionData = session.getClientSessionData(); - if ( - !verifySignature( - this.Signer, - response, - response.common.serverGatewayPubkey, - ) - ) { - throw SignatureVerificationFailed(fnTag); - } + commonBodyVerifier( + fnTag, + response.common, + sessionData, + MessageType.ACK_COMMIT_FINAL, + ); - if ( - sessionData.transferContextId != undefined && - response.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - response.common.transferContextId, - sessionData.transferContextId, - ); - } + signatureVerifier(fnTag, this.Signer, response, sessionData); if (response.assignmentAssertionClaim == undefined) { - throw MissingAssignmentAssertionClaim(fnTag); + throw new AssignmentAssertionClaimError(fnTag); } sessionData.assignmentAssertionClaim = response.assignmentAssertionClaim; @@ -683,7 +436,7 @@ export class Stage3ClientService extends SATPService { } if ( - sessionData.serverTransferNumber != undefined && + sessionData.serverTransferNumber != "" && response.serverTransferNumber != sessionData.serverTransferNumber ) { // This does not throw an error because the serverTransferNumber is only meaningful to the server. @@ -704,10 +457,15 @@ export class Stage3ClientService extends SATPService { const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; try { this.Log.debug(`${fnTag}, Burning Asset...`); - const sessionData = session.getClientSessionData(); - if (sessionData == undefined) { - throw new Error(`${fnTag}, Session data is missing`); + + if (session == undefined) { + throw new SessionError(fnTag); } + + session.verify(fnTag, SessionType.CLIENT); + + const sessionData = session.getClientSessionData(); + const assetId = sessionData.transferInitClaims?.digitalAssetId; const amount = sessionData.transferInitClaims?.amountFromOriginator; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/data-verifier.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/data-verifier.ts new file mode 100644 index 0000000000..c82bfe7438 --- /dev/null +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/data-verifier.ts @@ -0,0 +1,140 @@ +import { JsObjectSigner } from "@hyperledger/cactus-common"; +import { verifySignature } from "../../gateway-utils"; +import { + CommonSatp, + MessageType, +} from "../../generated/proto/cacti/satp/v02/common/message_pb"; +import { SessionData } from "../../generated/proto/cacti/satp/v02/common/session_pb"; +import { SATP_VERSION } from "../constants"; +import { + ClientGatewayPubkeyError, + HashError, + MessageTypeError, + ResourceUrlError, + SatpCommonBodyError, + SATPVersionError, + SequenceNumberError, + ServerGatewayPubkeyError, + SessionDataNotLoadedCorrectlyError, + SignatureMissingError, + SignatureVerificationError, + TransferContextIdError, +} from "../errors/satp-service-errors"; +import { getMessageHash, getPreviousMessageType } from "../session-utils"; + +export function commonBodyVerifier( + tag: string, + common: CommonSatp | undefined, + sessionData: SessionData | undefined, + messageStage: MessageType, + messageStage2?: MessageType, // this is only used in stage 1 when the message received can be either or 2 types +): void { + if (sessionData == undefined) { + throw new SessionDataNotLoadedCorrectlyError(tag, "undefined"); + } + + if (common == undefined) { + throw new SatpCommonBodyError(tag, "undefined"); + } + + if ( + common.version == "" || + common.messageType == undefined || + common.sessionId == "" || + common.sequenceNumber == undefined || + common.resourceUrl == "" || + common.clientGatewayPubkey == "" || + common.serverGatewayPubkey == "" || + (common.hashPreviousMessage == "" && + messageStage != MessageType.INIT_PROPOSAL) + ) { + throw new SatpCommonBodyError(tag, JSON.stringify(common)); + } + + if (common.version != SATP_VERSION) { + throw new SATPVersionError(tag, common.version, SATP_VERSION); + } + + if (common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { + throw new ServerGatewayPubkeyError(tag); + } + + if (common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { + throw new ClientGatewayPubkeyError(tag); + } + + if (common.sequenceNumber != sessionData.lastSequenceNumber + BigInt(1)) { + throw new SequenceNumberError( + tag, + common.sequenceNumber, + sessionData.lastSequenceNumber, + ); + } + + if (common.transferContextId != sessionData.transferContextId) { + throw new TransferContextIdError( + tag, + common.transferContextId, + sessionData.transferContextId, + ); + } + + if (common.resourceUrl != sessionData.resourceUrl) { + throw new ResourceUrlError(tag); + } + + if ( + common.messageType != messageStage && + common.messageType != messageStage2 + ) { + throw new MessageTypeError( + tag, + common.messageType.toString(), + messageStage.toString(), + ); + } + + if ( + common.hashPreviousMessage != + getMessageHash( + sessionData, + getPreviousMessageType(sessionData, messageStage), + ) + ) { + throw new HashError( + tag, + common.hashPreviousMessage, + getMessageHash( + sessionData, + getPreviousMessageType(sessionData, messageStage), + ), + ); + } +} + +export function signatureVerifier( + tag: string, + signer: JsObjectSigner, + message: any, + sessionData: SessionData | undefined, +) { + if (sessionData == undefined) { + throw new SessionDataNotLoadedCorrectlyError(tag, "undefined"); + } + + if (message.serverSignature != "") { + if ( + !verifySignature(signer, message, sessionData?.serverGatewayPubkey || "") + ) { + throw new SignatureVerificationError(tag); + } + } else if (message.clientSignature != "") { + if ( + !verifySignature(signer, message, sessionData?.clientGatewayPubkey || "") + ) { + throw new SignatureVerificationError(tag); + } + } else { + throw new SignatureMissingError(tag); + } +} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/errors.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/errors.ts deleted file mode 100644 index da52363ef3..0000000000 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/errors.ts +++ /dev/null @@ -1,117 +0,0 @@ -export function MissingSatpCommonBody(fnTag: string): Error { - return new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); -} - -export function SessionUndefined(fnTag: string): Error { - return new Error(`${fnTag}, session undefined`); -} - -export function SessionDataNotLoadedCorrectly(fnTag: string): Error { - return new Error(`${fnTag}, session data was not load correctly`); -} - -export function SATPVersionUnsupported( - fnTag: string, - unsupported: string, - supported: string, -): Error { - return new Error( - `${fnTag}, unsupported SATP version \n received: ${unsupported}, supported: ${supported}`, - ); -} - -export function SignatureVerificationFailed(fnTag: string): Error { - return new Error(`${fnTag}, message signature verification failed`); -} - -export function MessageTypeMissMatch( - fnTag: string, - received: string, - expected: string, -): Error { - return new Error( - `${fnTag}, message type miss match \n received: ${received} \n expected: ${expected}`, - ); -} - -export function MissingTransferInitClaims(fnTag: string): Error { - return new Error(`${fnTag}, transferInitClaims missing or missmatch`); -} - -export function MissingNetworkCapabilities(fnTag: string): Error { - return new Error( - `${fnTag}, message does not contain network capabilities and parameters`, - ); -} - -export function DLTNotSupported(fnTag: string, dlt: string): Error { - return new Error(`${fnTag}, DLT not supported \n received: ${dlt}`); -} - -export function MissingServerGatewayPubkey(fnTag: string): Error { - return new Error(`${fnTag}, serverGatewayPubkey missing or missmatch`); -} - -export function MissingClientGatewayPubkey(fnTag: string): Error { - return new Error(`${fnTag}, clientGatewayPubkey missing or missmatch`); -} - -export function SequenceNumberMissMatch( - fnTag: string, - received: bigint, - expected: bigint, -): Error { - return new Error( - `${fnTag}, sequence number missmatch \n received: ${received} \n expected: ${expected}`, - ); -} - -export function HashMissMatch( - fnTag: string, - received: string, - expected: string, -): Error { - return new Error( - `${fnTag}, hash missmatch \n received: ${received} \n expected: ${expected}`, - ); -} - -export function TransferContextIdMissMatch( - fnTag: string, - received: string, - expected: string, -): Error { - return new Error( - `${fnTag}, transferContextId missing or missmatch \n received: ${received} \n expected: ${expected}`, - ); -} - -export function MissingBridgeManager(fnTag: string): Error { - return new Error(`${fnTag}, bridge manager missing`); -} - -export function MissingLockAssertionClaim(fnTag: string): Error { - return new Error(`${fnTag}, lockAssertionClaim missing`); -} - -export function MissingLockAssertionClaimFormat(fnTag: string): Error { - return new Error(`${fnTag}, lockAssertionClaimFormat missing`); -} - -export function MissingLockAssertionExpiration(fnTag: string): Error { - return new Error(`${fnTag}, lockAssertionExpiration missing`); -} - -export function MissingBurnAssertionClaim(fnTag: string): Error { - return new Error(`${fnTag}, burnAssertionClaim missing`); -} - -export function MissingMintAssertionClaim(fnTag: string): Error { - return new Error(`${fnTag}, mintAssertionClaim missing`); -} - -export function MissingAssignmentAssertionClaim(fnTag: string): Error { - return new Error(`${fnTag}, assignmentAssertionClaim missing`); -} diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/besu-bridge.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/besu-bridge.ts index d7f79203e5..a6bb0b2902 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/besu-bridge.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/besu-bridge.ts @@ -21,6 +21,8 @@ import { import { InteractionsRequest } from "../../../generated/SATPWrapperContract"; import { getInteractionType } from "./types/asset"; import { InteractionData } from "./types/interact"; +import { OntologyError } from "../../errors/bridge-erros"; +import { TransactionError } from "fabric-network"; interface BesuResponse { success: boolean; @@ -53,14 +55,13 @@ export class BesuBridge implements NetworkBridge { } public async wrapAsset(asset: BesuAsset): Promise { + const fnTag = `${BesuBridge.CLASS_NAME}}#wrapAsset`; this.log.debug( - `${BesuBridge.CLASS_NAME}#wrapAsset Wrapping Asset: {${asset.tokenId}, ${asset.owner}, ${asset.contractAddress}, ${asset.tokenType}}`, + `${fnTag}, Wrapping Asset: {${asset.tokenId}, ${asset.owner}, ${asset.contractAddress}, ${asset.tokenType}}`, ); if (asset.ontology === undefined) { - throw new Error( - `${BesuBridge.CLASS_NAME}#wrapAsset: Ontology is required to interact with tokens`, - ); + throw new OntologyError(fnTag); } const interactions = this.interactionList(asset.ontology); @@ -82,7 +83,7 @@ export class BesuBridge implements NetworkBridge { })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#wrapAsset:Transaction failed`); + throw new TransactionError(fnTag); } return { @@ -91,9 +92,8 @@ export class BesuBridge implements NetworkBridge { }; } public async unwrapAsset(assetId: string): Promise { - this.log.debug( - `${BesuBridge.CLASS_NAME}#UnwrapAsset Unwrapping Asset: ${assetId}`, - ); + const fnTag = `${BesuBridge.CLASS_NAME}}#unwrapAsset`; + this.log.debug(`${fnTag}, Unwrapping Asset: ${assetId}`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -104,9 +104,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error( - `${BesuBridge.CLASS_NAME}#unwrapAsset:Transaction failed`, - ); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -117,9 +115,8 @@ export class BesuBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug( - `${BesuBridge.CLASS_NAME}#lockAsset Locking Asset: ${assetId} amount: ${amount}`, - ); + const fnTag = `${BesuBridge.CLASS_NAME}}#lockAsset`; + this.log.debug(`${fnTag}, Locking Asset: ${assetId} amount: ${amount}`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -130,7 +127,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#lockAsset:Transaction failed}`); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -141,9 +138,8 @@ export class BesuBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug( - `${BesuBridge.CLASS_NAME}#unlockAsset Unlocking Asset: ${assetId} amount: ${amount}`, - ); + const fnTag = `${BesuBridge.CLASS_NAME}}#unlockAsset`; + this.log.debug(`${fnTag}, Unlocking Asset: ${assetId} amount: ${amount}`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -154,9 +150,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error( - `${BesuBridge.CLASS_NAME}#unlockAsset:Transaction failed}`, - ); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -167,9 +161,8 @@ export class BesuBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug( - `${BesuBridge.CLASS_NAME}#mintAsset Minting Asset: ${assetId} amount: ${amount}`, - ); + const fnTag = `${BesuBridge.CLASS_NAME}}#mintAsset`; + this.log.debug(`${fnTag}, Minting Asset: ${assetId} amount: ${amount}`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -180,7 +173,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#mintAsset:Transaction failed}`); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -191,9 +184,8 @@ export class BesuBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug( - `${BesuBridge.CLASS_NAME}#burnAsset Burning Asset: ${assetId} amount: ${amount}`, - ); + const fnTag = `${BesuBridge.CLASS_NAME}}#burnAsset`; + this.log.debug(`${fnTag}, Burning Asset: ${assetId} amount: ${amount}`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -204,7 +196,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#burnAsset:Transaction failed}`); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -216,8 +208,9 @@ export class BesuBridge implements NetworkBridge { to: string, amount: number, ): Promise { + const fnTag = `${BesuBridge.CLASS_NAME}}#assignAsset`; this.log.debug( - `${BesuBridge.CLASS_NAME}#assignAsset Assigning Asset: ${assetId} amount: ${amount} to: ${to}`, + `${fnTag}, Assigning Asset: ${assetId} amount: ${amount} to: ${to}`, ); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, @@ -229,9 +222,7 @@ export class BesuBridge implements NetworkBridge { gas: this.config.gas, })) as BesuResponse; if (!response.success) { - throw new Error( - `${BesuBridge.CLASS_NAME}#assignAsset:Transaction failed}`, - ); + throw new TransactionError(fnTag); } return { transactionId: response.out.transactionReceipt.transactionHash ?? "", @@ -240,7 +231,8 @@ export class BesuBridge implements NetworkBridge { } public async getAssets(): Promise { - this.log.debug(`${BesuBridge.CLASS_NAME}#getAssets Getting Assets`); + const fnTag = `${BesuBridge.CLASS_NAME}}#getAssets`; + this.log.debug(`${fnTag}, Getting Assets`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -252,14 +244,15 @@ export class BesuBridge implements NetworkBridge { })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#getAssets: Transaction failed`); + throw new TransactionError(fnTag); } return response.callOutput as string[]; } public async getAsset(assetId: string): Promise { - this.log.debug(`${BesuBridge.CLASS_NAME}#getAsset Getting Asset`); + const fnTag = `${BesuBridge.CLASS_NAME}}#getAsset`; + this.log.debug(`${fnTag}, Getting Asset`); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -271,7 +264,7 @@ export class BesuBridge implements NetworkBridge { })) as BesuResponse; if (!response.success) { - throw new Error(`${BesuBridge.CLASS_NAME}#getAsset: Transaction failed`); + throw new TransactionError(fnTag); } return response.callOutput as BesuAsset; @@ -286,7 +279,10 @@ export class BesuBridge implements NetworkBridge { params: string[], invocationType: EthContractInvocationType, ): Promise { - this.log.debug(`Running Transaction: ${methodName}`); + const fnTag = `${BesuBridge.CLASS_NAME}}#runTransaction`; + this.log.debug( + `${fnTag}, Running Transaction: ${methodName} with params: ${params}`, + ); const response = (await this.connector.invokeContract({ contractName: this.config.contractName, keychainId: this.config.keychainId, @@ -298,9 +294,7 @@ export class BesuBridge implements NetworkBridge { })) as BesuResponse; if (!response.success) { - throw new Error( - `${BesuBridge.CLASS_NAME}#runTransaction:Transaction failed}`, - ); + throw new TransactionError(fnTag); } return { @@ -314,8 +308,9 @@ export class BesuBridge implements NetworkBridge { assetId: string, transactionHash: string, ): Promise { + const fnTag = `${BesuBridge.CLASS_NAME}}#getReceipt`; this.log.debug( - `Getting Receipt: ${assetId} transactionHash: ${transactionHash}`, + `${fnTag}, Getting Receipt: ${assetId} transactionHash: ${transactionHash}`, ); //todo needs implementation const networkDetails = { diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/fabric-bridge.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/fabric-bridge.ts index 6762fea50a..f4e8046135 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/fabric-bridge.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/satp-bridge/fabric-bridge.ts @@ -20,6 +20,7 @@ import { NetworkBridge } from "./network-bridge"; import { InteractionSignature } from "./types/fabric-asset"; import { InteractionData } from "./types/interact"; import { getInteractionType } from "./types/asset"; +import { OntologyError, TransactionError } from "../../errors/bridge-erros"; export class FabricBridge implements NetworkBridge { public static readonly CLASS_NAME = "FabricBridge"; @@ -46,12 +47,12 @@ export class FabricBridge implements NetworkBridge { }); } public async wrapAsset(asset: FabricAsset): Promise { - this.log.debug(`Wrapping Asset: ${asset.tokenId}`); - + const fnTag = `${FabricBridge.CLASS_NAME}}#wrapAsset`; + this.log.debug( + `${fnTag}, Wrapping Asset: {${asset.tokenId}, ${asset.owner}, ${asset.tokenType}}`, + ); if (asset.ontology === undefined) { - throw new Error( - `${FabricBridge.CLASS_NAME}#wrapAsset: Ontology is required to interact with tokens`, - ); + throw new OntologyError(fnTag); } const interactions = this.interactionList(asset.ontology); @@ -73,13 +74,18 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, }; } public async unwrapAsset(assetId: string): Promise { - this.log.debug(`Unwrapping Asset: ${assetId}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#unwrapAsset`; + this.log.debug(`${fnTag}, Unwrapping Asset: ${assetId}`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -89,6 +95,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -98,7 +108,8 @@ export class FabricBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug(`Locking Asset: ${assetId} amount: ${amount}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#lockAsset`; + this.log.debug(`${fnTag}, Locking Asset: ${assetId} amount: ${amount}`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -108,6 +119,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -117,7 +132,8 @@ export class FabricBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug(`Unlocking Asset: ${assetId} amount: ${amount}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#unlockAsset`; + this.log.debug(`${fnTag}, Unlocking Asset: ${assetId} amount: ${amount}`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -127,6 +143,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -136,7 +156,8 @@ export class FabricBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug(`Minting Asset: ${assetId} amount: ${amount}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#mintAsset`; + this.log.debug(`${fnTag}, Minting Asset: ${assetId} amount: ${amount}`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -146,6 +167,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -155,7 +180,8 @@ export class FabricBridge implements NetworkBridge { assetId: string, amount: number, ): Promise { - this.log.debug(`Burning Asset: ${assetId} amount: ${amount}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#burnAsset`; + this.log.debug(`${fnTag}, Burning Asset: ${assetId} amount: ${amount}`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -165,6 +191,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -175,7 +205,10 @@ export class FabricBridge implements NetworkBridge { to: string, amount: number, ): Promise { - this.log.debug(`Assigning Asset: ${assetId} to: ${to} amount: ${amount}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#assignAsset`; + this.log.debug( + `${fnTag}, Assigning Asset: ${assetId} amount: ${amount} to: ${to}`, + ); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -185,6 +218,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, output: response.functionOutput, @@ -192,7 +229,8 @@ export class FabricBridge implements NetworkBridge { } public async getAsset(assetId: string): Promise { - this.log.debug(`Getting Asset: ${assetId}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#getAsset`; + this.log.debug(`${fnTag}, Getting Asset`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -202,13 +240,18 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Call, }); + if (response == undefined) { + throw new TransactionError(fnTag); + } + const token = JSON.parse(response.functionOutput) as FabricAsset; return token; } public async getClientId(): Promise { - this.log.debug(`Getting Client Id`); + const fnTag = `${FabricBridge.CLASS_NAME}}#getClientId`; + this.log.debug(`${fnTag}, Getting Client Id`); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -218,6 +261,10 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Call, }); + if (response == undefined) { + throw new TransactionError(fnTag); + } + return response.functionOutput; } @@ -229,7 +276,10 @@ export class FabricBridge implements NetworkBridge { methodName: string, params: string[], ): Promise { - this.log.debug(`Running Transaction: ${methodName} with params: ${params}`); + const fnTag = `${FabricBridge.CLASS_NAME}}#runTransaction`; + this.log.debug( + `${fnTag}, Running Transaction: ${methodName} with params: ${params}`, + ); const response = await this.connector.transact({ signingCredential: this.config.signingCredential, channelName: this.config.channelName, @@ -239,9 +289,12 @@ export class FabricBridge implements NetworkBridge { invocationType: FabricContractInvocationType.Send, }); + if (response == undefined || response.transactionId == "") { + throw new TransactionError(fnTag); + } + return { transactionId: response.transactionId, - transactionReceipt: "response.transactionReceipt", output: response.functionOutput, }; } @@ -250,8 +303,9 @@ export class FabricBridge implements NetworkBridge { assetId: string, transactionId: string, ): Promise { + const fnTag = `${FabricBridge.CLASS_NAME}}#getReceipt`; this.log.debug( - `Getting Receipt for Asset: ${assetId} Transaction: ${transactionId}`, + `${fnTag}, Getting Receipt: ${assetId} transactionHash: ${transactionId}`, ); //todo needs implementation const networkDetails = { 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 1e4f9daefd..c582714c88 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 @@ -4,6 +4,7 @@ import { BridgeManager } from "./bridge-manager"; import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; import { SATPBridgeConfig } from "../../types"; import { Asset } from "./types/asset"; +import { TransactionIdUndefinedError } from "../../errors/bridge-erros"; export class SATPBridgeManager implements BridgeManager { public static readonly CLASS_NAME = "FabricBridgeManager"; @@ -25,7 +26,7 @@ export class SATPBridgeManager implements BridgeManager { const response = await this.config.network.wrapAsset(asset); if (response.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = this.config.network.getReceipt( @@ -43,7 +44,7 @@ export class SATPBridgeManager implements BridgeManager { const response = await this.config.network.unwrapAsset(assetId); if (response.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = this.config.network.getReceipt( @@ -66,7 +67,7 @@ export class SATPBridgeManager implements BridgeManager { const response = await this.config.network.lockAsset(assetId, amount); if (response.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = await this.config.network.getReceipt( @@ -85,7 +86,7 @@ export class SATPBridgeManager implements BridgeManager { const response = await this.config.network.unlockAsset(assetId, amount); if (response.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = await this.config.network.getReceipt( @@ -104,7 +105,7 @@ export class SATPBridgeManager implements BridgeManager { const transaction = await this.config.network.mintAsset(assetId, amount); if (transaction.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = await this.config.network.getReceipt( @@ -123,7 +124,7 @@ export class SATPBridgeManager implements BridgeManager { const transaction = await this.config.network.burnAsset(assetId, amount); if (transaction.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = await this.config.network.getReceipt( @@ -150,7 +151,7 @@ export class SATPBridgeManager implements BridgeManager { ); if (response.transactionId == undefined) { - throw new Error(`${fnTag}, transactionId is undefined`); + throw new TransactionIdUndefinedError(fnTag); } const receipt = await this.config.network.getReceipt( diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage0-server-service.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage0-server-service.ts index 747d10760c..a1304df153 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage0-server-service.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/core/stage-services/server/stage0-server-service.ts @@ -1,30 +1,4 @@ -import { - PreTransferCommenceRequestMessage, - PreTransferCommenceResponseMessage, - PreTransferVerificationAndContextEstablishmentRequest, - PreTransferVerificationAndContextEstablishmentResponse, -} from "../../../generated/proto/cacti/satp/v02/stage_0_pb"; -import { - MessageType, - CommonSatp, -} from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; -import { SATP_VERSION } from "../../constants"; -import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { TransferClaims } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { - TimestampType, - getMessageHash, - getMessageTimestamp, - saveHash, - saveSignature, -} from "../../session-utils"; -import { SATPSession } from "../../../core/satp-session"; +import { Token } from "../../../public-api"; import { SATPService, SATPServiceType, @@ -50,386 +24,12 @@ export class Stage0ServerService extends SATPService { super(commonOptions); } - async preTransferProposalResponse( - request: PreTransferVerificationAndContextEstablishmentRequest, - session: SATPSession | undefined, - ): Promise { - const stepTag = `transferProposalResponse()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - if (request.context == undefined || request.transferClaims == undefined) { - throw new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); - } - - if (session == undefined) { - throw new Error(`${fnTag}, session is undefined`); - } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.context.sessionId}`, - ); - } - - // saveSignature( - // sessionData, - // MessageType.PRE_INIT_PROPOSAL, - // request.context.signature, - // ); - - sessionData.sourceLedgerAssetId = - request.transferClaims.verifiedOriginatorEntityId; - sessionData.recipientLedgerAssetId = - request.transferClaims.verifiedBeneficiaryEntityId; // todo shouldn't be the server to create this id? - - sessionData.hashTransferInitClaims = getHash(request.transferClaims); - - saveHash(sessionData, MessageType.PRE_INIT_PROPOSAL, getHash(request)); - - sessionData.lastSequenceNumber = request.context.sequenceNumber + BigInt(1); - - const commonBody = new CommonSatp(); - commonBody.version = sessionData.version; - - commonBody.sessionId = sessionData.id; - commonBody.sequenceNumber = request.context.sequenceNumber + BigInt(1); - commonBody.resourceUrl = request.context.resourceUrl; - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.PRE_INIT_PROPOSAL, - ); - - const preTransferProposalReceiptMessage = - new PreTransferVerificationAndContextEstablishmentResponse(); - preTransferProposalReceiptMessage.context = commonBody; - preTransferProposalReceiptMessage.hashPreTransferVerificationAndContext = - sessionData.hashTransferInitClaims; - preTransferProposalReceiptMessage.timestamp = getMessageTimestamp( - sessionData, - MessageType.PRE_INIT_PROPOSAL, - TimestampType.RECEIVED, - ); - - const messageSignature = bufArray2HexStr( - sign(this.Signer, JSON.stringify(preTransferProposalReceiptMessage)), - ); - - // preTransferProposalReceiptMessage.context.signature = messageSignature; - - saveSignature(sessionData, commonBody.messageType, messageSignature); - - saveHash( - sessionData, - commonBody.messageType, - getHash(preTransferProposalReceiptMessage), - ); - - // TODO: store logs in the database using session ID; refactor storelog not to need gateway as input - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "transferProposalResponse", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - this.Log.info( - `${fnTag}, sending PreTransferVerificationAndContextEstablishmentResponse...`, - ); - - return preTransferProposalReceiptMessage; - } - - async transferCommenceResponse( - request: PreTransferCommenceRequestMessage, - session: SATPSession | undefined, - ): Promise { - const stepTag = `transferCommenceResponse()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - if (request.common == undefined) { - throw new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); - } - - if (session == undefined) { - throw new Error(`${fnTag}, session is undefined`); - } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not loaded correctly ${request.common.sessionId}`, - ); - } - - saveHash( - sessionData, - MessageType.TRANSFER_COMMENCE_REQUEST, - getHash(request), - ); - - const commonBody = new CommonSatp(); - commonBody.version = sessionData.version; - commonBody.messageType = MessageType.PRE_TRANSFER_COMMENCE_RESPONSE; - commonBody.sequenceNumber = sessionData.lastSequenceNumber + BigInt(1); - commonBody.hashPreviousMessage = getMessageHash( - sessionData, - MessageType.TRANSFER_COMMENCE_REQUEST, - ); - - commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; - commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; - commonBody.sessionId = sessionData.id; - - const preTransferCommenceResponseMessage = - new PreTransferCommenceResponseMessage(); - preTransferCommenceResponseMessage.common = commonBody; - - sessionData.lastSequenceNumber = commonBody.sequenceNumber; - - const messageSignature = bufArray2HexStr( - sign(this.Signer, JSON.stringify(preTransferCommenceResponseMessage)), - ); - - // preTransferCommenceResponseMessage.common.signature = messageSignature; - - saveSignature( - sessionData, - MessageType.PRE_TRANSFER_COMMENCE_RESPONSE, - messageSignature, - ); - - saveHash( - sessionData, - MessageType.PRE_TRANSFER_COMMENCE_RESPONSE, - getHash(preTransferCommenceResponseMessage), - ); - - /* - await storeLog(gateway, { - sessionID: sessionData.id, - type: "transferCommenceResponse", - operation: "lock", - data: JSON.stringify(sessionData), - }); - */ - - this.Log.info(`${fnTag}, sending PreTransferCommenceResponseMessage...`); - - return preTransferCommenceResponseMessage; - } - - async checkPreTransferProposalRequestMessage( - request: PreTransferVerificationAndContextEstablishmentRequest, - session: SATPSession | undefined, - //supportedDLTs: SupportedChain[], - ): Promise { - const stepTag = `checkTransferProposalRequestMessage()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - // todo use session; - session; - - if ( - request.context == undefined || - request.context.version == undefined || - request.context.messageType == undefined || - request.context.sessionId == undefined || - // request.context.transferContextId == undefined || - request.context.sequenceNumber == undefined || - request.context.resourceUrl == undefined || - // request.context.actionResponse == undefined || - // request.context.payloadProfile == undefined || - // request.context.applicationProfile == undefined || - // request.context.signature == undefined || - request.context.clientGatewayPubkey == undefined || - request.context.serverGatewayPubkey == undefined - ) { - throw new Error( - `${fnTag}, message satp common body is missing or is missing required fields`, - ); - } - - if (request.context.version != SATP_VERSION) { - throw new Error(`${fnTag}, unsupported SATP version`); - } - - if ( - !verifySignature( - this.Signer, - request.context, - request.context.clientGatewayPubkey, - ) - ) { - throw new Error( - `${fnTag}, TransferProposalRequest message signature verification failed`, - ); - } - - if (request.context.messageType != MessageType.INIT_PROPOSAL) { - throw new Error( - `${fnTag}, wrong message type for TransferProposalRequest`, - ); - } - - if (request.transferClaims == undefined) { - throw new Error( - `${fnTag}, TransferProposalRequest message does not contain transfer initialization claims`, - ); - } - - // const senderId = request.transferClaims - // .senderGatewayNetworkId as SupportedChain; - - this.Log.info(`TransferProposalRequest passed all checks.`); - - if (!this.checkTransferClaims(request.transferClaims)) { - throw new Error(); - } - return true; - } - - async checkTransferCommenceRequestMessage( - request: PreTransferCommenceRequestMessage, - session: SATPSession | undefined, - ): Promise { - const stepTag = `checkTransferCommenceRequestMessage()`; - const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - - 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.actionResponse == 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`); - } - - if (session == undefined) { - throw new Error(`${fnTag}, session is undefined`); - } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw new Error( - `${fnTag}, session data not found for session id ${request.common.sessionId}`, - ); - } - - if ( - sessionData.serverGatewayPubkey == undefined || - sessionData.hashes == undefined || - sessionData.hashes.stage1 == undefined || - sessionData.hashes.stage1.transferProposalReceiptMessageHash == - undefined || - sessionData.lastSequenceNumber == undefined - ) { - throw new Error(`${fnTag}, session data was not load correctly`); - } - - if (request.common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { - throw new Error( - `${fnTag}, TransferCommenceRequest serverIdentity public key does not match the one that was sent`, - ); - } - - if (request.common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { - throw new Error( - `${fnTag}, TransferCommenceRequest clientIdentity public key does not match the one that was sent`, - ); - } - - if ( - !verifySignature( - this.Signer, - request.common, - request.common.clientGatewayPubkey, - ) - ) { - throw new Error( - `${fnTag}, TransferCommenceRequest message signature verification failed`, - ); - } - - if (request.common.messageType != MessageType.TRANSFER_COMMENCE_REQUEST) { - throw new Error( - `${fnTag}, wrong message type for TransferCommenceRequest`, - ); - } - - if ( - request.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw new Error( - `${fnTag}, TransferCommenceRequest Message sequence number is wrong`, - ); - } - - if ( - request.common.hashPreviousMessage != - sessionData.hashes.stage1.transferProposalReceiptMessageHash - ) { - throw new Error( - `${fnTag}, TransferCommenceRequest previous message hash does not match the one that was sent`, - ); - } - - if ( - request.hashPreTransferVerificationAndContext == undefined || - request.hashPreTransferVerificationAndContext != - sessionData.hashTransferInitClaims - ) { - throw new Error( - `${fnTag}, TransferCommenceRequest message does not contain transfer claims`, - ); - } - - if ( - !verifySignature(this.Signer, request, sessionData.clientGatewayPubkey) - ) { - throw new Error( - `${fnTag}, TransferCommenceRequest message signature verification failed`, - ); - } - - this.Log.info(`TransferCommenceRequest passed all checks.`); - return sessionData; - } - - // eslint-disable-next-line @typescript-eslint/no-unused-vars - private checkTransferClaims(transferClaims: TransferClaims): boolean { + public async getPubKey(): Promise { //todo - return true; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - private counterProposalTransferClaims( - oldClaims: TransferClaims, - ): TransferClaims { + public async wrapToken(token: Token) { //todo - return oldClaims; + return token; } } 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 f6ac52e937..f5fd51fb1b 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 @@ -7,21 +7,18 @@ import { import { MessageType, CommonSatp, + NetworkCapabilities, + SignatureAlgorithm, + LockType, } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; // eslint-disable-next-line prettier/prettier import { ACCEPTANCE, - SessionData, } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; -import { SATP_VERSION } from "../../constants"; -import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; +import { bufArray2HexStr, getHash, sign } from "../../../gateway-utils"; import { TransferClaims } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; import { + SessionType, TimestampType, getMessageHash, getMessageTimestamp, @@ -36,22 +33,14 @@ import { ISATPServerServiceOptions, ISATPServiceOptions, } from "../satp-service"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; import { - DLTNotSupported, - HashMissMatch, - MessageTypeMissMatch, - MissingClientGatewayPubkey, - MissingNetworkCapabilities, - MissingSatpCommonBody, - MissingServerGatewayPubkey, - MissingTransferInitClaims, - SATPVersionUnsupported, - SequenceNumberMissMatch, - SessionDataNotLoadedCorrectly, - SessionUndefined, - SignatureVerificationFailed, - TransferContextIdMissMatch, -} from "../errors"; + DLTNotSupportedError, + NetworkCapabilitiesError, + SessionError, + TransferInitClaimsError, + TransferInitClaimsHashError, +} from "../../errors/satp-service-errors"; export class Stage1ServerService extends SATPService { public static readonly SATP_STAGE = "1"; public static readonly SERVICE_TYPE = SATPServiceType.Server; @@ -72,33 +61,24 @@ export class Stage1ServerService extends SATPService { async transferProposalResponse( request: TransferProposalRequestMessage, - session: SATPSession | undefined, + session: SATPSession, ): Promise { const stepTag = `transferProposalResponse()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, transferProposalResponse...`); - if ( - request.common == undefined || - request.transferInitClaims == undefined || - request.networkCapabilities == undefined - ) { - throw MissingSatpCommonBody(fnTag); - } - if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + session.verify(fnTag, SessionType.SERVER); + + const sessionData = session.getServerSessionData(); sessionData.sourceLedgerAssetId = - request.transferInitClaims.verifiedOriginatorEntityId; + request.transferInitClaims!.verifiedOriginatorEntityId; sessionData.recipientLedgerAssetId = - request.transferInitClaims.verifiedBeneficiaryEntityId; // todo shouldn't be the server to create this id? + request.transferInitClaims!.verifiedBeneficiaryEntityId; // todo shouldn't be the server to create this id? sessionData.hashTransferInitClaims = getHash(request.transferInitClaims); @@ -107,11 +87,11 @@ export class Stage1ServerService extends SATPService { commonBody.sessionId = sessionData.id; sessionData.lastSequenceNumber = commonBody.sequenceNumber = - request.common.sequenceNumber + BigInt(1); - commonBody.resourceUrl = request.common.resourceUrl; + request.common!.sequenceNumber + BigInt(1); commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; commonBody.transferContextId = sessionData.transferContextId; + commonBody.resourceUrl = sessionData.resourceUrl; commonBody.hashPreviousMessage = getMessageHash( sessionData, @@ -119,38 +99,28 @@ export class Stage1ServerService extends SATPService { ); const transferProposalReceiptMessage = new TransferProposalReceiptMessage(); - transferProposalReceiptMessage.common = commonBody; - transferProposalReceiptMessage.hashTransferInitClaims = - sessionData.hashTransferInitClaims; - transferProposalReceiptMessage.timestamp = getMessageTimestamp( - sessionData, - MessageType.INIT_PROPOSAL, - TimestampType.RECEIVED, - ); - - //TODO implement reject - /* - if (reject) { + if (sessionData.acceptance == ACCEPTANCE.ACCEPTANCE_REJECTED) { + transferProposalReceiptMessage.common = commonBody; commonBody.messageType = MessageType.INIT_REJECT; - const counterProposalTransferClaims = this.counterProposalTransferClaims( - request.transferInitClaims, + transferProposalReceiptMessage.timestamp = getMessageTimestamp( + sessionData, + MessageType.INIT_REJECT, + TimestampType.RECEIVED, ); - - if (!counterProposalTransferClaims) { - this.Log.info(`${fnTag}, ProposalTransferClaims were rejected...`); - sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_REJECTED; - } else { - sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_CONDITIONAL; - transferProposalReceiptMessage.transferCounterClaims = - counterProposalTransferClaims; - } } else { - commonBody.messageType = MessageType.INIT_RECEIPT; sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_ACCEPTED; + transferProposalReceiptMessage.common = commonBody; + transferProposalReceiptMessage.hashTransferInitClaims = + sessionData.hashTransferInitClaims; + commonBody.messageType = MessageType.INIT_RECEIPT; + transferProposalReceiptMessage.timestamp = getMessageTimestamp( + sessionData, + MessageType.INIT_PROPOSAL, + TimestampType.RECEIVED, + ); } - */ - commonBody.messageType = MessageType.INIT_RECEIPT; - sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_ACCEPTED; + + //TODO implement conditional reject const messageSignature = bufArray2HexStr( sign(this.Signer, JSON.stringify(transferProposalReceiptMessage)), @@ -182,30 +152,25 @@ export class Stage1ServerService extends SATPService { async transferCommenceResponse( request: TransferCommenceRequestMessage, - session: SATPSession | undefined, + session: SATPSession, ): Promise { const stepTag = `transferCommenceResponse()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, transferCommenceResponse...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + session.verify(fnTag, SessionType.SERVER); - if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getServerSessionData(); const commonBody = new CommonSatp(); commonBody.version = sessionData.version; commonBody.messageType = MessageType.TRANSFER_COMMENCE_RESPONSE; sessionData.lastSequenceNumber = commonBody.sequenceNumber = - request.common.sequenceNumber + BigInt(1); + request.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.TRANSFER_COMMENCE_REQUEST, @@ -214,8 +179,8 @@ export class Stage1ServerService extends SATPService { commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; commonBody.sessionId = sessionData.id; - commonBody.resourceUrl = request.common.resourceUrl; commonBody.transferContextId = sessionData.transferContextId; + commonBody.resourceUrl = sessionData.resourceUrl; const transferCommenceResponseMessage = new TransferCommenceResponseMessage(); @@ -255,104 +220,75 @@ export class Stage1ServerService extends SATPService { async checkTransferProposalRequestMessage( request: TransferProposalRequestMessage, - session: SATPSession | undefined, + session: SATPSession, supportedDLTs: SupportedChain[], - ): Promise { + ): Promise { const stepTag = `checkTransferProposalRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkTransferProposalRequestMessage...`); - if (session == undefined) { - throw SessionUndefined(fnTag); - } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if ( - request.common == undefined || - request.common.version == undefined || - request.common.messageType == undefined || - request.common.sessionId == undefined || - request.common.sequenceNumber == undefined || - request.common.resourceUrl == undefined || - // request.common.actionResponse == undefined || - // request.common.payloadProfile == undefined || - // request.common.applicationProfile == undefined || - request.clientSignature == undefined || - request.common.clientGatewayPubkey == undefined || - request.common.serverGatewayPubkey == undefined - ) { - throw MissingSatpCommonBody(fnTag); - } - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - - if ( - !verifySignature(this.Signer, request, request.common.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); + if (session == undefined) { + throw new SessionError(fnTag); } - if (request.common.messageType != MessageType.INIT_PROPOSAL) { - throw MessageTypeMissMatch( - fnTag, - request.common.messageType.toString(), - MessageType.INIT_PROPOSAL.toString(), - ); - } + const sessionData = session.getServerSessionData(); - if (request.transferInitClaims == undefined) { - throw MissingTransferInitClaims(fnTag); - } + this.checkNetworkCapabilities(request.networkCapabilities, fnTag); - if (request.networkCapabilities == undefined) { - throw MissingNetworkCapabilities(fnTag); + if (this.checkTransferClaims(request.transferInitClaims, fnTag)) { + sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_ACCEPTED; + } else { + this.Log.info(`${fnTag}, TransferProposalRequest was rejected...`); + sessionData.acceptance = ACCEPTANCE.ACCEPTANCE_REJECTED; + return; } - const senderId = request.transferInitClaims + const senderId = request.transferInitClaims! .senderGatewayNetworkId as SupportedChain; if (!supportedDLTs.includes(senderId)) { - throw DLTNotSupported(fnTag, senderId); //todo change this to the transferClaims check - } - - if (!this.checkTransferClaims(request.transferInitClaims)) { - throw new Error(); + throw new DLTNotSupportedError(fnTag, senderId); //todo change this to the transferClaims check } - this.Log.info(`TransferProposalRequest passed all checks.`); - - sessionData.version = request.common.version; - sessionData.digitalAssetId = request.transferInitClaims.digitalAssetId; - sessionData.originatorPubkey = request.transferInitClaims.originatorPubkey; + sessionData.version = request.common!.version; + sessionData.digitalAssetId = request.transferInitClaims!.digitalAssetId; + sessionData.originatorPubkey = request.transferInitClaims!.originatorPubkey; sessionData.beneficiaryPubkey = - request.transferInitClaims.beneficiaryPubkey; + request.transferInitClaims!.beneficiaryPubkey; sessionData.senderGatewayNetworkId = - request.transferInitClaims.senderGatewayNetworkId; + request.transferInitClaims!.senderGatewayNetworkId; sessionData.recipientGatewayNetworkId = - request.transferInitClaims.recipientGatewayNetworkId; + request.transferInitClaims!.recipientGatewayNetworkId; sessionData.clientGatewayPubkey = - request.transferInitClaims.clientGatewayPubkey; + request.transferInitClaims!.clientGatewayPubkey; sessionData.serverGatewayPubkey = - request.transferInitClaims.serverGatewayPubkey; + request.transferInitClaims!.serverGatewayPubkey; sessionData.receiverGatewayOwnerId = - request.transferInitClaims.receiverGatewayOwnerId; + request.transferInitClaims!.receiverGatewayOwnerId; sessionData.senderGatewayOwnerId = - request.transferInitClaims.senderGatewayOwnerId; + request.transferInitClaims!.senderGatewayOwnerId; sessionData.signatureAlgorithm = - request.networkCapabilities.signatureAlgorithm; - sessionData.lockType = request.networkCapabilities.lockType; + request.networkCapabilities!.signatureAlgorithm; + sessionData.lockType = request.networkCapabilities!.lockType; sessionData.lockExpirationTime = - request.networkCapabilities.lockExpirationTime; + request.networkCapabilities!.lockExpirationTime; sessionData.credentialProfile = - request.networkCapabilities.credentialProfile; - sessionData.loggingProfile = request.networkCapabilities.loggingProfile; + request.networkCapabilities!.credentialProfile; + sessionData.loggingProfile = request.networkCapabilities!.loggingProfile; sessionData.accessControlProfile = - request.networkCapabilities.accessControlProfile; + request.networkCapabilities!.accessControlProfile; + sessionData.resourceUrl = request.common!.resourceUrl; + + session.verify(fnTag, SessionType.SERVER); + + commonBodyVerifier( + fnTag, + request.common, + sessionData, + MessageType.INIT_PROPOSAL, + ); + + signatureVerifier(fnTag, this.Signer, request, sessionData); this.Log.info( `${fnTag}, Session data created for session id ${sessionData.id}`, @@ -361,122 +297,37 @@ export class Stage1ServerService extends SATPService { saveHash(sessionData, MessageType.INIT_PROPOSAL, getHash(request)); this.Log.info(`${fnTag}, TransferProposalRequest passed all checks.`); - - return sessionData; } async checkTransferCommenceRequestMessage( request: TransferCommenceRequestMessage, - session: SATPSession | undefined, - ): Promise { + session: SATPSession, + ): Promise { const stepTag = `checkTransferCommenceRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; - if ( - request.common == undefined || - request.common.version == undefined || - request.common.messageType == undefined || - request.common.sessionId == undefined || - request.common.sequenceNumber == undefined || - request.common.resourceUrl == undefined || - // request.common.actionResponse == undefined || - // request.common.payloadProfile == undefined || - // request.common.applicationProfile == undefined || - request.clientSignature == undefined || - request.common.clientGatewayPubkey == undefined || - request.common.serverGatewayPubkey == undefined - ) { - throw MissingSatpCommonBody(fnTag); - } - - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); - - if ( - sessionData == undefined || - sessionData.serverGatewayPubkey == undefined || - sessionData.hashes == undefined || - sessionData.hashes.stage1 == undefined || - sessionData.hashes.stage1.transferProposalReceiptMessageHash == - undefined || - sessionData.lastSequenceNumber == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + session.verify(fnTag, SessionType.SERVER); - if (request.common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { - throw MissingServerGatewayPubkey(fnTag); - } - - if (request.common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { - throw MissingClientGatewayPubkey(fnTag); - } - - if ( - !verifySignature(this.Signer, request, request.common.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } + const sessionData = session.getServerSessionData(); - if (request.common.messageType != MessageType.TRANSFER_COMMENCE_REQUEST) { - throw MessageTypeMissMatch( - fnTag, - request.common.messageType.toString(), - MessageType.TRANSFER_COMMENCE_REQUEST.toString(), - ); - } + commonBodyVerifier( + fnTag, + request.common, + sessionData, + MessageType.TRANSFER_COMMENCE_REQUEST, + ); - if ( - request.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw SequenceNumberMissMatch( - fnTag, - request.common.sequenceNumber, - sessionData.lastSequenceNumber + BigInt(1), - ); - } + signatureVerifier(fnTag, this.Signer, request, sessionData); if ( - request.common.hashPreviousMessage != - sessionData.hashes.stage1.transferProposalReceiptMessageHash - ) { - throw HashMissMatch( - fnTag, - request.common.hashPreviousMessage, - sessionData.hashes.stage1.transferProposalReceiptMessageHash, - ); - } - - if ( - request.hashTransferInitClaims == undefined || + request.hashTransferInitClaims == "" || request.hashTransferInitClaims != sessionData.hashTransferInitClaims ) { - throw MissingTransferInitClaims(fnTag); - } - - if ( - !verifySignature(this.Signer, request, sessionData.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } - - if ( - sessionData.transferContextId != undefined && - request.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - request.common.transferContextId, - sessionData.transferContextId, - ); + throw new TransferInitClaimsHashError(fnTag); } if (request.clientTransferNumber != undefined) { @@ -493,12 +344,98 @@ export class Stage1ServerService extends SATPService { ); this.Log.info(`${fnTag}, TransferCommenceRequest passed all checks.`); + } - return sessionData; + private checkTransferClaims( + transferClaims: TransferClaims | undefined, + tag: string, + ): boolean { + if (transferClaims == undefined) { + throw new TransferInitClaimsError(tag); + } + if (transferClaims.digitalAssetId == "") { + this.Log.error(`${tag}, digitalAssetId is missing`); + } + if (transferClaims.assetProfileId == "") { + this.Log.error(`${tag}, assetProfileId is missing`); + return false; + } + if (transferClaims.verifiedOriginatorEntityId == "") { + this.Log.error(`${tag}, verifiedOriginatorEntityId is missing`); + return false; + } + if (transferClaims.verifiedBeneficiaryEntityId == "") { + this.Log.error(`${tag}, verifiedBeneficiaryEntityId is missing`); + } + if (transferClaims.originatorPubkey == "") { + this.Log.error(`${tag}, originatorPubkey is missing`); + return false; + } + if (transferClaims.beneficiaryPubkey == "") { + this.Log.error(`${tag}, beneficiaryPubkey is missing`); + return false; + } + if (transferClaims.senderGatewayNetworkId != "") { + this.Log.info(`${tag}, optional variable senderGatewayNetworkId loaded`); + } + if (transferClaims.recipientGatewayNetworkId != "") { + this.Log.info( + `${tag}, optional variable recipientGatewayNetworkId loaded`, + ); + } + if (transferClaims.clientGatewayPubkey == "") { + this.Log.error(`${tag}, clientGatewayPubkey is missing`); + return false; + } + if (transferClaims.serverGatewayPubkey == "") { + this.Log.error(`${tag}, serverGatewayPubkey is missing`); + return false; + } + if (transferClaims.senderGatewayOwnerId != "") { + this.Log.info(`${tag}, optional variable senderGatewayNetworkId loaded`); + } + if (transferClaims.receiverGatewayOwnerId != "") { + this.Log.info(`${tag}, optional variable receiverGatewayOwnerId loaded`); + } + //todo + return true; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - private checkTransferClaims(transferClaims: TransferClaims): boolean { + private checkNetworkCapabilities( + networkCapabilities: NetworkCapabilities | undefined, + tag: string, + ): boolean { + if (networkCapabilities == undefined) { + throw new NetworkCapabilitiesError(tag); + } + if (networkCapabilities.senderGatewayNetworkId == "") { + } + if ( + networkCapabilities.signatureAlgorithm == SignatureAlgorithm.UNSPECIFIED + ) { + } + if (networkCapabilities.supportedSignatureAlgorithms.length == 0) { + } + if (networkCapabilities.lockType == LockType.UNSPECIFIED) { + } + if (networkCapabilities.lockExpirationTime == BigInt(0)) { + } + if (networkCapabilities.permissions == undefined) { + } + if (networkCapabilities.developerUrn == "") { + } + if (networkCapabilities.credentialProfile == undefined) { + } + if (networkCapabilities.applicationProfile == "") { + } + if (networkCapabilities.loggingProfile == "") { + } + if (networkCapabilities.accessControlProfile == "") { + } + if (networkCapabilities.subsequentCalls == undefined) { + } + if (networkCapabilities.history == undefined) { + } //todo return true; } 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 1c01eb4b78..15dd69e987 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 @@ -7,14 +7,13 @@ 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 } from "../../../gateway-utils"; import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; + getMessageHash, + saveHash, + saveSignature, + SessionType, +} from "../../session-utils"; import { SATPService, SATPServiceType, @@ -22,22 +21,13 @@ import { ISATPServiceOptions, } from "../satp-service"; import { SATPSession } from "../../../core/satp-session"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; import { - HashMissMatch, - MessageTypeMissMatch, - MissingClientGatewayPubkey, - MissingLockAssertionClaim, - MissingLockAssertionClaimFormat, - MissingLockAssertionExpiration, - MissingSatpCommonBody, - MissingServerGatewayPubkey, - SATPVersionUnsupported, - SequenceNumberMissMatch, - SessionDataNotLoadedCorrectly, - SessionUndefined, - SignatureVerificationFailed, - TransferContextIdMissMatch, -} from "../errors"; + LockAssertionClaimError, + LockAssertionClaimFormatError, + LockAssertionExpirationError, + SessionError, +} from "../../errors/satp-service-errors"; export class Stage2ServerService extends SATPService { public static readonly SATP_STAGE = "2"; public static readonly SERVICE_TYPE = SATPServiceType.Server; @@ -63,30 +53,25 @@ export class Stage2ServerService extends SATPService { this.Log.debug(`${fnTag}, lockAssertionResponse...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + session.verify(fnTag, SessionType.SERVER); - if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getServerSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.ASSERTION_RECEIPT; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); + commonBody.sequenceNumber = request.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.LOCK_ASSERT, ); - commonBody.sessionId = request.common.sessionId; + commonBody.sessionId = request.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; sessionData.lastSequenceNumber = commonBody.sequenceNumber; @@ -134,119 +119,48 @@ export class Stage2ServerService extends SATPService { async checkLockAssertionRequestMessage( request: LockAssertionRequestMessage, session: SATPSession, - ): Promise { + ): Promise { const stepTag = `checkLockAssertionRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkLockAssertionRequestMessage...`); if (session == undefined) { - throw SessionUndefined(fnTag); - } - - const sessionData = session.getServerSessionData(); - - if ( - sessionData == undefined || - sessionData.serverGatewayPubkey == undefined || - sessionData.lastSequenceNumber == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); + throw new SessionError(fnTag); } - if ( - request.common == undefined || - request.common.version == undefined || - request.common.messageType == undefined || - request.common.sessionId == undefined || - request.common.sequenceNumber == undefined || - request.common.resourceUrl == undefined || - request.clientSignature == undefined || - request.common.clientGatewayPubkey == undefined || - request.common.serverGatewayPubkey == undefined || - request.common.hashPreviousMessage == undefined - ) { - throw MissingSatpCommonBody(fnTag); - } + session.verify(fnTag, SessionType.SERVER); - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - - if (request.common.serverGatewayPubkey != sessionData.serverGatewayPubkey) { - throw MissingServerGatewayPubkey(fnTag); - } - - if (request.common.clientGatewayPubkey != sessionData.clientGatewayPubkey) { - throw MissingClientGatewayPubkey(fnTag); - } - - if ( - !verifySignature(this.Signer, request, request.common.serverGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } - - if (request.common.messageType != MessageType.LOCK_ASSERT) { - throw MessageTypeMissMatch( - fnTag, - request.common.messageType.toString(), - MessageType.LOCK_ASSERT.toString(), - ); - } + const sessionData = session.getServerSessionData(); - if ( - request.common.sequenceNumber != - sessionData.lastSequenceNumber + BigInt(1) - ) { - throw SequenceNumberMissMatch( - fnTag, - request.common.sequenceNumber, - sessionData.lastSequenceNumber, - ); - } + commonBodyVerifier( + fnTag, + request.common, + sessionData, + MessageType.LOCK_ASSERT, + ); - if ( - request.common.hashPreviousMessage != - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE) - ) { - throw HashMissMatch( - fnTag, - request.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_RESPONSE), - ); - } + signatureVerifier(fnTag, this.Signer, request, sessionData); if (request.lockAssertionClaim == undefined) { - throw MissingLockAssertionClaim(fnTag); + throw new LockAssertionClaimError(fnTag); } sessionData.lockAssertionClaim = request.lockAssertionClaim; if (request.lockAssertionClaimFormat == undefined) { - throw MissingLockAssertionClaimFormat(fnTag); + throw new LockAssertionClaimFormatError(fnTag); } sessionData.lockAssertionClaimFormat = request.lockAssertionClaimFormat; //todo check if valid - if (request.lockAssertionExpiration == undefined) { - throw MissingLockAssertionExpiration(fnTag); + if (request.lockAssertionExpiration == BigInt(0)) { + throw new LockAssertionExpirationError(fnTag); } sessionData.lockAssertionExpiration = request.lockAssertionExpiration; //todo check if expired if ( - sessionData.transferContextId != undefined && - request.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - request.common.transferContextId, - sessionData.transferContextId, - ); - } - - if ( - sessionData.clientTransferNumber != undefined && + sessionData.clientTransferNumber != "" && request.clientTransferNumber != sessionData.clientTransferNumber ) { // This does not throw an error because the clientTransferNumber is only meaningful to the client. @@ -258,6 +172,5 @@ export class Stage2ServerService extends SATPService { saveHash(sessionData, MessageType.LOCK_ASSERT, getHash(request)); this.Log.info(`${fnTag}, 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 7634d9416f..0831f815d7 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 @@ -12,14 +12,13 @@ import { MessageType, MintAssertionClaim, } from "../../../generated/proto/cacti/satp/v02/common/message_pb"; -import { SessionData } from "../../../generated/proto/cacti/satp/v02/common/session_pb"; +import { bufArray2HexStr, getHash, sign } from "../../../gateway-utils"; import { - bufArray2HexStr, - getHash, - sign, - verifySignature, -} from "../../../gateway-utils"; -import { getMessageHash, saveHash, saveSignature } from "../../session-utils"; + getMessageHash, + saveHash, + saveSignature, + SessionType, +} from "../../session-utils"; import { SATPService, SATPServiceType, @@ -28,23 +27,14 @@ import { } from "../satp-service"; import { SATPSession } from "../../../core/satp-session"; import { SATPBridgesManager } from "../../../gol/satp-bridges-manager"; +import { commonBodyVerifier, signatureVerifier } from "../data-verifier"; import { - HashMissMatch, - MessageTypeMissMatch, - MissingAssignmentAssertionClaim, - MissingBridgeManager, - MissingBurnAssertionClaim, - MissingClientGatewayPubkey, - MissingMintAssertionClaim, - MissingSatpCommonBody, - MissingServerGatewayPubkey, - SATPVersionUnsupported, - SequenceNumberMissMatch, - SessionDataNotLoadedCorrectly, - SessionUndefined, - SignatureVerificationFailed, - TransferContextIdMissMatch, -} from "../errors"; + AssignmentAssertionClaimError, + BurnAssertionClaimError, + MintAssertionClaimError, + MissingBridgeManagerError, + SessionError, +} from "../../errors/satp-service-errors"; export class Stage3ServerService extends SATPService { public static readonly SATP_STAGE = "3"; @@ -64,7 +54,9 @@ export class Stage3ServerService extends SATPService { }; super(commonOptions); if (ops.bridgeManager == undefined) { - throw MissingBridgeManager(`${this.getServiceIdentifier()}#constructor`); + throw new MissingBridgeManagerError( + `${this.getServiceIdentifier()}#constructor`, + ); } this.bridgeManager = ops.bridgeManager; } @@ -78,30 +70,25 @@ export class Stage3ServerService extends SATPService { this.Log.debug(`${fnTag}, commitReady...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); + session.verify(fnTag, SessionType.SERVER); - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } - - if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getServerSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.COMMIT_READY; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); + commonBody.sequenceNumber = request.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.COMMIT_PREPARE, ); - commonBody.sessionId = request.common.sessionId; + commonBody.sessionId = request.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; sessionData.lastSequenceNumber = commonBody.sequenceNumber; @@ -109,7 +96,7 @@ export class Stage3ServerService extends SATPService { commitReadyMessage.common = commonBody; if (sessionData.mintAssertionClaim == undefined) { - throw MissingMintAssertionClaim(fnTag); + throw new MintAssertionClaimError(fnTag); } commitReadyMessage.mintAssertionClaim = sessionData.mintAssertionClaim; @@ -162,30 +149,25 @@ export class Stage3ServerService extends SATPService { this.Log.debug(`${fnTag}, commitFinalAcknowledgementReceiptResponse...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); - - if (sessionData == undefined) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + session.verify(fnTag, SessionType.SERVER); - if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } + const sessionData = session.getServerSessionData(); const commonBody = new CommonSatp(); commonBody.version = SATP_VERSION; commonBody.messageType = MessageType.ACK_COMMIT_FINAL; - commonBody.sequenceNumber = request.common.sequenceNumber + BigInt(1); + commonBody.sequenceNumber = request.common!.sequenceNumber + BigInt(1); commonBody.hashPreviousMessage = getMessageHash( sessionData, MessageType.COMMIT_FINAL, ); - commonBody.sessionId = request.common.sessionId; + commonBody.sessionId = request.common!.sessionId; commonBody.clientGatewayPubkey = sessionData.clientGatewayPubkey; commonBody.serverGatewayPubkey = sessionData.serverGatewayPubkey; + commonBody.resourceUrl = sessionData.resourceUrl; sessionData.lastSequenceNumber = commonBody.sequenceNumber; @@ -194,7 +176,7 @@ export class Stage3ServerService extends SATPService { commitFinalAcknowledgementReceiptResponseMessage.common = commonBody; if (sessionData.assignmentAssertionClaim == undefined) { - throw MissingAssignmentAssertionClaim(fnTag); + throw new AssignmentAssertionClaimError(fnTag); } commitFinalAcknowledgementReceiptResponseMessage.assignmentAssertionClaim = @@ -251,91 +233,32 @@ export class Stage3ServerService extends SATPService { async checkCommitPreparationRequestMessage( request: CommitPreparationRequestMessage, session: SATPSession, - ): Promise { + ): Promise { const stepTag = `checkCommitPreparationRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkCommitPreparationRequestMessage...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); + session.verify(fnTag, SessionType.SERVER); - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + const sessionData = session.getServerSessionData(); if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - - if (request.common.messageType != MessageType.COMMIT_PREPARE) { - throw MessageTypeMissMatch( - fnTag, - request.common.messageType.toString(), - MessageType.COMMIT_PREPARE.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( + commonBodyVerifier( fnTag, - sessionData.lastSequenceNumber, - request.common.sequenceNumber, + request.common, + sessionData, + MessageType.COMMIT_PREPARE, ); } - if ( - getMessageHash(sessionData, MessageType.ASSERTION_RECEIPT) != - request.common.hashPreviousMessage - ) { - throw HashMissMatch( - fnTag, - request.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.ASSERTION_RECEIPT), - ); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw MissingClientGatewayPubkey(fnTag); - } - - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw MissingServerGatewayPubkey(fnTag); - } - - if ( - !verifySignature(this.Signer, request, request.common.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } - - if ( - sessionData.transferContextId != undefined && - request.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - request.common.transferContextId, - sessionData.transferContextId, - ); - } + signatureVerifier(fnTag, this.Signer, request, sessionData); if ( - sessionData.clientTransferNumber != undefined && + sessionData.clientTransferNumber != "" && request.clientTransferNumber != sessionData.clientTransferNumber ) { // This does not throw an error because the clientTransferNumber is only meaningful to the client. @@ -349,98 +272,38 @@ export class Stage3ServerService extends SATPService { this.Log.info( `${fnTag}, CommitPreparationRequestMessage passed all checks.`, ); - - return sessionData; } async checkCommitFinalAssertionRequestMessage( request: CommitFinalAssertionRequestMessage, session: SATPSession, - ): Promise { + ): Promise { const stepTag = `checkCommitFinalAssertionRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkCommitFinalAssertionRequestMessage...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); + session.verify(fnTag, SessionType.SERVER); - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + const sessionData = session.getServerSessionData(); if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - - if (request.common.messageType != MessageType.COMMIT_FINAL) { - throw MessageTypeMissMatch( - fnTag, - request.common.messageType.toString(), - MessageType.COMMIT_FINAL.toString(), - ); - } - - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( + commonBodyVerifier( fnTag, - request.common.sequenceNumber, - sessionData.lastSequenceNumber, + request.common, + sessionData, + MessageType.COMMIT_FINAL, ); } - if ( - getMessageHash(sessionData, MessageType.COMMIT_READY) != - request.common.hashPreviousMessage - ) { - throw HashMissMatch( - fnTag, - request.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.COMMIT_READY), - ); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw MissingClientGatewayPubkey(fnTag); - } + signatureVerifier(fnTag, this.Signer, request, sessionData); - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw MissingServerGatewayPubkey(fnTag); - } - - if ( - !verifySignature(this.Signer, request, request.common.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } - - if ( - sessionData.transferContextId != undefined && - request.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - request.common.transferContextId, - sessionData.transferContextId, - ); - } //todo check burn if (request.burnAssertionClaim == undefined) { - throw MissingBurnAssertionClaim(fnTag); + throw new BurnAssertionClaimError(fnTag); } sessionData.burnAssertionClaim = request.burnAssertionClaim; @@ -467,110 +330,34 @@ export class Stage3ServerService extends SATPService { this.Log.info( `${fnTag}, CommitFinalAssertionRequestMessage passed all checks.`, ); - - return sessionData; } async checkTransferCompleteRequestMessage( request: TransferCompleteRequestMessage, session: SATPSession, - ): Promise { + ): Promise { const stepTag = `checkTransferCompleteRequestMessage()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; this.Log.debug(`${fnTag}, checkTransferCompleteRequestMessage...`); if (session == undefined) { - throw SessionUndefined(fnTag); + throw new SessionError(fnTag); } - const sessionData = session.getServerSessionData(); + session.verify(fnTag, SessionType.SERVER); - if ( - sessionData == undefined || - sessionData.lastSequenceNumber == undefined || - sessionData.version == undefined || - sessionData.signatures == undefined - ) { - throw SessionDataNotLoadedCorrectly(fnTag); - } + const sessionData = session.getServerSessionData(); if (request.common == undefined) { - throw MissingSatpCommonBody(fnTag); - } - - if (request.common.version != SATP_VERSION) { - throw SATPVersionUnsupported(fnTag, request.common.version, SATP_VERSION); - } - - if (request.common.messageType != MessageType.COMMIT_TRANSFER_COMPLETE) { - throw MessageTypeMissMatch( + commonBodyVerifier( fnTag, - request.common.messageType.toString(), - MessageType.COMMIT_TRANSFER_COMPLETE.toString(), + request.common, + sessionData, + MessageType.COMMIT_TRANSFER_COMPLETE, ); } - if ( - sessionData.lastSequenceNumber + BigInt(1) != - request.common.sequenceNumber - ) { - throw SequenceNumberMissMatch( - fnTag, - request.common.sequenceNumber, - sessionData.lastSequenceNumber, - ); - } - - if ( - getMessageHash(sessionData, MessageType.ACK_COMMIT_FINAL) != - request.common.hashPreviousMessage - ) { - throw HashMissMatch( - fnTag, - request.common.hashPreviousMessage, - getMessageHash(sessionData, MessageType.ACK_COMMIT_FINAL), - ); - } - - if ( - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_REQUEST) != - request.hashTransferCommence - ) { - throw HashMissMatch( - fnTag, - request.hashTransferCommence, - getMessageHash(sessionData, MessageType.TRANSFER_COMMENCE_REQUEST), - ); - } - - if (sessionData.clientGatewayPubkey != request.common.clientGatewayPubkey) { - throw MissingClientGatewayPubkey(fnTag); - } - - if (sessionData.serverGatewayPubkey != request.common.serverGatewayPubkey) { - throw MissingServerGatewayPubkey(fnTag); - } - - if ( - !verifySignature(this.Signer, request, request.common.clientGatewayPubkey) - ) { - throw SignatureVerificationFailed(fnTag); - } - - this.Log.info( - `${fnTag}, TransferCompleteRequestMessage passed all checks.`, - ); - - if ( - sessionData.transferContextId != undefined && - request.common.transferContextId != sessionData.transferContextId - ) { - throw TransferContextIdMissMatch( - fnTag, - request.common.transferContextId, - sessionData.transferContextId, - ); - } + signatureVerifier(fnTag, this.Signer, request, sessionData); if ( sessionData.clientTransferNumber != undefined && @@ -591,17 +378,25 @@ export class Stage3ServerService extends SATPService { getHash(request), ); - return sessionData; + this.Log.info( + `${fnTag}, TransferCompleteRequestMessage passed all checks.`, + ); } + async mintAsset(session: SATPSession): Promise { const stepTag = `mintAsset()`; const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; try { this.Log.info(`${fnTag}, Minting Asset...`); - const sessionData = session.getServerSessionData(); - if (sessionData == undefined) { - throw new Error(`${fnTag}, Session data not found`); + + if (session == undefined) { + throw new SessionError(fnTag); } + + session.verify(fnTag, SessionType.SERVER); + + const sessionData = session.getServerSessionData(); + const assetId = sessionData.transferInitClaims?.digitalAssetId; const amount = sessionData.transferInitClaims?.amountToBeneficiary; @@ -634,10 +429,15 @@ export class Stage3ServerService extends SATPService { const fnTag = `${this.getServiceIdentifier()}#${stepTag}`; try { this.Log.info(`${fnTag}, Assigning Asset...`); - const sessionData = session.getServerSessionData(); - if (sessionData == undefined) { - throw new Error(`${fnTag}, Session data not found`); + + if (session == undefined) { + throw new SessionError(fnTag); } + + session.verify(fnTag, SessionType.SERVER); + + const sessionData = session.getServerSessionData(); + const assetId = sessionData.transferInitClaims?.digitalAssetId; const amount = sessionData.transferInitClaims?.amountToBeneficiary; const recipient = sessionData.transferInitClaims?.beneficiaryPubkey; diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/common/session_pb.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/common/session_pb.ts index 6ec707d790..39ea829e99 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/common/session_pb.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/common/session_pb.ts @@ -337,6 +337,11 @@ export class SessionData extends Message { */ assetProfile?: AssetProfile; + /** + * @generated from field: string resource_url = 61; + */ + resourceUrl = ""; + constructor(data?: PartialMessage) { super(); proto3.util.initPartial(data, this); @@ -405,6 +410,7 @@ export class SessionData extends Message { { no: 58, name: "server_transfer_number", kind: "scalar", T: 9 /* ScalarType.STRING */ }, { no: 59, name: "lock_assertion_expiration", kind: "scalar", T: 4 /* ScalarType.UINT64 */ }, { no: 60, name: "asset_profile", kind: "message", T: AssetProfile }, + { no: 61, name: "resource_url", kind: "scalar", T: 9 /* ScalarType.STRING */ }, ]); static fromBinary(bytes: Uint8Array, options?: Partial): SessionData { diff --git a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/stage_1_pb.ts b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/stage_1_pb.ts index 498ac7b5e2..e40e13871f 100644 --- a/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/stage_1_pb.ts +++ b/packages/cactus-plugin-satp-hermes/src/main/typescript/generated/proto/cacti/satp/v02/stage_1_pb.ts @@ -105,7 +105,7 @@ export class TransferProposalReceiptMessage extends Message): TransferProposalReceiptMessage { 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 index dfa48a7152..02ea361a6f 100644 --- 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 @@ -221,6 +221,7 @@ export class SATPManager { bridgeManager: this.bridgesManager, })); } + private initializeServices( serviceClasses: SATPServiceInstance[], serviceOptions: ISATPServiceOptions[], diff --git a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/services.test.ts b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/services.test.ts index a93038dc2f..4782c1d440 100644 --- a/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/services.test.ts +++ b/packages/cactus-plugin-satp-hermes/src/test/typescript/unit/services.test.ts @@ -153,8 +153,8 @@ describe("SATP Services Testing", () => { "hex", ); sessionData.serverGatewayPubkey = sessionData.clientGatewayPubkey; - sessionData.originatorPubkey = sessionData.clientGatewayPubkey; - sessionData.beneficiaryPubkey = sessionData.clientGatewayPubkey; + sessionData.originatorPubkey = "MOCK_ORIGINATOR_PUBKEY"; + sessionData.beneficiaryPubkey = "MOCK_BENEFICIARY_PUBKEY"; sessionData.digitalAssetId = "MOCK_DIGITAL_ASSET_ID"; sessionData.assetProfileId = "MOCK_ASSET_PROFILE_ID"; sessionData.verifiedOriginatorEntityId = @@ -162,6 +162,7 @@ describe("SATP Services Testing", () => { sessionData.verifiedBeneficiaryEntityId = "MOCK_VERIFIED_BENEFICIARY_ENTITY_ID"; sessionData.receiverGatewayOwnerId = "MOCK_RECEIVER_GATEWAY_OWNER_ID"; + sessionData.recipientGatewayNetworkId = "MOCK_RECIPIENT_GATEWAY_NETWORK_ID"; sessionData.senderGatewayOwnerId = SupportedChain.FABRIC; sessionData.senderGatewayNetworkId = SupportedChain.BESU; sessionData.signatureAlgorithm = SignatureAlgorithm.RSA; @@ -170,6 +171,8 @@ describe("SATP Services Testing", () => { sessionData.credentialProfile = CredentialProfile.X509; sessionData.loggingProfile = "MOCK_LOGGING_PROFILE"; sessionData.accessControlProfile = "MOCK_ACCESS_CONTROL_PROFILE"; + sessionData.resourceUrl = "MOCK_RESOURCE_URL"; + sessionData.lockAssertionExpiration = BigInt(99999); transferProposalRequestMessage = (await satpClientService1.transferProposalRequest( diff --git a/yarn.lock b/yarn.lock index dd1f043ea8..a7c63bdb6e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -39733,7 +39733,7 @@ __metadata: languageName: node linkType: hard -"node-fetch@npm:^3.3.2": +"node-fetch@npm:^3.2.10, node-fetch@npm:^3.3.2": version: 3.3.2 resolution: "node-fetch@npm:3.3.2" dependencies: