From 2ab9801cdd8a6ef29ee3a78dbafb80a6b0f60028 Mon Sep 17 00:00:00 2001 From: Mohammad Kermani Date: Fri, 13 Sep 2024 17:17:05 +0330 Subject: [PATCH] chore: remove legacy packages --- .changeset/few-rings-flash.md | 2 + .dockerignore | 2 - package-lock.json | 226 ----- packages-legacy/.gitkeep | 0 packages-legacy/p2p-node/.eslintignore | 1 - packages-legacy/p2p-node/README.md | 31 - packages-legacy/p2p-node/lib/errors.ts | 5 - packages-legacy/p2p-node/lib/index.ts | 834 ------------------ .../lib/message-broker/MessageBroker.ts | 48 - .../lib/message-broker/MessageRetryHelper.ts | 103 --- .../p2p-node/lib/message-broker/types.ts | 11 - packages-legacy/p2p-node/lib/types/index.ts | 47 - packages-legacy/p2p-node/lib/utils.ts | 20 - packages-legacy/p2p-node/package.json | 55 -- packages-legacy/p2p-node/tests/.gitkeep | 0 .../lib/message-broker/MessageBroker.spec.ts | 165 ---- .../p2p-node/tests/lib/utils.spec.ts | 43 - .../p2p-node/tests/lib/utilsTestData.ts | 7 - packages-legacy/p2p-node/tsconfig.build.json | 7 - packages-legacy/p2p-node/tsconfig.json | 7 - packages-legacy/p2p-node/vitest.config.ts | 11 - packages-legacy/p2p-relay/.eslintignore | 1 - packages-legacy/p2p-relay/README.md | 31 - packages-legacy/p2p-relay/lib/index.ts | 100 --- packages-legacy/p2p-relay/lib/types/index.ts | 5 - packages-legacy/p2p-relay/lib/utils.ts | 62 -- packages-legacy/p2p-relay/package.json | 45 - packages-legacy/p2p-relay/tests/.gitkeep | 0 packages-legacy/p2p-relay/tsconfig.build.json | 7 - packages-legacy/p2p-relay/tsconfig.json | 7 - packages-legacy/p2p-relay/vitest.config.ts | 11 - services-legacy/relay/.eslintignore | 1 - services-legacy/relay/README.md | 9 - services-legacy/relay/config/default.yml | 11 - services-legacy/relay/config/local.yaml | 0 services-legacy/relay/package.json | 47 - services-legacy/relay/relay.json | 0 .../relay/src/configs/extend-yup.ts | 53 -- services-legacy/relay/src/configs/index.ts | 81 -- services-legacy/relay/src/constants.ts | 3 - services-legacy/relay/src/index.ts | 21 - services-legacy/relay/src/types/index.ts | 0 services-legacy/relay/tests/.gitkeep | 0 services-legacy/relay/ts-node-esm-loader.js | 15 - services-legacy/relay/tsconfig.json | 11 - services-legacy/relay/vitest.config.ts | 12 - 46 files changed, 2 insertions(+), 2156 deletions(-) create mode 100644 .changeset/few-rings-flash.md delete mode 100644 packages-legacy/.gitkeep delete mode 100644 packages-legacy/p2p-node/.eslintignore delete mode 100644 packages-legacy/p2p-node/README.md delete mode 100644 packages-legacy/p2p-node/lib/errors.ts delete mode 100644 packages-legacy/p2p-node/lib/index.ts delete mode 100644 packages-legacy/p2p-node/lib/message-broker/MessageBroker.ts delete mode 100644 packages-legacy/p2p-node/lib/message-broker/MessageRetryHelper.ts delete mode 100644 packages-legacy/p2p-node/lib/message-broker/types.ts delete mode 100644 packages-legacy/p2p-node/lib/types/index.ts delete mode 100644 packages-legacy/p2p-node/lib/utils.ts delete mode 100644 packages-legacy/p2p-node/package.json delete mode 100644 packages-legacy/p2p-node/tests/.gitkeep delete mode 100644 packages-legacy/p2p-node/tests/lib/message-broker/MessageBroker.spec.ts delete mode 100644 packages-legacy/p2p-node/tests/lib/utils.spec.ts delete mode 100644 packages-legacy/p2p-node/tests/lib/utilsTestData.ts delete mode 100644 packages-legacy/p2p-node/tsconfig.build.json delete mode 100644 packages-legacy/p2p-node/tsconfig.json delete mode 100644 packages-legacy/p2p-node/vitest.config.ts delete mode 100644 packages-legacy/p2p-relay/.eslintignore delete mode 100644 packages-legacy/p2p-relay/README.md delete mode 100644 packages-legacy/p2p-relay/lib/index.ts delete mode 100644 packages-legacy/p2p-relay/lib/types/index.ts delete mode 100644 packages-legacy/p2p-relay/lib/utils.ts delete mode 100644 packages-legacy/p2p-relay/package.json delete mode 100644 packages-legacy/p2p-relay/tests/.gitkeep delete mode 100644 packages-legacy/p2p-relay/tsconfig.build.json delete mode 100644 packages-legacy/p2p-relay/tsconfig.json delete mode 100644 packages-legacy/p2p-relay/vitest.config.ts delete mode 100644 services-legacy/relay/.eslintignore delete mode 100644 services-legacy/relay/README.md delete mode 100644 services-legacy/relay/config/default.yml delete mode 100644 services-legacy/relay/config/local.yaml delete mode 100644 services-legacy/relay/package.json delete mode 100644 services-legacy/relay/relay.json delete mode 100644 services-legacy/relay/src/configs/extend-yup.ts delete mode 100644 services-legacy/relay/src/configs/index.ts delete mode 100644 services-legacy/relay/src/constants.ts delete mode 100644 services-legacy/relay/src/index.ts delete mode 100644 services-legacy/relay/src/types/index.ts delete mode 100644 services-legacy/relay/tests/.gitkeep delete mode 100644 services-legacy/relay/ts-node-esm-loader.js delete mode 100644 services-legacy/relay/tsconfig.json delete mode 100644 services-legacy/relay/vitest.config.ts diff --git a/.changeset/few-rings-flash.md b/.changeset/few-rings-flash.md new file mode 100644 index 0000000..a845151 --- /dev/null +++ b/.changeset/few-rings-flash.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/.dockerignore b/.dockerignore index 868fbe2..fb0c88b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,3 @@ **/node_modules -# **/dist **/coverage **/.terraform -packages-legacy diff --git a/package-lock.json b/package-lock.json index 1640386..c1d0809 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9246,150 +9246,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "packages-legacy/p2p-node": { - "name": "@rosen-bridge/p2p-node", - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/bootstrap": "^5.0.2", - "@libp2p/interface-connection": "^3.0.6", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "@multiformats/multiaddr": "^11.0.3", - "@rosen-bridge/json-bigint": "^0.1.0", - "@rosen-bridge/logger-interface": "^0.2.0", - "it-pipe": "2.0.4", - "it-pushable": "^3.1.0", - "json-bigint": "^1.0.0", - "libp2p": "^0.41.0", - "lodash-es": "^4.17.21", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } - }, - "packages-legacy/p2p-relay": { - "name": "@rosen-bridge/p2p-relay", - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "libp2p": "^0.41.0", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } - }, - "packages/p2p-node": { - "name": "@rosen-bridge/p2p-node", - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/bootstrap": "^5.0.2", - "@libp2p/interface-connection": "^3.0.6", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "@multiformats/multiaddr": "^11.0.3", - "@rosen-bridge/json-bigint": "^0.1.0", - "@rosen-bridge/logger-interface": "^0.2.0", - "it-pipe": "2.0.4", - "it-pushable": "^3.1.0", - "json-bigint": "^1.0.0", - "libp2p": "^0.41.0", - "lodash-es": "^4.17.21", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } - }, - "packages/p2p-relay": { - "name": "@rosen-bridge/p2p-relay", - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "libp2p": "^0.41.0", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } - }, "packages/rosenet-node": { "name": "@rosen-bridge/rosenet-node", "version": "0.0.0", @@ -10204,66 +10060,6 @@ "node": ">=20.11.0" } }, - "services-legacy/relay": { - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@multiformats/multiaddr": "^12.1.7", - "@rosen-bridge/p2p-relay": "^0.1.0", - "@rosen-bridge/winston-logger": "^0.2.1", - "config": "^3.3.7", - "is-valid-path": "^0.1.1", - "lodash-es": "^4.17.21", - "yup": "^1.3.2" - }, - "devDependencies": { - "@types/config": "^0.0.41", - "@types/is-valid-path": "^0.1.0", - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-c8": "^0.26.3", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "ts-node": "^10.7.0", - "tsconfig-paths": "^4.1.2", - "typescript": "^5.0.0", - "vitest": "^0.26.2" - } - }, - "services/relay": { - "version": "0.1.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@multiformats/multiaddr": "^12.1.7", - "@rosen-bridge/p2p-relay": "^0.1.0", - "@rosen-bridge/winston-logger": "^0.2.1", - "config": "^3.3.7", - "is-valid-path": "^0.1.1", - "lodash-es": "^4.17.21", - "yup": "^1.3.2" - }, - "devDependencies": { - "@types/config": "^0.0.41", - "@types/is-valid-path": "^0.1.0", - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-c8": "^0.26.3", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "ts-node": "^10.7.0", - "tsconfig-paths": "^4.1.2", - "typescript": "^5.0.0", - "vitest": "^0.26.2" - } - }, "tests/basic-messaging": { "name": "@rosenet-tests/basic-messaging", "version": "0.0.0", @@ -10285,28 +10081,6 @@ "typescript": "^5.3.3" } }, - "tests/local-test": { - "name": "@rosenet-tests/local-test", - "version": "0.0.0", - "extraneous": true, - "license": "GPL-3.0", - "dependencies": { - "@rosen-bridge/rosenet-node": "^0.0.0", - "@rosen-bridge/rosenet-relay": "^0.0.0" - }, - "devDependencies": { - "@types/node": "^20.11.9", - "@typescript-eslint/eslint-plugin": "^6.19.1", - "@typescript-eslint/parser": "^6.19.1", - "eslint": "^8.56.0", - "eslint-config-prettier": "^9.1.0", - "extensionless": "^1.9.6", - "prettier": "^3.2.4", - "ts-node": "^10.7.0", - "tsconfig-paths": "^4.1.2", - "typescript": "^5.3.3" - } - }, "tests/scaling": { "name": "@rosenet-tests/scaling", "version": "0.0.0", diff --git a/packages-legacy/.gitkeep b/packages-legacy/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages-legacy/p2p-node/.eslintignore b/packages-legacy/p2p-node/.eslintignore deleted file mode 100644 index 1521c8b..0000000 --- a/packages-legacy/p2p-node/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -dist diff --git a/packages-legacy/p2p-node/README.md b/packages-legacy/p2p-node/README.md deleted file mode 100644 index 94a4c1e..0000000 --- a/packages-legacy/p2p-node/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# @rosen-bridge/p2p-node - -## Table of contents - -- [@rosen-bridge/p2p-node](#rosen-bridgep2p-node) - - [Table of contents](#table-of-contents) - - [Introduction](#introduction) - - [Installation](#installation) - - [Usage](#usage) - -## Introduction - -Rosen Bridge p2p node, used inside guards. - -## Installation - -npm: - -```sh -npm i @rosen-bridge/p2p-node -``` - -yarn: - -```sh -yarn add @rosen-bridge/p2p-node -``` - -## Usage - -TBD diff --git a/packages-legacy/p2p-node/lib/errors.ts b/packages-legacy/p2p-node/lib/errors.ts deleted file mode 100644 index 079c693..0000000 --- a/packages-legacy/p2p-node/lib/errors.ts +++ /dev/null @@ -1,5 +0,0 @@ -export class NotStartedP2PNodeError extends Error { - constructor() { - super("P2P node isn't ready, please try later"); - } -} diff --git a/packages-legacy/p2p-node/lib/index.ts b/packages-legacy/p2p-node/lib/index.ts deleted file mode 100644 index 44f210b..0000000 --- a/packages-legacy/p2p-node/lib/index.ts +++ /dev/null @@ -1,834 +0,0 @@ -import fs from 'fs'; -import * as lp from 'it-length-prefixed'; -import map from 'it-map'; -import { pipe } from 'it-pipe'; -import { pushable, Pushable } from 'it-pushable'; -import { createLibp2p, Libp2p } from 'libp2p'; -import { toString as uint8ArrayToString } from 'uint8arrays'; - -import { groupBy, negate } from 'lodash-es'; - -import { gossipsub } from '@chainsafe/libp2p-gossipsub'; -import { noise } from '@chainsafe/libp2p-noise'; - -import { bootstrap } from '@libp2p/bootstrap'; -import { Connection, Stream } from '@libp2p/interface-connection'; -import { OPEN } from '@libp2p/interface-connection/status'; -import { PeerId } from '@libp2p/interface-peer-id'; -import { mplex } from '@libp2p/mplex'; -import { createEd25519PeerId, createFromJSON } from '@libp2p/peer-id-factory'; -import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'; -import { webSockets } from '@libp2p/websockets'; - -import * as multiaddr from '@multiformats/multiaddr'; - -import JsonBigInt from '@rosen-bridge/json-bigint'; -import { AbstractLogger, DummyLogger } from '@rosen-bridge/logger-interface'; - -import MessageBroker from './message-broker/MessageBroker'; - -import { objectToUint8Array } from './utils'; - -import { NotStartedP2PNodeError } from './errors'; - -import { - ConnectionStream, - Message, - P2PNodeConfig, - SubscribeChannel, - SubscribeChannels, - SubscribeChannelWithURL, -} from './types'; - -class P2PNode { - private static instance: P2PNode; - private static config: P2PNodeConfig; - private static logger: AbstractLogger; - - private _node: Libp2p | undefined; - private _subscribedChannels: SubscribeChannels = {}; - - private messageBroker!: MessageBroker; - - private constructor() { - P2PNode.logger.info('P2PNode constructor called.'); - } - - public static initialize = async ( - config: P2PNodeConfig, - logger: AbstractLogger = new DummyLogger(), - ) => { - if (!P2PNode.instance) { - P2PNode.logger = logger; - P2PNode.logger.debug('P2PNode logger set'); - - P2PNode.instance = new P2PNode(); - P2PNode.logger.debug('P2PNode instance created'); - - P2PNode.config = config; - P2PNode.logger.debug('P2PNode config set'); - - await P2PNode.instance.startP2PNode(); - P2PNode.logger.debug('P2PNode instance started'); - - P2PNode.instance.messageBroker = new MessageBroker( - { - exponentialFactor: config.messageSendingRetriesExponentialFactor, - maxRetries: Number(config.messageSendingRetriesMaxCount), - }, - logger, - ); - P2PNode.instance.messageBroker.startRouting( - P2PNode.instance.routeMessage, - ); - - P2PNode.logger.debug('P2PNode message queue processing started'); - } else { - P2PNode.logger.debug( - 'P2PNode is already initialized, avoiding re-initialization', - ); - } - }; - - /** - * @return a P2PNode instance (create if it doesn't exist) - */ - public static getInstance = async () => { - return P2PNode.instance; - }; - - /** - * return PeerID or create PeerID if it doesn't exist - * @return PeerID - */ - static getOrCreatePeerID = async (): Promise<{ - peerId: PeerId; - exist: boolean; - }> => { - try { - const peerIdFilePath = P2PNode.config.peerIdFilePath; - if (!fs.existsSync(peerIdFilePath)) { - P2PNode.logger.debug( - "peerId file didn't exist, generating a new peerId.", - { - peerIdFilePath, - }, - ); - return { - peerId: await createEd25519PeerId(), - exist: false, - } as const; - } else { - P2PNode.logger.debug( - 'peerId file exists, reading and returning the contents of the file as peerId.', - { - peerIdFilePath, - }, - ); - const jsonData = fs.readFileSync(peerIdFilePath, 'utf8'); - const p2pNodePeerIdJson: Parameters['0'] = - JSON.parse(jsonData); - P2PNode.logger.debug('PeerId file read and parsed successfully.'); - return { - peerId: await createFromJSON(p2pNodePeerIdJson), - exist: true, - }; - } - } catch (error) { - throw new Error(`Couldn't get or create a PeerID: ${error}`); - } - }; - - /** - * If it didn't exist PeerID file, this function try to create a file and save peerId into that - * @param peerObj { peerId: PeerId; exist: boolean } - */ - static savePeerIdIfNeeded = async (peerObj: { - peerId: PeerId; - exist: boolean; - }) => { - if (!peerObj.exist) { - const peerId = peerObj.peerId; - let privateKey: Uint8Array; - let publicKey: Uint8Array; - if (peerId.privateKey && peerId.publicKey) { - privateKey = peerId.privateKey; - publicKey = peerId.publicKey; - } else throw new Error('PrivateKey for p2p is required'); - - const p2pNodePeerIdJson = { - id: peerId.toString(), - privKey: uint8ArrayToString(privateKey, 'base64pad'), - pubKey: uint8ArrayToString(publicKey, 'base64pad'), - }; - const jsonData = JSON.stringify(p2pNodePeerIdJson); - fs.writeFile( - P2PNode.config.peerIdFilePath, - jsonData, - 'utf8', - function (error) { - if (error) { - P2PNode.logger.warn( - `An error occurred while writing created PeerId to the file.`, - ); - error.stack && P2PNode.logger.warn(error.stack); - throw error; - } - P2PNode.logger.info('PeerId file created.'); - }, - ); - } else { - P2PNode.logger.debug('PeerId exists, ignored saving to file.', { - peerObj, - }); - } - }; - - /** - * Only used for Typescript narrowing. - * @returns if channel has URL - */ - private hasUrl = ( - channel: SubscribeChannel, - ): channel is SubscribeChannelWithURL => - !!(channel as SubscribeChannelWithURL).url; - - /** - * @return list of subscribed channels' name - */ - getSubscribedChannels = () => { - return Object.keys(this._subscribedChannels); - }; - - /** - * @return P2PNode's Id - */ - getP2PNodeId = () => { - if (!this._node) { - throw new NotStartedP2PNodeError(); - } - return this._node.peerId.toString(); - }; - - /** - * @return string of PeerID - */ - getPeerIds = () => { - if (!this._node) { - throw new NotStartedP2PNodeError(); - } - return this._node.getPeers().map((peer) => peer.toString()); - }; - - /** - * @return discovered peers count in the address book - */ - getDiscoveredPeersCount = async () => { - if (!this._node) { - throw new NotStartedP2PNodeError(); - } - return (await this._node.peerStore.all()).length; - }; - - /** - * @returns connected peers count - */ - getConnectedPeersCount = () => { - return this.getPeerIds().length; - }; - - /** - * @returns relay states grouped by the connection status - */ - getRelayStates = () => { - const connectedPeers = this.getPeerIds(); - const relayStates = groupBy(P2PNode.config.relays.peerIDs, (peer) => - connectedPeers.includes(peer) ? 'connected' : 'notConnected', - ); - return relayStates; - }; - - /** - * Checks if a peer belongs to a relay - * - * @param peer - */ - isRelay = (peer: string) => P2PNode.config.relays.peerIDs.includes(peer); - - /** - * Checks if a peer belongs to a listener (and not a relay) - * - * @param peer - */ - isListener = negate(this.isRelay); - - /** - * establish connection to relay - * @param channel: string desire channel for subscription - * @param callback: a callback function for subscribed channel - * @param url: string for apiCallbackFunction - */ - subscribeChannel = ( - channel: string, - callback: SubscribeChannel['func'], - url?: string, - ) => { - const callbackObj = { - func: callback, - ...(url && { url }), - } as SubscribeChannel; - - if (this._subscribedChannels[channel]) { - if ( - this._subscribedChannels[channel].find( - (sub) => - sub.func.name === callback.name && - ((this.hasUrl(sub) && sub.url === url) || !url), - ) - ) { - P2PNode.logger.info('A redundant subscribed channel detected.', { - channel, - url, - }); - return; - } - this._subscribedChannels[channel].push(callbackObj); - P2PNode.logger.info(`Channel [${channel}] subscribed.`, { - url, - }); - } else { - this._subscribedChannels[channel] = []; - this._subscribedChannels[channel].push(callbackObj); - P2PNode.logger.info(`Channel [${channel}] subscribed.`, { - url, - }); - } - }; - - /** - * send message to specific peer or broadcast it - * @param channel - * @param data - * @param peerId - */ - sendMessage = async (channel: string, data: string, peerId?: string) => { - if (peerId) { - const message = { - data, - channel: channel, - peerId, - }; - this.messageBroker.enqueue(message); - } else { - // send message for listener peers (not relays) - const peers = this._node!.getPeers().filter((peer) => - this.isListener(peer.toString()), - ); - for (const peer of peers) { - const message = { - data, - channel: channel, - peerId: peer.toString(), - }; - this.messageBroker.enqueue(message); - } - } - }; - - /** - * Creates a `PeerId` object from a string - * @param id peer id string - */ - private createFromString = (id: string) => createFromJSON({ id }); - - /** - * Adds an array of peers to address book. Because `autoDial` is enabled, it - * causes those peers to be dialed, too. - * @param peers id of peers - */ - addPeersToAddressBook = async (peers: string[]) => { - if (this._node) { - for (const peer of peers) { - for (const addr of P2PNode.config.relays.multiaddrs) { - try { - const multi = multiaddr.multiaddr( - addr.concat(`/p2p-circuit/p2p/${peer}`), - ); - if (!this.getPeerIds().includes(peer)) { - await this._node.peerStore.addressBook.add( - await this.createFromString(peer), - [multi], - ); - P2PNode.logger.debug(`Peer [${peer}] added to the address book.`); - } - } catch (error) { - P2PNode.logger.error( - `An error occurred while trying to add peer to address book: ${error}`, - { peer }, - ); - if (error instanceof Error && error.stack) { - P2PNode.logger.error(error.stack); - } - } - } - } - } - }; - - /** - * Removes a peer from the address book. - * @param peer id of peer - */ - removePeerFromAddressBook = async (peer: string) => { - if (this._node) { - try { - await this._node.peerStore.addressBook.delete( - await this.createFromString(peer), - ); - P2PNode.logger.debug(`Peer [${peer}] removed from the address book.`); - } catch (error) { - P2PNode.logger.warn( - `An error occurred while removing peer from address book: ${error}`, - { peer }, - ); - if (error instanceof Error && error.stack) { - P2PNode.logger.warn(error.stack); - } - } - } - }; - - /** - * create or find an open stream for specific peer and protocol - * @param node - * @param peer create or find stream for peer - * @param protocol try to create a stream with this protocol - */ - private getOpenStreamAndConnection = async ( - node: Libp2p, - peer: PeerId, - protocol: string, - ): Promise => { - let connection: Connection | undefined = undefined; - let stream: Stream | undefined = undefined; - - const peerString = peer.toString(); - - for (const conn of node.getConnections(peer)) { - if (conn.stat.status === OPEN) { - for (const obj of conn.streams) { - if ( - obj.stat.protocol === protocol && - obj.stat.direction === 'outbound' - ) { - stream = obj; - break; - } - } - if (stream) { - connection = conn; - P2PNode.logger.debug( - `Found an existing connection and a stream with protocol [${protocol}] to peer [${peerString}].`, - { conn, stream }, - ); - break; - } - } - } - - if (!connection) { - P2PNode.logger.debug( - `Found no connection to peer [${peerString}], trying to dial...`, - ); - connection = await node.dial(peer); - P2PNode.logger.debug(`Peer [${peerString}] dialed successfully.`, { - connection, - }); - } - if (!stream) { - P2PNode.logger.debug( - `Found no stream with protocol [${protocol}] to peer [${peerString}], trying to create a new one...`, - ); - stream = await connection.newStream([protocol]); - P2PNode.logger.debug( - `A new stream with protocol [${protocol}] to peer [${peerString}] created successfully.`, - { stream }, - ); - } - return { - stream: stream, - connection: connection, - }; - }; - - /** - * handle incoming messages with `config.protocol` protocol - * @param stream - * @param connection - */ - private handleIncomingMessage = async ( - stream: Stream, - connection: Connection, - ) => { - pipe( - // Read from the stream (the source) - stream.source, - // Decode length-prefixed data - lp.decode(), - // Turn buffers into strings - (source) => map(source, (buf) => uint8ArrayToString(buf.subarray())), - // Sink function - async (source) => { - try { - P2PNode.logger.debug( - `A new message with [${ - P2PNode.config.protocol - }] protocol received from peer [${connection.remotePeer.toString()}], trying to parse...`, - ); - // For each chunk of data - for await (const rawMessage of source) { - const message: Message = JsonBigInt.parse(rawMessage.toString()); - - P2PNode.logger.debug( - `The new message with [${P2PNode.config.protocol}] parsed successfully.`, - { - message, - subscribedChannels: this._subscribedChannels, - fromPeer: connection.remotePeer.toString(), - }, - ); - - const runSubscribeCallback = async (channel: SubscribeChannel) => { - this.hasUrl(channel) - ? channel.func( - message.data, - message.channel, - connection.remotePeer.toString(), - channel.url, - ) - : channel.func( - message.data, - message.channel, - connection.remotePeer.toString(), - ); - }; - if (this._subscribedChannels[message.channel]) { - P2PNode.logger.debug( - `Received a message from [${connection.remotePeer.toString()}] in subscribed channel [${ - message.channel - }].`, - ); - this._subscribedChannels[message.channel].forEach( - runSubscribeCallback, - ); - } else { - P2PNode.logger.debug( - `Received a message from [${connection.remotePeer.toString()}] in unsubscribed channel [${ - message.channel - }].`, - ); - } - } - } catch (error) { - P2PNode.logger.error( - `An error occurred while handling stream callback: ${error}`, - ); - if (error instanceof Error && error.stack) { - P2PNode.logger.error(error.stack); - } - } - }, - ).catch((error) => { - P2PNode.logger.error( - `An error occurred while handling broadcast protocol stream: ${error}`, - ); - P2PNode.logger.error(error.stack); - }); - }; - - /** - * Runs a callback in an interval to log some info - * @param callback - */ - private startLoggingInterval = (callback: () => void) => { - setInterval(callback, P2PNode.config.loggingInterval * 1000); - }; - - /** - * Tries to re-connect to a disconnected relay. If the relay is connected, the - * corresponding interval is cleared and connection manager event listener is - * removed. - * - * @param peer peer of recently disconnected peer - */ - private tryReconnectingRelay = (peer: string) => { - P2PNode.logger.debug(`Trying to re-connect relay ${peer}...`); - - const interval = setInterval(async () => { - const multiaddrIndex = P2PNode.config.relays.peerIDs.findIndex( - (id) => id === peer, - ); - P2PNode.logger.debug(`Trying to add relay to address book...`, { peer }); - try { - await this._node?.peerStore.addressBook.add( - await this.createFromString(peer), - [ - multiaddr.multiaddr( - P2PNode.config.relays.multiaddrs[multiaddrIndex], - ), - ], - ); - P2PNode.logger.debug(`Relay added to address book successfully.`, { - peer, - }); - } catch (error) { - P2PNode.logger.warn( - `An error occurred while trying to add relay [${peer}] to address book: ${error}`, - ); - if (error instanceof Error && error.stack) { - P2PNode.logger.warn(error.stack); - } - } - }, P2PNode.config.relayReconnectionInterval * 1000); - - const controller = new AbortController(); - - this._node?.connectionManager.addEventListener( - 'peer:connect', - async (evt) => { - const connectedPeer = evt.detail.remotePeer.toString(); - - if (connectedPeer === peer) { - P2PNode.logger.info(`Relay ${peer} re-connected successfully.`); - clearInterval(interval); - P2PNode.logger.debug('Relay re-connection interval cleared.', { - peer, - }); - controller.abort(); - P2PNode.logger.debug('Relay re-connection event listener removed.', { - peer, - }); - } - }, - { signal: controller.signal }, - ); - }; - - /** - * - * config a p2p node with peerDiscovery - * @return a Libp2p object after start node - */ - private startP2PNode = async () => { - try { - const peerId = await P2PNode.getOrCreatePeerID(); - const node = await createLibp2p({ - // get or create new PeerID if it doesn't exist - peerId: peerId.peerId, - // Type of communication - transports: [webSockets()], - // Enable module encryption message - connectionEncryption: [noise()], - streamMuxers: [ - // mplex is a Stream Multiplexer protocol - mplex(), - ], - relay: { - // Circuit Relay options (this config is part of libp2p core configurations) - enabled: true, // Allows you to dial and accept relayed connections. - autoRelay: { - enabled: true, - }, - }, - connectionManager: { - minConnections: P2PNode.config.guardsCount + 10, // We add 10 to handle relays and other possible connections - }, - pubsub: gossipsub({ allowPublishToZeroPeers: true }), - peerDiscovery: [ - bootstrap({ - timeout: P2PNode.config.bootstrapTimeout * 1000, - list: P2PNode.config.relays.multiaddrs, - }), - pubsubPeerDiscovery({ - interval: P2PNode.config.pubsubInterval * 1000, - }), - ], - }); - - P2PNode.logger.debug('libp2p instance created.'); - - // Listen for peers disconnecting - node.connectionManager.addEventListener( - 'peer:disconnect', - async (evt) => { - const peer = evt.detail.remotePeer.toString(); - - this.removePeerFromAddressBook(peer); - - if (this.isRelay(peer)) { - P2PNode.logger.warn(`Relay [${peer}] disconnected.`); - this.tryReconnectingRelay(peer); - } else { - P2PNode.logger.info(`Peer [${peer}] disconnected.`); - } - }, - ); - - // Listen for new peers - node.addEventListener('peer:discovery', async (evt) => { - if (this.isListener(evt.detail.id.toString())) { - P2PNode.logger.debug(`Found peer [${evt.detail.id.toString()}].`); - this.addPeersToAddressBook([evt.detail.id.toString()]).catch( - (error) => { - P2PNode.logger.error( - `An error occurred while dialing peer [${evt.detail.id}].`, - ); - P2PNode.logger.error(error.stack); - }, - ); - } - }); - - // Define protocol for node - await node.handle( - P2PNode.config.protocol, - async ({ stream, connection }) => { - // Read the stream - this.handleIncomingMessage(stream, connection); - }, - { - maxInboundStreams: - P2PNode.config.guardsCount * P2PNode.config.allowedStreamsPerGuard, - maxOutboundStreams: - P2PNode.config.guardsCount * P2PNode.config.allowedStreamsPerGuard, - }, - ); - - await node.start(); - P2PNode.logger.info( - `P2PNode node started with peerId: ${node.peerId.toString()}.`, - ); - - this._node = node; - - // this should call after createRelayConnection duo to peerId should save after create relay connection - await P2PNode.savePeerIdIfNeeded(peerId); - - /** - * TODO: This is not the ideal way to increase the streams limits, but there - * seems to be no other way to do it with current libp2p apis. It needs to - * be changed if such an api is added in the future. - * - * Related issues: - * - https://github.com/libp2p/js-libp2p/issues/1518 - * - local:ergo/rosen-bridge/p2p#6 - */ - const handler = node.registrar.getHandler('/libp2p/circuit/relay/0.1.0'); - node.registrar.unhandle('/libp2p/circuit/relay/0.1.0'); - await node.registrar.handle( - '/libp2p/circuit/relay/0.1.0', - handler.handler, - { - ...handler.options, - maxInboundStreams: - P2PNode.config.guardsCount * P2PNode.config.allowedStreamsPerGuard, - maxOutboundStreams: - P2PNode.config.guardsCount * P2PNode.config.allowedStreamsPerGuard, - }, - ); - - // Log peers discovery and connection state - this.startLoggingInterval(async () => { - const requiredPeersCount = - P2PNode.config.guardsCount - 1 + P2PNode.config.relays.peerIDs.length; - const discoveredPeersCount = await this.getDiscoveredPeersCount(); - const connectedPeersCount = this.getConnectedPeersCount(); - const remainingRequiredDiscoveries = - requiredPeersCount - discoveredPeersCount; - const remainingRequiredConnections = - requiredPeersCount - connectedPeersCount; - P2PNode.logger.info( - `[${discoveredPeersCount}] peers are discovered. Required discoveries remaining: ${remainingRequiredDiscoveries}`, - ); - P2PNode.logger.info( - `[${connectedPeersCount}] out of [${discoveredPeersCount}] discovered peers are connected. Required connections remaining: ${remainingRequiredConnections}`, - ); - P2PNode.logger.debug(`Connected peers are: [${this.getPeerIds()}].`); - }); - - // Log relays connection state - this.startLoggingInterval(() => { - const relayStates = this.getRelayStates(); - P2PNode.logger.debug('Relays connection states: ', { relayStates }); - - if (relayStates.notConnected?.length) { - if (relayStates.connected?.length) { - P2PNode.logger.warn( - `[${relayStates.notConnected.length}] out of [${P2PNode.config.relays.peerIDs.length}] relays are not connected.`, - ); - } else { - P2PNode.logger.error( - `None of [${P2PNode.config.relays.peerIDs.length}] relays are connected. The service won't work properly until at least one relay is connected.`, - ); - } - } - }); - } catch (error) { - P2PNode.logger.error(`An error occurred while starting p2p node.`); - if (error instanceof Error && error.stack) { - P2PNode.logger.error(error.stack); - } - } - }; - - /** - * send a message to its corresponding peer - * @param message - */ - private routeMessage = async (message: Message) => { - const routesInfo: Record< - string, - { - source: Pushable; - stream: Stream; - } - > = {}; - - /** - * Returns the source piped to the provided stream - * @param stream - * @param peer - * @returns The source which is piped to the stream - */ - const getStreamSource = (stream: Stream, peer: string) => { - if (routesInfo[peer]?.stream === stream) { - return routesInfo[peer].source; - } else { - routesInfo[peer] = { - source: pushable(), - stream: stream, - }; - const source = routesInfo[peer].source; - pipe(source, lp.encode(), stream.sink); - return source; - } - }; - - const connStream = await this.getOpenStreamAndConnection( - this._node!, - await this.createFromString(message.peerId), - P2PNode.config.protocol, - ); - - try { - const source = getStreamSource(connStream.stream, message.peerId); - source.push(objectToUint8Array(message)); - } catch (error) { - P2PNode.logger.error( - `An error occurred while trying to get stream source: ${error}`, - ); - } - }; -} - -export default P2PNode; diff --git a/packages-legacy/p2p-node/lib/message-broker/MessageBroker.ts b/packages-legacy/p2p-node/lib/message-broker/MessageBroker.ts deleted file mode 100644 index bc1c4a5..0000000 --- a/packages-legacy/p2p-node/lib/message-broker/MessageBroker.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { pushable } from 'it-pushable'; - -import { AbstractLogger } from '@rosen-bridge/logger-interface'; - -import MessageRetryHelper from './MessageRetryHelper'; - -import { MessageBrokerOptions } from './types'; -import { Message } from '../types'; - -class MessageBroker extends MessageRetryHelper { - private queue = pushable(); - - constructor(options: MessageBrokerOptions, logger: AbstractLogger) { - super(options, logger); - logger.debug('MessageBroker instantiated'); - } - - /** - * enqueue a message - * @param message - */ - enqueue = (message: Message) => { - const wrappedMessage = this.wrapMessage(message, 0); - this.queue.push(wrappedMessage); - this.logger.debug('new message enqueued', { message }); - }; - - /** - * start routing messages, sending them to their corresponding targets and - * retrying in case of failure - * @param route - */ - startRouting = async (route: (message: Message) => Promise) => { - this.logger.info('message routing started'); - for await (const wrappedMessage of this.queue) { - try { - const { message } = this.unwrapMessage(wrappedMessage); - await route(message); - this.logger.debug('message sent successfully', { message }); - } catch (error) { - this.logger.debug('failed to send message', wrappedMessage); - this.retryRouting(wrappedMessage, this.queue.push); - } - } - }; -} - -export default MessageBroker; diff --git a/packages-legacy/p2p-node/lib/message-broker/MessageRetryHelper.ts b/packages-legacy/p2p-node/lib/message-broker/MessageRetryHelper.ts deleted file mode 100644 index c960471..0000000 --- a/packages-legacy/p2p-node/lib/message-broker/MessageRetryHelper.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { random } from 'lodash-es'; - -import { AbstractLogger } from '@rosen-bridge/logger-interface'; - -import { objectToUint8Array, uint8ArrayToObject } from '../utils'; - -import { MessageBrokerOptions, WrappedMessage } from './types'; -import { Message } from '../types'; - -class MessageRetryHelper { - constructor( - private options: MessageBrokerOptions, - protected logger: AbstractLogger, - ) {} - - /** - * wrap a message, adding retries to it and converting it to a byte array - * @param message - * @param retries - */ - protected wrapMessage = (message: Message, retries: number) => - objectToUint8Array({ message, retries }); - - /** - * unwrap a wrapped message from a byte array - * @param wrappedMessage - */ - protected unwrapMessage = (wrappedMessage: Uint8Array): WrappedMessage => - uint8ArrayToObject(wrappedMessage); - - /** - * get timeout for a retry round - * @description the timeout grows exponentially as the round increases - * @param retryRound - */ - protected getTimeoutForRetryRound = (retryRound: number) => - 1000 * random(0.8, 1.2) * this.options.exponentialFactor ** retryRound; - - /** - * schedule a message retry, which simply means adding the message to the - * queue after a time - * @param message - * @param round - * @param enqueue - */ - protected scheduleMessageRetry = ( - message: Message, - round: number, - enqueue: (wrappedMessage: Uint8Array) => void, - ) => { - const timeout = this.getTimeoutForRetryRound(round); - - setTimeout(() => { - const newWrappedMessage = this.wrapMessage(message, round); - enqueue(newWrappedMessage); - this.logger.debug( - `retry #${round} for sending failed message, message enqueued`, - { message }, - ); - }, timeout); - - return timeout; - }; - - /** - * try to retry routing a message if tried less than maxRetries - * @param wrappedMessage - * @param enqueue - */ - protected retryRouting = ( - wrappedMessage: Uint8Array, - enqueue: (wrappedMessage: Uint8Array) => void, - ) => { - const { retries, message } = this.unwrapMessage(wrappedMessage); - const currentRetryRound = Number(retries) + 1; - - if (currentRetryRound <= this.options.maxRetries) { - const timeout = this.scheduleMessageRetry( - message, - currentRetryRound, - enqueue, - ); - this.logger.debug( - `message retry#${currentRetryRound} scheduled, retrying in ${timeout}ms`, - { - message, - }, - ); - } else { - this.logger.warn( - `failed to send a message after ${this.options.maxRetries} retries, message dropped`, - ); - this.logger.warn( - 'this is mostly caused as a result of connection issues between current and target nodes', - ); - this.logger.debug(`dropped message:`, { - message, - }); - } - }; -} - -export default MessageRetryHelper; diff --git a/packages-legacy/p2p-node/lib/message-broker/types.ts b/packages-legacy/p2p-node/lib/message-broker/types.ts deleted file mode 100644 index 1acde10..0000000 --- a/packages-legacy/p2p-node/lib/message-broker/types.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Message } from '../types'; - -export interface MessageBrokerOptions { - maxRetries: number; - exponentialFactor: number; -} - -export interface WrappedMessage { - retries: bigint; - message: Message; -} diff --git a/packages-legacy/p2p-node/lib/types/index.ts b/packages-legacy/p2p-node/lib/types/index.ts deleted file mode 100644 index b8f428c..0000000 --- a/packages-legacy/p2p-node/lib/types/index.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Connection, Stream } from '@libp2p/interface-connection'; - -export interface SubscribeChannelWithURL { - func: (msg: string, channel: string, sender: string, url: string) => void; - url: string; -} -export interface SubscribeChannelWithoutURL { - func: (msg: string, channel: string, sender: string) => void; -} -export type SubscribeChannel = - | SubscribeChannelWithURL - | SubscribeChannelWithoutURL; - -export interface SubscribeChannels { - [id: string]: Array; -} - -export interface Message { - data: string; - channel: string; - peerId: string; -} - -export interface ConnectionStream { - connection: Connection; - stream: Stream; -} - -export interface RelayInfo { - peerId: string; - address: string; -} - -export interface P2PNodeConfig { - allowedStreamsPerGuard: number; - apiCallbackTimeout: number; - bootstrapTimeout: number; - guardsCount: number; - loggingInterval: number; - messageSendingRetriesExponentialFactor: number; - messageSendingRetriesMaxCount: bigint; - peerIdFilePath: string; - protocol: string; - pubsubInterval: number; - relayReconnectionInterval: number; - relays: { multiaddrs: string[]; peerIDs: string[] }; -} diff --git a/packages-legacy/p2p-node/lib/utils.ts b/packages-legacy/p2p-node/lib/utils.ts deleted file mode 100644 index 432879e..0000000 --- a/packages-legacy/p2p-node/lib/utils.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - fromString as uint8ArrayFromString, - toString as uint8ArrayToString, -} from 'uint8arrays'; - -import JsonBigInt from '@rosen-bridge/json-bigint'; - -/** - * Converts an object to Uint8Array - * @param object - */ -export const objectToUint8Array = (object: unknown) => - uint8ArrayFromString(JsonBigInt.stringify(object)); - -/** - * Converts a Unit8Array to an object - * @param uint8Array - */ -export const uint8ArrayToObject = (uint8Array: Uint8Array) => - JsonBigInt.parse(uint8ArrayToString(uint8Array)); diff --git a/packages-legacy/p2p-node/package.json b/packages-legacy/p2p-node/package.json deleted file mode 100644 index 2fb1184..0000000 --- a/packages-legacy/p2p-node/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "@rosen-bridge/p2p-node", - "version": "0.1.0", - "description": "Rosen Bridge p2p node, used inside guards", - "repository": "https://github.com/rosen-bridge/p2p", - "license": "GPL-3.0", - "author": "Rosen Team", - "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc --build tsconfig.build.json", - "coverage": "npm run test -- --coverage", - "lint": "eslint --fix . && npm run prettify", - "prettify": "prettier --write . --ignore-path ./.gitignore", - "release": "npm run build && npm publish --access public", - "test": "NODE_OPTIONS=--experimental-specifier-resolution=node vitest", - "type-check": "tsc --noEmit" - }, - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/bootstrap": "^5.0.2", - "@libp2p/interface-connection": "^3.0.6", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "@multiformats/multiaddr": "^11.0.3", - "@rosen-bridge/json-bigint": "^0.1.0", - "@rosen-bridge/logger-interface": "^0.2.0", - "it-pipe": "2.0.4", - "it-pushable": "^3.1.0", - "json-bigint": "^1.0.0", - "libp2p": "^0.41.0", - "lodash-es": "^4.17.21", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } -} diff --git a/packages-legacy/p2p-node/tests/.gitkeep b/packages-legacy/p2p-node/tests/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages-legacy/p2p-node/tests/lib/message-broker/MessageBroker.spec.ts b/packages-legacy/p2p-node/tests/lib/message-broker/MessageBroker.spec.ts deleted file mode 100644 index 4da5cfd..0000000 --- a/packages-legacy/p2p-node/tests/lib/message-broker/MessageBroker.spec.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { describe, expect, it, vi, vitest } from 'vitest'; - -import { DummyLogger } from '@rosen-bridge/logger-interface'; - -import MessageBroker from '../../../lib/message-broker/MessageBroker'; - -/** - * generate fake messages on demand - */ -function* messageGenerator() { - const counter = 0; - while (true) { - yield { - channel: 'somechannel', - data: `hello ${counter}`, - peerId: counter.toString(), - }; - } -} - -/** - * create a fixture for testing message broker - */ -const createFixture = () => { - const maxRetries = 3; - const messageBroker = new MessageBroker( - { - exponentialFactor: 3, - maxRetries, - }, - new DummyLogger(), - ); - - const messagesIterator = messageGenerator(); - - return { messagesIterator, messageBroker, maxRetries }; -}; - -describe('MessageBroker', () => { - /** - * @target - * MessageBroker should broker messages correctly - * - * @dependencies - * - * @scenario - * - instantiate MessageBroker - * - start routing with a mocked route - * - enqueue two messages - * @expected - * the enqueued messages should be routed - */ - it('should broker messages correctly', async () => { - const { - messageBroker, - messagesIterator: [message1, message2], - } = createFixture(); - - const route = vitest.fn(); - messageBroker.startRouting(route); - - messageBroker.enqueue(message1); - messageBroker.enqueue(message2); - - await vi.waitFor(() => { - expect(route).toHaveBeenCalledWith(message1); - expect(route).toHaveBeenCalledWith(message2); - }); - }); - - /** - * @target - * MessageBroker should retry failed messages - * - * @dependencies - * - * @scenario - * - mock timers - * - instantiate MessageBroker - * - mock the passed route to reject for the first call - * - mock the passed route to call a spy on subsequent calls - * - start routing with the mocked route - * - enqueue a message - * - wait for the mocked route to be called once - * - run next set timeout - * @expected - * - the spy should be called - * - the mocked route should be called only twice - */ - it('should retry failed messages', async () => { - vi.useFakeTimers(); - const { - messageBroker, - messagesIterator: [message], - } = createFixture(); - - const spy = vitest.fn(); - const route = vitest - .fn() - .mockRejectedValueOnce(new Error()) - .mockImplementation((message) => { - spy(message); - }); - - messageBroker.startRouting(route); - - messageBroker.enqueue(message); - - await vi.waitFor(() => { - expect(route).toHaveBeenCalledTimes(1); - }); - - vi.advanceTimersToNextTimer(); - - await vi.waitFor(() => { - expect(spy).toHaveBeenCalledWith(message); - expect(route).toHaveBeenCalledTimes(2); - }); - }); - - /** - * @target - * MessageBroker should not retry failed messages forever - * - * @dependencies - * - * @scenario - * - mock timers - * - instantiate MessageBroker - * - mock the passed route to always reject - * - start routing with the mocked route - * - enqueue a message - * - wait for the mocked route to be called for n times, where n equals - * maxRetries - * @expected - * - the mocked route should not be called more than that - */ - it('should not retry failed messages forever', async () => { - vi.useFakeTimers(); - const { - messageBroker, - messagesIterator: [message], - maxRetries, - } = createFixture(); - - const route = vitest.fn().mockRejectedValue(new Error()); - - messageBroker.startRouting(route); - - messageBroker.enqueue(message); - - for (let i = 0; i <= maxRetries; i++) { - await vi.waitFor(() => { - expect(route).toHaveBeenCalledTimes(i + 1); - vi.advanceTimersToNextTimer(); - }); - } - - expect(() => - vi.waitFor(() => { - expect(route).toHaveBeenCalledTimes(5); - }), - ).rejects.toThrow(); - }); -}); diff --git a/packages-legacy/p2p-node/tests/lib/utils.spec.ts b/packages-legacy/p2p-node/tests/lib/utils.spec.ts deleted file mode 100644 index 3a19461..0000000 --- a/packages-legacy/p2p-node/tests/lib/utils.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest'; - -import { objectToUint8Array, uint8ArrayToObject } from '../../lib/utils'; - -import { testData } from './utilsTestData'; - -describe('objectToUint8Array', () => { - /** - * @target - * objectToUint8Array should convert object to Uint8Array correctly - * - * @dependencies - * - * @scenario - * - call the function under test - * @expected - * - converted value should be the expected one - */ - it('should convert object to Uint8Array correctly', () => { - const converted = objectToUint8Array(testData.object); - - expect(converted).toEqual(testData.byteArray); - }); -}); - -describe('uint8ArrayToObject', () => { - /** - * @target - * uint8ArrayToObject should convert Uint8Array to object correctly - * - * @dependencies - * - * @scenario - * - call the function under test - * @expected - * - converted value should be the expected one - */ - it('should convert Uint8Array to object correctly', () => { - const converted = uint8ArrayToObject(testData.byteArray); - - expect(converted).toEqual(testData.object); - }); -}); diff --git a/packages-legacy/p2p-node/tests/lib/utilsTestData.ts b/packages-legacy/p2p-node/tests/lib/utilsTestData.ts deleted file mode 100644 index 80a7fcb..0000000 --- a/packages-legacy/p2p-node/tests/lib/utilsTestData.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const testData = { - object: { hello: 'world' }, - byteArray: new Uint8Array([ - 123, 34, 104, 101, 108, 108, 111, 34, 58, 34, 119, 111, 114, 108, 100, 34, - 125, - ]), -}; diff --git a/packages-legacy/p2p-node/tsconfig.build.json b/packages-legacy/p2p-node/tsconfig.build.json deleted file mode 100644 index 7716522..0000000 --- a/packages-legacy/p2p-node/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./lib" - }, - "exclude": ["tests", "vitest.config.ts"] -} diff --git a/packages-legacy/p2p-node/tsconfig.json b/packages-legacy/p2p-node/tsconfig.json deleted file mode 100644 index a62e484..0000000 --- a/packages-legacy/p2p-node/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "./dist", - }, - "include": ["tests", "lib", "vitest.config.ts"], -} diff --git a/packages-legacy/p2p-node/vitest.config.ts b/packages-legacy/p2p-node/vitest.config.ts deleted file mode 100644 index 39c01f4..0000000 --- a/packages-legacy/p2p-node/vitest.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - coverage: { - all: true, - reporter: ['cobertura', 'text', 'text-summary'], - }, - passWithNoTests: true, - }, -}); diff --git a/packages-legacy/p2p-relay/.eslintignore b/packages-legacy/p2p-relay/.eslintignore deleted file mode 100644 index 1521c8b..0000000 --- a/packages-legacy/p2p-relay/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -dist diff --git a/packages-legacy/p2p-relay/README.md b/packages-legacy/p2p-relay/README.md deleted file mode 100644 index 169aa85..0000000 --- a/packages-legacy/p2p-relay/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# @rosen-bridge/p2p-relay - -## Table of contents - -- [@rosen-bridge/p2p-relay](#rosen-bridgep2p-relay) - - [Table of contents](#table-of-contents) - - [Introduction](#introduction) - - [Installation](#installation) - - [Usage](#usage) - -## Introduction - -Rosen Bridge p2p relay, used inside relay service - -## Installation - -npm: - -```sh -npm i @rosen-bridge/p2p-relay -``` - -yarn: - -```sh -yarn add @rosen-bridge/p2p-relay -``` - -## Usage - -TBD diff --git a/packages-legacy/p2p-relay/lib/index.ts b/packages-legacy/p2p-relay/lib/index.ts deleted file mode 100644 index b5a35f0..0000000 --- a/packages-legacy/p2p-relay/lib/index.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { createLibp2p } from 'libp2p'; - -import { gossipsub } from '@chainsafe/libp2p-gossipsub'; -import { noise } from '@chainsafe/libp2p-noise'; - -import { mplex } from '@libp2p/mplex'; -import { pubsubPeerDiscovery } from '@libp2p/pubsub-peer-discovery'; -import { webSockets } from '@libp2p/websockets'; - -import { getOrCreatePeerID, savePeerIdIfNeed } from './utils'; - -import { RelayNodeConfig } from './types'; - -/** - * start a relay node based on config - * - * @param relayNodeConfig - */ -const startRelay = async (relayNodeConfig: RelayNodeConfig) => { - const peerId = await getOrCreatePeerID(relayNodeConfig.peerIdFilePath); - - const node = await createLibp2p({ - peerId: peerId.peerId, - addresses: { - listen: [`/ip4/0.0.0.0/tcp/${relayNodeConfig.port}/ws`], - }, - transports: [webSockets()], - connectionEncryption: [noise()], - streamMuxers: [mplex()], - relay: { - enabled: true, - hop: { - enabled: true, - timeout: 600_000, // 10 minutes - }, - }, - pubsub: gossipsub({ allowPublishToZeroPeers: true }), - peerDiscovery: [ - pubsubPeerDiscovery({ - interval: 1000, - }), - ], - }); - - // Listen for new peers - node.addEventListener('peer:discovery', (evt) => { - console.log(`Found peer ${evt.detail.id.toString()}`); - }); - - // Listen for new connections to peers - node.connectionManager.addEventListener('peer:connect', (evt) => { - const connection = evt.detail; - - const connectedPeer = connection.remotePeer.toString(); - - if (relayNodeConfig.allowedPeers.includes(connectedPeer)) { - console.log(`Connected to ${connectedPeer}`); - } else { - // Drop connections from disallowed peers - connection.close(); - console.log( - `Connection from ${connectedPeer} rejected due to allow list config`, - ); - } - }); - - // Listen for peers disconnecting - node.connectionManager.addEventListener('peer:disconnect', (evt) => { - console.log(`Disconnected from ${evt.detail.remotePeer.toString()}`); - }); - - await node.start(); - - await savePeerIdIfNeed(peerId, relayNodeConfig.peerIdFilePath); - - console.log(`Relay node started with id ${node.peerId.toString()}`); - console.log('Listening on:'); - node.getMultiaddrs().forEach((ma) => console.log(ma.toString())); - - /** - * TODO: This is not the ideal way to increase the streams limits, but there - * seems to be no other way to do it with current libp2p apis. It needs to - * be changed if such an api is added in the future. - * - * Related issues: - * - https://github.com/libp2p/js-libp2p/issues/1518 - * local:ergo/rosen-bridge/p2p#6 - */ - const handler = node.registrar.getHandler('/libp2p/circuit/relay/0.1.0'); - node.registrar.unhandle('/libp2p/circuit/relay/0.1.0'); - await node.registrar.handle('/libp2p/circuit/relay/0.1.0', handler.handler, { - ...handler.options, - maxInboundStreams: 1000, - maxOutboundStreams: 1000, - }); - - return node; -}; - -export { startRelay }; diff --git a/packages-legacy/p2p-relay/lib/types/index.ts b/packages-legacy/p2p-relay/lib/types/index.ts deleted file mode 100644 index 152bf06..0000000 --- a/packages-legacy/p2p-relay/lib/types/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface RelayNodeConfig { - allowedPeers: string[]; - port: number; - peerIdFilePath: string; -} diff --git a/packages-legacy/p2p-relay/lib/utils.ts b/packages-legacy/p2p-relay/lib/utils.ts deleted file mode 100644 index b82d55a..0000000 --- a/packages-legacy/p2p-relay/lib/utils.ts +++ /dev/null @@ -1,62 +0,0 @@ -import fs from 'fs'; -import { toString as uint8ArrayToString } from 'uint8arrays/to-string'; - -import { PeerId } from '@libp2p/interface-peer-id'; -import { createEd25519PeerId, createFromJSON } from '@libp2p/peer-id-factory'; - -/** - * return PeerID or create PeerID if it doesn't exist - * - * @param peerIdFilePath - */ -const getOrCreatePeerID = async ( - peerIdFilePath: string, -): Promise<{ peerId: PeerId; exist: boolean }> => { - if (!fs.existsSync(peerIdFilePath)) { - return { - peerId: await createEd25519PeerId(), - exist: false, - } as const; - } else { - const jsonData: string = fs.readFileSync(peerIdFilePath, 'utf8'); - const peerIdDialerJson = await JSON.parse(jsonData); - return { - peerId: await createFromJSON(peerIdDialerJson), - exist: true, - }; - } -}; - -/** - * Try to create a file and save peerId into that ff peer id file doesn't exist - * - * @param peerObj - * @param peerIdFilePath - */ -const savePeerIdIfNeed = async ( - peerObj: { peerId: PeerId; exist: boolean }, - peerIdFilePath: string, -): Promise => { - if (!peerObj.exist) { - const peerId = peerObj.peerId; - let privateKey: Uint8Array; - let publicKey: Uint8Array; - if (peerId.privateKey && peerId.publicKey) { - privateKey = peerId.privateKey; - publicKey = peerId.publicKey; - } else throw Error('PrivateKey for p2p is required'); - - const peerIdDialerJson = { - id: peerId.toString(), - privKey: uint8ArrayToString(privateKey, 'base64pad'), - pubKey: uint8ArrayToString(publicKey, 'base64pad'), - }; - const jsonData = JSON.stringify(peerIdDialerJson); - fs.writeFile(peerIdFilePath, jsonData, 'utf8', function (err) { - if (err) throw err; - console.log('PeerId created!'); - }); - } -}; - -export { getOrCreatePeerID, savePeerIdIfNeed }; diff --git a/packages-legacy/p2p-relay/package.json b/packages-legacy/p2p-relay/package.json deleted file mode 100644 index b8460ae..0000000 --- a/packages-legacy/p2p-relay/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "@rosen-bridge/p2p-relay", - "version": "0.1.0", - "description": "Rosen Bridge p2p relay, used inside relay service", - "repository": "https://github.com/rosen-bridge/p2p", - "license": "GPL-3.0", - "author": "Rosen Team", - "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build": "tsc --build tsconfig.build.json", - "coverage": "vitest run --coverage", - "lint": "eslint --fix . && npm run prettify", - "prettify": "prettier --write . --ignore-path ./.gitignore", - "release": "npm run build && npm publish --access public", - "test": "vitest", - "type-check": "tsc --noEmit" - }, - "dependencies": { - "@chainsafe/libp2p-gossipsub": "^5.4.1", - "@chainsafe/libp2p-noise": "^10.2.0", - "@libp2p/interface-peer-id": "^1.1.2", - "@libp2p/mplex": "^7.1.1", - "@libp2p/peer-id-factory": "^1.0.19", - "@libp2p/pubsub-peer-discovery": "^7.0.1", - "@libp2p/websockets": "^5.0.2", - "libp2p": "^0.41.0", - "uint8arrays": "^3.1.0" - }, - "devDependencies": { - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-v8": "^0.34.6", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "typescript": "^5.0.0", - "vitest": "^0.34.6" - }, - "engines": { - "node": ">=18.12.0" - } -} diff --git a/packages-legacy/p2p-relay/tests/.gitkeep b/packages-legacy/p2p-relay/tests/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages-legacy/p2p-relay/tsconfig.build.json b/packages-legacy/p2p-relay/tsconfig.build.json deleted file mode 100644 index 7716522..0000000 --- a/packages-legacy/p2p-relay/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./lib" - }, - "exclude": ["tests", "vitest.config.ts"] -} diff --git a/packages-legacy/p2p-relay/tsconfig.json b/packages-legacy/p2p-relay/tsconfig.json deleted file mode 100644 index a62e484..0000000 --- a/packages-legacy/p2p-relay/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "./dist", - }, - "include": ["tests", "lib", "vitest.config.ts"], -} diff --git a/packages-legacy/p2p-relay/vitest.config.ts b/packages-legacy/p2p-relay/vitest.config.ts deleted file mode 100644 index 39c01f4..0000000 --- a/packages-legacy/p2p-relay/vitest.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - coverage: { - all: true, - reporter: ['cobertura', 'text', 'text-summary'], - }, - passWithNoTests: true, - }, -}); diff --git a/services-legacy/relay/.eslintignore b/services-legacy/relay/.eslintignore deleted file mode 100644 index 1521c8b..0000000 --- a/services-legacy/relay/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -dist diff --git a/services-legacy/relay/README.md b/services-legacy/relay/README.md deleted file mode 100644 index 81fd70f..0000000 --- a/services-legacy/relay/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# relay - -## Table of contents - -- [Introduction](#introduction) - -## Introduction - -Rosen bridge relay service used to connect guards p2p nodes to each other diff --git a/services-legacy/relay/config/default.yml b/services-legacy/relay/config/default.yml deleted file mode 100644 index 464689e..0000000 --- a/services-legacy/relay/config/default.yml +++ /dev/null @@ -1,11 +0,0 @@ -allowedPeers: [] # list of allowed peers multiaddrs -logs: - - type: 'file' # [file, console] - path: './logs/' # path to log files (only for rotateFile type) - maxSize: '20m' # maximum size of each log file (20 MB) (only for rotateFile type) - maxFiles: '14d' # maximum number of log files (14 days) (only for rotateFile type) - level: 'info' # [debug, info, warn, error] - - type: 'console' - level: 'info' -peerIdFilePath: './relay.json' # path to peer id file path -port: 10000 # relay listening port diff --git a/services-legacy/relay/config/local.yaml b/services-legacy/relay/config/local.yaml deleted file mode 100644 index e69de29..0000000 diff --git a/services-legacy/relay/package.json b/services-legacy/relay/package.json deleted file mode 100644 index 83d0c38..0000000 --- a/services-legacy/relay/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "relay", - "private": true, - "version": "0.1.0", - "description": "Rosen bridge relay service used to connect guards p2p nodes to each other", - "repository": "https://github.com/rosen-bridge/p2p", - "license": "GPL-3.0", - "author": "Rosen Team", - "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "scripts": { - "build:prod": "tsc", - "coverage": "vitest run --coverage", - "lint": "eslint --fix . && npm run prettify", - "prettify": "prettier --write . --ignore-path ./.gitignore", - "start": "node --watch --experimental-specifier-resolution=node --loader ./ts-node-esm-loader.js ./src/index.ts", - "start:prod": "node --experimental-specifier-resolution=node ./dist/index.js", - "test": "vitest", - "type-check": "tsc --noEmit" - }, - "dependencies": { - "@multiformats/multiaddr": "^12.1.7", - "@rosen-bridge/p2p-relay": "^0.1.0", - "@rosen-bridge/winston-logger": "^0.2.1", - "config": "^3.3.7", - "is-valid-path": "^0.1.1", - "lodash-es": "^4.17.21", - "yup": "^1.3.2" - }, - "devDependencies": { - "@types/config": "^0.0.41", - "@types/is-valid-path": "^0.1.0", - "@types/lodash-es": "^4.17.9", - "@types/node": "^18.11.18", - "@typescript-eslint/eslint-plugin": "^6.7.0", - "@typescript-eslint/parser": "^6.7.0", - "@vitest/coverage-c8": "^0.26.3", - "eslint": "^8.16.0", - "eslint-config-prettier": "^8.5.0", - "prettier": "2.7.1", - "ts-node": "^10.7.0", - "tsconfig-paths": "^4.1.2", - "typescript": "^5.0.0", - "vitest": "^0.26.2" - } -} diff --git a/services-legacy/relay/relay.json b/services-legacy/relay/relay.json deleted file mode 100644 index e69de29..0000000 diff --git a/services-legacy/relay/src/configs/extend-yup.ts b/services-legacy/relay/src/configs/extend-yup.ts deleted file mode 100644 index ad6463a..0000000 --- a/services-legacy/relay/src/configs/extend-yup.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { addMethod, number, string } from 'yup'; -import isValidPath from 'is-valid-path'; - -import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'; - -declare module 'yup' { - interface StringSchema { - multiaddr(fieldName: string): this; - path(fieldName: string): this; - } - interface NumberSchema { - port(): this; - } -} - -addMethod(string, 'multiaddr', function validateMultiaddr(fieldName: string) { - return this.test( - 'multiaddr', - '"${value}" is not a multiaddr', - (str, context) => { - try { - if (!str) return true; - return isMultiaddr(multiaddr(str)); - } catch { - return context.createError({ - params: { - label: fieldName, - }, - }); - } - }, - ); -}); - -addMethod(string, 'path', function validatePath(fieldName: string) { - return this.test('path', '"${value}" is not a path', (str, context) => { - try { - if (!str) return true; - return isValidPath(str); - } catch { - return context.createError({ - params: { - label: fieldName, - }, - }); - } - }); -}); - -addMethod(number, 'port', function validatePort() { - // The provided numbers are standard server ports range - return this.min(1024).max(49151); -}); diff --git a/services-legacy/relay/src/configs/index.ts b/services-legacy/relay/src/configs/index.ts deleted file mode 100644 index 736944f..0000000 --- a/services-legacy/relay/src/configs/index.ts +++ /dev/null @@ -1,81 +0,0 @@ -import nodeConfig from 'config'; -import { ValidationError, array, number, object, string } from 'yup'; - -import { TransportOptions } from '@rosen-bridge/winston-logger'; - -import './extend-yup'; - -import { - DEFAULT_LOG_LEVEL, - DEFAULT_PEER_ID_FILE_PATH, - DEFAULT_PORT, -} from '../constants'; - -/** - * get all service configs or exit the process in case of invalid configs - */ -const getAllConfigs = () => { - try { - const allowedPeers = array( - string() - .multiaddr('allowedPeers') - .required('allowedPeers should not contain a null or undefined value') - .label('allowedPeers'), - ) - .required() - .min(1) - .label('allowedPeers') - .validateSync(nodeConfig.get('allowedPeers')); - - const logs = array( - object({ - type: string() - .oneOf(['file', 'console']) - .required() - .label('logs[index].type'), - path: string().path('logs[index].path').label('logs[index].path'), - maxSize: string().label('logs[index].maxSize'), - maxFiles: string().label('logs[index].maxFiles'), - level: string() - .required() - .oneOf(['debug', 'info', 'warn', 'error']) - .default(DEFAULT_LOG_LEVEL) - .label('logs[index].level'), - }), - ) - .label('logs') - .validateSync(nodeConfig.get('logs')); - - const peerIdFilePath = string() - .required() - .path('peerIdFilePath') - .label('peerIdFilePath') - .validateSync( - nodeConfig.get('peerIdFilePath') ?? DEFAULT_PEER_ID_FILE_PATH, - ); - - const port = number() - .required() - .port() - .label('port') - .validateSync(nodeConfig.get('port') ?? DEFAULT_PORT); - - return { - allowedPeers, - logs, - peerIdFilePath, - port, - }; - } catch (error) { - if (error instanceof ValidationError) { - console.error(`ConfigError: ${error.message}`); - } else { - console.error(error); - } - process.exit(1); - } -}; - -const config = getAllConfigs(); - -export default config; diff --git a/services-legacy/relay/src/constants.ts b/services-legacy/relay/src/constants.ts deleted file mode 100644 index dbac22a..0000000 --- a/services-legacy/relay/src/constants.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const DEFAULT_LOG_LEVEL = 'info'; -export const DEFAULT_PEER_ID_FILE_PATH = './relay.json'; -export const DEFAULT_PORT = 10000; diff --git a/services-legacy/relay/src/index.ts b/services-legacy/relay/src/index.ts deleted file mode 100644 index 891ddc3..0000000 --- a/services-legacy/relay/src/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { startRelay } from '@rosen-bridge/p2p-relay'; - -import config from './configs'; - -/** - * start the service - */ -const main = async () => { - try { - await startRelay({ - allowedPeers: config.allowedPeers, - peerIdFilePath: config.peerIdFilePath, - port: config.port, - }); - } catch (error) { - console.error(`an error occurred for start relay: [${error}]`); - process.exit(1); - } -}; - -main(); diff --git a/services-legacy/relay/src/types/index.ts b/services-legacy/relay/src/types/index.ts deleted file mode 100644 index e69de29..0000000 diff --git a/services-legacy/relay/tests/.gitkeep b/services-legacy/relay/tests/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/services-legacy/relay/ts-node-esm-loader.js b/services-legacy/relay/ts-node-esm-loader.js deleted file mode 100644 index 6a27e30..0000000 --- a/services-legacy/relay/ts-node-esm-loader.js +++ /dev/null @@ -1,15 +0,0 @@ -import { resolve as resolveTs } from 'ts-node/esm'; -import * as tsConfigPaths from 'tsconfig-paths'; -import { pathToFileURL } from 'url'; - -const { absoluteBaseUrl, paths } = tsConfigPaths.loadConfig(); -const matchPath = tsConfigPaths.createMatchPath(absoluteBaseUrl, paths); - -export function resolve(specifier, ctx, defaultResolve) { - const match = matchPath(specifier); - return match - ? resolveTs(pathToFileURL(`${match}`).href, ctx, defaultResolve) - : resolveTs(specifier, ctx, defaultResolve); -} - -export { load, transformSource } from 'ts-node/esm'; diff --git a/services-legacy/relay/tsconfig.json b/services-legacy/relay/tsconfig.json deleted file mode 100644 index 0deaa44..0000000 --- a/services-legacy/relay/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "outDir": "./dist", - "baseUrl": ".", - }, - "include": ["src"], - "ts-node": { - "esm": true, - }, -} diff --git a/services-legacy/relay/vitest.config.ts b/services-legacy/relay/vitest.config.ts deleted file mode 100644 index ebf132e..0000000 --- a/services-legacy/relay/vitest.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - coverage: { - all: true, - reporter: ['cobertura', 'text', 'text-summary'], - }, - passWithNoTests: true, - threads: false, - }, -});