diff --git a/.eslintrc.json b/.eslintrc.json index 898bee844b..e7b70bc0d5 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -25,6 +25,7 @@ }] } ], + "@typescript-eslint/explicit-member-accessibility": "error", "prettier/prettier": [ "error", { diff --git a/packages/core/src/lib/base_protocol.ts b/packages/core/src/lib/base_protocol.ts index 69a7e29067..64dd435d7a 100644 --- a/packages/core/src/lib/base_protocol.ts +++ b/packages/core/src/lib/base_protocol.ts @@ -25,7 +25,7 @@ export class BaseProtocol implements IBaseProtocolCore { public readonly removeLibp2pEventListener: Libp2p["removeEventListener"]; protected streamManager: StreamManager; - constructor( + protected constructor( public multicodec: string, private components: Libp2pComponents, private log: Logger, @@ -82,7 +82,7 @@ export class BaseProtocol implements IBaseProtocolCore { * @returns A list of peers that support the protocol sorted by latency. */ - async getPeers( + public async getPeers( { numPeers, maxBootstrapPeers diff --git a/packages/core/src/lib/filter/filter_rpc.ts b/packages/core/src/lib/filter/filter_rpc.ts index 5c43c598eb..882f1754e1 100644 --- a/packages/core/src/lib/filter/filter_rpc.ts +++ b/packages/core/src/lib/filter/filter_rpc.ts @@ -8,16 +8,16 @@ import { v4 as uuid } from "uuid"; export class FilterPushRpc { public constructor(public proto: proto.MessagePush) {} - static decode(bytes: Uint8Array): FilterPushRpc { + public static decode(bytes: Uint8Array): FilterPushRpc { const res = proto.MessagePush.decode(bytes); return new FilterPushRpc(res); } - encode(): Uint8Array { + public encode(): Uint8Array { return proto.MessagePush.encode(this.proto); } - get wakuMessage(): WakuMessage | undefined { + public get wakuMessage(): WakuMessage | undefined { return this.proto.wakuMessage; } @@ -25,7 +25,7 @@ export class FilterPushRpc { * Get the pubsub topic from the FilterPushRpc object. * @returns string */ - get pubsubTopic(): string | undefined { + public get pubsubTopic(): string | undefined { return this.proto.pubsubTopic; } } @@ -33,7 +33,7 @@ export class FilterPushRpc { export class FilterSubscribeRpc { public constructor(public proto: proto.FilterSubscribeRequest) {} - static createSubscribeRequest( + public static createSubscribeRequest( pubsubTopic: string, contentTopics: string[] ): FilterSubscribeRpc { @@ -46,7 +46,7 @@ export class FilterSubscribeRpc { }); } - static createUnsubscribeRequest( + public static createUnsubscribeRequest( pubsubTopic: string, contentTopics: string[] ): FilterSubscribeRpc { @@ -59,7 +59,9 @@ export class FilterSubscribeRpc { }); } - static createUnsubscribeAllRequest(pubsubTopic: string): FilterSubscribeRpc { + public static createUnsubscribeAllRequest( + pubsubTopic: string + ): FilterSubscribeRpc { return new FilterSubscribeRpc({ requestId: uuid(), filterSubscribeType: @@ -69,7 +71,7 @@ export class FilterSubscribeRpc { }); } - static createSubscriberPingRequest(): FilterSubscribeRpc { + public static createSubscriberPingRequest(): FilterSubscribeRpc { return new FilterSubscribeRpc({ requestId: uuid(), filterSubscribeType: @@ -79,28 +81,28 @@ export class FilterSubscribeRpc { }); } - static decode(bytes: Uint8Array): FilterSubscribeRpc { + public static decode(bytes: Uint8Array): FilterSubscribeRpc { const res = proto.FilterSubscribeRequest.decode(bytes); return new FilterSubscribeRpc(res); } - encode(): Uint8Array { + public encode(): Uint8Array { return proto.FilterSubscribeRequest.encode(this.proto); } - get filterSubscribeType(): proto.FilterSubscribeRequest.FilterSubscribeType { + public get filterSubscribeType(): proto.FilterSubscribeRequest.FilterSubscribeType { return this.proto.filterSubscribeType; } - get requestId(): string { + public get requestId(): string { return this.proto.requestId; } - get pubsubTopic(): string | undefined { + public get pubsubTopic(): string | undefined { return this.proto.pubsubTopic; } - get contentTopics(): string[] { + public get contentTopics(): string[] { return this.proto.contentTopics; } } @@ -108,24 +110,24 @@ export class FilterSubscribeRpc { export class FilterSubscribeResponse { public constructor(public proto: proto.FilterSubscribeResponse) {} - static decode(bytes: Uint8Array): FilterSubscribeResponse { + public static decode(bytes: Uint8Array): FilterSubscribeResponse { const res = proto.FilterSubscribeResponse.decode(bytes); return new FilterSubscribeResponse(res); } - encode(): Uint8Array { + public encode(): Uint8Array { return proto.FilterSubscribeResponse.encode(this.proto); } - get statusCode(): number { + public get statusCode(): number { return this.proto.statusCode; } - get statusDesc(): string | undefined { + public get statusDesc(): string | undefined { return this.proto.statusDesc; } - get requestId(): string { + public get requestId(): string { return this.proto.requestId; } } diff --git a/packages/core/src/lib/filter/index.ts b/packages/core/src/lib/filter/index.ts index 78d1f61182..97ba6d4fe8 100644 --- a/packages/core/src/lib/filter/index.ts +++ b/packages/core/src/lib/filter/index.ts @@ -32,7 +32,7 @@ export const FilterCodecs = { }; export class FilterCore extends BaseProtocol implements IBaseProtocolCore { - constructor( + public constructor( private handleIncomingMessage: ( pubsubTopic: PubsubTopic, wakuMessage: WakuMessage, @@ -58,47 +58,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore { }); } - private onRequest(streamData: IncomingStreamData): void { - const { connection, stream } = streamData; - const { remotePeer } = connection; - log.info(`Received message from ${remotePeer.toString()}`); - try { - pipe(stream, lp.decode, async (source) => { - for await (const bytes of source) { - const response = FilterPushRpc.decode(bytes.slice()); - - const { pubsubTopic, wakuMessage } = response; - - if (!wakuMessage) { - log.error("Received empty message"); - return; - } - - if (!pubsubTopic) { - log.error("Pubsub topic missing from push message"); - return; - } - - await this.handleIncomingMessage( - pubsubTopic, - wakuMessage, - connection.remotePeer.toString() - ); - } - }).then( - () => { - log.info("Receiving pipe closed."); - }, - (e) => { - log.error("Error with receiving pipe", e); - } - ); - } catch (e) { - log.error("Error decoding message", e); - } - } - - async subscribe( + public async subscribe( pubsubTopic: PubsubTopic, peer: Peer, contentTopics: ContentTopic[] @@ -152,7 +112,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore { }; } - async unsubscribe( + public async unsubscribe( pubsubTopic: PubsubTopic, peer: Peer, contentTopics: ContentTopic[] @@ -198,7 +158,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore { }; } - async unsubscribeAll( + public async unsubscribeAll( pubsubTopic: PubsubTopic, peer: Peer ): Promise { @@ -246,7 +206,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore { }; } - async ping(peer: Peer): Promise { + public async ping(peer: Peer): Promise { let stream: Stream | undefined; try { stream = await this.getStream(peer); @@ -316,4 +276,44 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore { failure: null }; } + + private onRequest(streamData: IncomingStreamData): void { + const { connection, stream } = streamData; + const { remotePeer } = connection; + log.info(`Received message from ${remotePeer.toString()}`); + try { + pipe(stream, lp.decode, async (source) => { + for await (const bytes of source) { + const response = FilterPushRpc.decode(bytes.slice()); + + const { pubsubTopic, wakuMessage } = response; + + if (!wakuMessage) { + log.error("Received empty message"); + return; + } + + if (!pubsubTopic) { + log.error("Pubsub topic missing from push message"); + return; + } + + await this.handleIncomingMessage( + pubsubTopic, + wakuMessage, + connection.remotePeer.toString() + ); + } + }).then( + () => { + log.info("Receiving pipe closed."); + }, + (e) => { + log.error("Error with receiving pipe", e); + } + ); + } catch (e) { + log.error("Error decoding message", e); + } + } } diff --git a/packages/core/src/lib/keep_alive_manager.ts b/packages/core/src/lib/keep_alive_manager.ts index e16e4a0a85..27754b6b38 100644 --- a/packages/core/src/lib/keep_alive_manager.ts +++ b/packages/core/src/lib/keep_alive_manager.ts @@ -26,7 +26,11 @@ export class KeepAliveManager { private relayKeepAliveTimers: Map[]> = new Map(); - constructor({ options, relay, libp2p }: CreateKeepAliveManagerOptions) { + public constructor({ + options, + relay, + libp2p + }: CreateKeepAliveManagerOptions) { this.options = options; this.relay = relay; this.libp2p = libp2p; diff --git a/packages/core/src/lib/light_push/index.ts b/packages/core/src/lib/light_push/index.ts index e1936023f8..ec899d40e5 100644 --- a/packages/core/src/lib/light_push/index.ts +++ b/packages/core/src/lib/light_push/index.ts @@ -32,7 +32,7 @@ type PreparePushMessageResult = ThisOrThat<"query", PushRpc>; * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/). */ export class LightPushCore extends BaseProtocol implements IBaseProtocolCore { - constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) { + public constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) { super( LightPushCodec, libp2p.components, @@ -78,7 +78,7 @@ export class LightPushCore extends BaseProtocol implements IBaseProtocolCore { } } - async send( + public async send( encoder: IEncoder, message: IMessage, peer: Peer diff --git a/packages/core/src/lib/light_push/push_rpc.ts b/packages/core/src/lib/light_push/push_rpc.ts index 7eb0d8f654..7b726e3e49 100644 --- a/packages/core/src/lib/light_push/push_rpc.ts +++ b/packages/core/src/lib/light_push/push_rpc.ts @@ -5,7 +5,7 @@ import { v4 as uuid } from "uuid"; export class PushRpc { public constructor(public proto: proto.PushRpc) {} - static createRequest( + public static createRequest( message: proto.WakuMessage, pubsubTopic: string ): PushRpc { @@ -19,20 +19,20 @@ export class PushRpc { }); } - static decode(bytes: Uint8ArrayList): PushRpc { + public static decode(bytes: Uint8ArrayList): PushRpc { const res = proto.PushRpc.decode(bytes); return new PushRpc(res); } - encode(): Uint8Array { + public encode(): Uint8Array { return proto.PushRpc.encode(this.proto); } - get query(): proto.PushRequest | undefined { + public get query(): proto.PushRequest | undefined { return this.proto.request; } - get response(): proto.PushResponse | undefined { + public get response(): proto.PushResponse | undefined { return this.proto.response; } } diff --git a/packages/core/src/lib/message/version_0.ts b/packages/core/src/lib/message/version_0.ts index d90335dc27..8e4c8162c0 100644 --- a/packages/core/src/lib/message/version_0.ts +++ b/packages/core/src/lib/message/version_0.ts @@ -20,28 +20,28 @@ export const Version = 0; export { proto }; export class DecodedMessage implements IDecodedMessage { - constructor( + public constructor( public pubsubTopic: string, protected proto: proto.WakuMessage ) {} - get ephemeral(): boolean { + public get ephemeral(): boolean { return Boolean(this.proto.ephemeral); } - get payload(): Uint8Array { + public get payload(): Uint8Array { return this.proto.payload; } - get contentTopic(): string { + public get contentTopic(): string { return this.proto.contentTopic; } - get _rawTimestamp(): bigint | undefined { + public get _rawTimestamp(): bigint | undefined { return this.proto.timestamp; } - get timestamp(): Date | undefined { + public get timestamp(): Date | undefined { // In the case we receive a value that is bigger than JS's max number, // we catch the error and return undefined. try { @@ -56,23 +56,23 @@ export class DecodedMessage implements IDecodedMessage { } } - get meta(): Uint8Array | undefined { + public get meta(): Uint8Array | undefined { return this.proto.meta; } - get version(): number { + public get version(): number { // https://rfc.vac.dev/spec/14/ // > If omitted, the value SHOULD be interpreted as version 0. return this.proto.version ?? 0; } - get rateLimitProof(): IRateLimitProof | undefined { + public get rateLimitProof(): IRateLimitProof | undefined { return this.proto.rateLimitProof; } } export class Encoder implements IEncoder { - constructor( + public constructor( public contentTopic: string, public ephemeral: boolean = false, public pubsubTopic: PubsubTopic, @@ -83,11 +83,11 @@ export class Encoder implements IEncoder { } } - async toWire(message: IMessage): Promise { + public async toWire(message: IMessage): Promise { return proto.WakuMessage.encode(await this.toProtoObj(message)); } - async toProtoObj(message: IMessage): Promise { + public async toProtoObj(message: IMessage): Promise { const timestamp = message.timestamp ?? new Date(); const protoMessage = { @@ -133,7 +133,7 @@ export function createEncoder({ } export class Decoder implements IDecoder { - constructor( + public constructor( public pubsubTopic: PubsubTopic, public contentTopic: string ) { @@ -142,7 +142,9 @@ export class Decoder implements IDecoder { } } - fromWireToProtoObj(bytes: Uint8Array): Promise { + public fromWireToProtoObj( + bytes: Uint8Array + ): Promise { const protoMessage = proto.WakuMessage.decode(bytes); return Promise.resolve({ payload: protoMessage.payload, @@ -155,7 +157,7 @@ export class Decoder implements IDecoder { }); } - async fromProtoObj( + public async fromProtoObj( pubsubTopic: string, proto: IProtoMessage ): Promise { diff --git a/packages/core/src/lib/metadata/index.ts b/packages/core/src/lib/metadata/index.ts index e879e29c38..183f5b3aa5 100644 --- a/packages/core/src/lib/metadata/index.ts +++ b/packages/core/src/lib/metadata/index.ts @@ -23,9 +23,9 @@ export const MetadataCodec = "/vac/waku/metadata/1.0.0"; class Metadata extends BaseProtocol implements IMetadata { private libp2pComponents: Libp2pComponents; - handshakesConfirmed: Map = new Map(); + protected handshakesConfirmed: Map = new Map(); - constructor( + public constructor( public shardInfo: ShardInfo, libp2p: Libp2pComponents ) { @@ -41,40 +41,10 @@ class Metadata extends BaseProtocol implements IMetadata { }); } - /** - * Handle an incoming metadata request - */ - private async onRequest(streamData: IncomingStreamData): Promise { - try { - const { stream, connection } = streamData; - const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode( - this.shardInfo - ); - - const encodedResponse = await pipe( - [encodedShardInfo], - lp.encode, - stream, - lp.decode, - async (source) => await all(source) - ); - - const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse); - - if (error) { - return; - } - - await this.savePeerShardInfo(connection.remotePeer, shardInfo); - } catch (error) { - log.error("Error handling metadata request", error); - } - } - /** * Make a metadata query to a peer */ - async query(peerId: PeerId): Promise { + public async query(peerId: PeerId): Promise { const request = proto_metadata.WakuMetadataRequest.encode(this.shardInfo); const peer = await this.peerStore.get(peerId); @@ -135,6 +105,36 @@ class Metadata extends BaseProtocol implements IMetadata { return await this.query(peerId); } + /** + * Handle an incoming metadata request + */ + private async onRequest(streamData: IncomingStreamData): Promise { + try { + const { stream, connection } = streamData; + const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode( + this.shardInfo + ); + + const encodedResponse = await pipe( + [encodedShardInfo], + lp.encode, + stream, + lp.decode, + async (source) => await all(source) + ); + + const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse); + + if (error) { + return; + } + + await this.savePeerShardInfo(connection.remotePeer, shardInfo); + } catch (error) { + log.error("Error handling metadata request", error); + } + } + private decodeMetadataResponse( encodedResponse: Uint8ArrayList[] ): MetadataQueryResult { diff --git a/packages/core/src/lib/store/history_rpc.ts b/packages/core/src/lib/store/history_rpc.ts index 2db298d90a..fb9049437f 100644 --- a/packages/core/src/lib/store/history_rpc.ts +++ b/packages/core/src/lib/store/history_rpc.ts @@ -22,18 +22,18 @@ export interface Params { export class HistoryRpc { private constructor(public readonly proto: proto.HistoryRpc) {} - get query(): proto.HistoryQuery | undefined { + public get query(): proto.HistoryQuery | undefined { return this.proto.query; } - get response(): proto.HistoryResponse | undefined { + public get response(): proto.HistoryResponse | undefined { return this.proto.response; } /** * Create History Query. */ - static createQuery(params: Params): HistoryRpc { + public static createQuery(params: Params): HistoryRpc { const contentFilters = params.contentTopics.map((contentTopic) => { return { contentTopic }; }); @@ -69,12 +69,12 @@ export class HistoryRpc { }); } - decode(bytes: Uint8ArrayList): HistoryRpc { + public decode(bytes: Uint8ArrayList): HistoryRpc { const res = proto.HistoryRpc.decode(bytes); return new HistoryRpc(res); } - encode(): Uint8Array { + public encode(): Uint8Array { return proto.HistoryRpc.encode(this.proto); } } diff --git a/packages/core/src/lib/store/index.ts b/packages/core/src/lib/store/index.ts index fbf806efe0..64ce6c1c35 100644 --- a/packages/core/src/lib/store/index.ts +++ b/packages/core/src/lib/store/index.ts @@ -68,11 +68,11 @@ export interface QueryOptions { * The Waku Store protocol can be used to retrieved historical messages. */ export class StoreCore extends BaseProtocol implements IStoreCore { - constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) { + public constructor(libp2p: Libp2p, options?: ProtocolCreateOptions) { super(StoreCodec, libp2p.components, log, options!.pubsubTopics!, options); } - async *queryPerPage( + public async *queryPerPage( queryOpts: Params, decoders: Map>, peer: Peer diff --git a/packages/core/src/lib/stream_manager/stream_manager.ts b/packages/core/src/lib/stream_manager/stream_manager.ts index b602d47e71..2896ff583f 100644 --- a/packages/core/src/lib/stream_manager/stream_manager.ts +++ b/packages/core/src/lib/stream_manager/stream_manager.ts @@ -13,7 +13,7 @@ export class StreamManager { private readonly streamPool: Map>; private readonly log: Logger; - constructor( + public constructor( public multicodec: string, public getConnections: Libp2p["getConnections"], public addEventListener: Libp2p["addEventListener"] diff --git a/packages/discovery/src/dns/dns.spec.ts b/packages/discovery/src/dns/dns.spec.ts index a818c6d40d..055ac7b4a9 100644 --- a/packages/discovery/src/dns/dns.spec.ts +++ b/packages/discovery/src/dns/dns.spec.ts @@ -32,23 +32,23 @@ const errorBranchB = `enrtree-branch:${branchDomainD}`; * Mocks DNS resolution. */ class MockDNS implements DnsClient { - fqdnRes: Map; - fqdnThrows: string[]; + private fqdnRes: Map; + private fqdnThrows: string[]; - constructor() { + public constructor() { this.fqdnRes = new Map(); this.fqdnThrows = []; } - addRes(fqdn: string, res: string[]): void { + public addRes(fqdn: string, res: string[]): void { this.fqdnRes.set(fqdn, res); } - addThrow(fqdn: string): void { + public addThrow(fqdn: string): void { this.fqdnThrows.push(fqdn); } - resolveTXT(fqdn: string): Promise { + public resolveTXT(fqdn: string): Promise { if (this.fqdnThrows.includes(fqdn)) throw "Mock DNS throws."; const res = this.fqdnRes.get(fqdn); diff --git a/packages/discovery/src/dns/dns.ts b/packages/discovery/src/dns/dns.ts index b17b25d4c5..206891ca9b 100644 --- a/packages/discovery/src/dns/dns.ts +++ b/packages/discovery/src/dns/dns.ts @@ -37,7 +37,7 @@ export class DnsNodeDiscovery { * peers encountered by randomized search exceeds the sum of the fields of * @link wantedNodeCapabilityCount plus the @link _errorTolerance factor. */ - async getPeers( + public async getPeers( enrTreeUrls: string[], wantedNodeCapabilityCount: Partial ): Promise { @@ -74,7 +74,7 @@ export class DnsNodeDiscovery { /** * {@inheritDoc getPeers} */ - async *getNextPeer( + public async *getNextPeer( enrTreeUrls: string[], wantedNodeCapabilityCount: Partial ): AsyncGenerator { diff --git a/packages/discovery/src/dns/dns_discovery.ts b/packages/discovery/src/dns/dns_discovery.ts index b58960a7d6..99534be256 100644 --- a/packages/discovery/src/dns/dns_discovery.ts +++ b/packages/discovery/src/dns/dns_discovery.ts @@ -36,7 +36,10 @@ export class PeerDiscoveryDns private _components: DnsDiscoveryComponents; private _options: DnsDiscOptions; - constructor(components: DnsDiscoveryComponents, options: DnsDiscOptions) { + public constructor( + components: DnsDiscoveryComponents, + options: DnsDiscOptions + ) { super(); this._started = false; this._components = components; @@ -49,7 +52,7 @@ export class PeerDiscoveryDns /** * Start discovery process */ - async start(): Promise { + public async start(): Promise { log.info("Starting peer discovery via dns"); this._started = true; @@ -122,15 +125,15 @@ export class PeerDiscoveryDns /** * Stop emitting events */ - stop(): void { + public stop(): void { this._started = false; } - get [symbol](): true { + public get [symbol](): true { return true; } - get [Symbol.toStringTag](): string { + public get [Symbol.toStringTag](): string { return "@waku/bootstrap"; } } diff --git a/packages/discovery/src/dns/dns_over_https.ts b/packages/discovery/src/dns/dns_over_https.ts index d1558a6bf0..8c1f45799c 100644 --- a/packages/discovery/src/dns/dns_over_https.ts +++ b/packages/discovery/src/dns/dns_over_https.ts @@ -36,7 +36,7 @@ export class DnsOverHttps implements DnsClient { * * @throws if the query fails */ - async resolveTXT(domain: string): Promise { + public async resolveTXT(domain: string): Promise { let answers; try { const res = await query( diff --git a/packages/discovery/src/dns/enrtree.ts b/packages/discovery/src/dns/enrtree.ts index 7a1412c29b..d47f5c3ab2 100644 --- a/packages/discovery/src/dns/enrtree.ts +++ b/packages/discovery/src/dns/enrtree.ts @@ -26,7 +26,7 @@ export class ENRTree { * Extracts the branch subdomain referenced by a DNS tree root string after verifying * the root record signature with its base32 compressed public key. */ - static parseAndVerifyRoot(root: string, publicKey: string): string { + public static parseAndVerifyRoot(root: string, publicKey: string): string { if (!root.startsWith(this.ROOT_PREFIX)) throw new Error( `ENRTree root entry must start with '${this.ROOT_PREFIX}'` @@ -57,7 +57,7 @@ export class ENRTree { return rootValues.eRoot; } - static parseRootValues(txt: string): ENRRootValues { + public static parseRootValues(txt: string): ENRRootValues { const matches = txt.match( /^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/ ); @@ -86,7 +86,7 @@ export class ENRTree { * The domain is the starting point for traversing a set of linked DNS TXT records * and the public key is used to verify the root entry record */ - static parseTree(tree: string): ENRTreeValues { + public static parseTree(tree: string): ENRTreeValues { if (!tree.startsWith(this.TREE_PREFIX)) throw new Error( `ENRTree tree entry must start with '${this.TREE_PREFIX}'` @@ -112,7 +112,7 @@ export class ENRTree { * Returns subdomains listed in an ENR branch entry. These in turn lead to * either further branch entries or ENR records. */ - static parseBranch(branch: string): string[] { + public static parseBranch(branch: string): string[] { if (!branch.startsWith(this.BRANCH_PREFIX)) throw new Error( `ENRTree branch entry must start with '${this.BRANCH_PREFIX}'` diff --git a/packages/discovery/src/local-peer-cache/index.ts b/packages/discovery/src/local-peer-cache/index.ts index 14a79013e7..7b8a846915 100644 --- a/packages/discovery/src/local-peer-cache/index.ts +++ b/packages/discovery/src/local-peer-cache/index.ts @@ -35,7 +35,7 @@ export class LocalPeerCacheDiscovery private isStarted: boolean; private peers: LocalStoragePeerInfo[] = []; - constructor( + public constructor( private readonly components: Libp2pComponents, private readonly options?: LocalPeerCacheDiscoveryOptions ) { @@ -44,11 +44,11 @@ export class LocalPeerCacheDiscovery this.peers = this.getPeersFromLocalStorage(); } - get [Symbol.toStringTag](): string { + public get [Symbol.toStringTag](): string { return "@waku/local-peer-cache-discovery"; } - async start(): Promise { + public async start(): Promise { if (this.isStarted) return; log.info("Starting Local Storage Discovery"); @@ -86,7 +86,7 @@ export class LocalPeerCacheDiscovery this.isStarted = true; } - stop(): void | Promise { + public stop(): void | Promise { if (!this.isStarted) return; log.info("Stopping Local Storage Discovery"); this.components.events.removeEventListener( @@ -98,7 +98,7 @@ export class LocalPeerCacheDiscovery this.savePeersToLocalStorage(); } - handleNewPeers = (event: CustomEvent): void => { + public handleNewPeers = (event: CustomEvent): void => { const { peerId, listenAddrs } = event.detail; const websocketMultiaddr = getWsMultiaddrFromMultiaddrs(listenAddrs); diff --git a/packages/discovery/src/peer-exchange/rpc.ts b/packages/discovery/src/peer-exchange/rpc.ts index 2444ccc1cc..49479e3436 100644 --- a/packages/discovery/src/peer-exchange/rpc.ts +++ b/packages/discovery/src/peer-exchange/rpc.ts @@ -7,7 +7,9 @@ import type { Uint8ArrayList } from "uint8arraylist"; export class PeerExchangeRPC { public constructor(public proto: proto.PeerExchangeRPC) {} - static createRequest(params: proto.PeerExchangeQuery): PeerExchangeRPC { + public static createRequest( + params: proto.PeerExchangeQuery + ): PeerExchangeRPC { const { numPeers } = params; return new PeerExchangeRPC({ query: { @@ -21,7 +23,7 @@ export class PeerExchangeRPC { * Encode the current PeerExchangeRPC request to bytes * @returns Uint8Array */ - encode(): Uint8Array { + public encode(): Uint8Array { return proto.PeerExchangeRPC.encode(this.proto); } @@ -29,16 +31,16 @@ export class PeerExchangeRPC { * Decode the current PeerExchangeRPC request to bytes * @returns Uint8Array */ - static decode(bytes: Uint8ArrayList): PeerExchangeRPC { + public static decode(bytes: Uint8ArrayList): PeerExchangeRPC { const res = proto.PeerExchangeRPC.decode(bytes); return new PeerExchangeRPC(res); } - get query(): proto.PeerExchangeQuery | undefined { + public get query(): proto.PeerExchangeQuery | undefined { return this.proto.query; } - get response(): proto.PeerExchangeResponse | undefined { + public get response(): proto.PeerExchangeResponse | undefined { return this.proto.response; } } diff --git a/packages/discovery/src/peer-exchange/waku_peer_exchange.ts b/packages/discovery/src/peer-exchange/waku_peer_exchange.ts index ee4d02cfd7..0aed7b141e 100644 --- a/packages/discovery/src/peer-exchange/waku_peer_exchange.ts +++ b/packages/discovery/src/peer-exchange/waku_peer_exchange.ts @@ -28,14 +28,17 @@ export class WakuPeerExchange extends BaseProtocol implements IPeerExchange { /** * @param components - libp2p components */ - constructor(components: Libp2pComponents, pubsubTopics: PubsubTopic[]) { + public constructor( + components: Libp2pComponents, + pubsubTopics: PubsubTopic[] + ) { super(PeerExchangeCodec, components, log, pubsubTopics); } /** * Make a peer exchange query to a peer */ - async query( + public async query( params: PeerExchangeQueryParams ): Promise { const { numPeers } = params; diff --git a/packages/discovery/src/peer-exchange/waku_peer_exchange_discovery.ts b/packages/discovery/src/peer-exchange/waku_peer_exchange_discovery.ts index 5b52340d05..17bcd50168 100644 --- a/packages/discovery/src/peer-exchange/waku_peer_exchange_discovery.ts +++ b/packages/discovery/src/peer-exchange/waku_peer_exchange_discovery.ts @@ -82,7 +82,7 @@ export class PeerExchangeDiscovery ); }; - constructor( + public constructor( components: Libp2pComponents, pubsubTopics: PubsubTopic[], options: Options = {} @@ -97,7 +97,7 @@ export class PeerExchangeDiscovery /** * Start emitting events */ - start(): void { + public start(): void { if (this.isStarted) { return; } @@ -114,7 +114,7 @@ export class PeerExchangeDiscovery /** * Remove event listener */ - stop(): void { + public stop(): void { if (!this.isStarted) return; log.info("Stopping peer exchange node discovery"); this.isStarted = false; @@ -125,11 +125,11 @@ export class PeerExchangeDiscovery ); } - get [symbol](): true { + public get [symbol](): true { return true; } - get [Symbol.toStringTag](): string { + public get [Symbol.toStringTag](): string { return "@waku/peer-exchange"; } diff --git a/packages/enr/src/creator.ts b/packages/enr/src/creator.ts index 804158294e..44d947b812 100644 --- a/packages/enr/src/creator.ts +++ b/packages/enr/src/creator.ts @@ -7,7 +7,7 @@ import { ENR } from "./enr.js"; import { getPublicKeyFromPeerId } from "./peer_id.js"; export class EnrCreator { - static fromPublicKey( + public static fromPublicKey( publicKey: Uint8Array, kvs: Record = {} ): Promise { @@ -22,7 +22,7 @@ export class EnrCreator { }); } - static async fromPeerId( + public static async fromPeerId( peerId: PeerId, kvs: Record = {} ): Promise { diff --git a/packages/enr/src/decoder.ts b/packages/enr/src/decoder.ts index e01cd5f189..0fdcca9578 100644 --- a/packages/enr/src/decoder.ts +++ b/packages/enr/src/decoder.ts @@ -9,7 +9,7 @@ import { ENR } from "./enr.js"; const log = new Logger("enr:decoder"); export class EnrDecoder { - static fromString(encoded: string): Promise { + public static fromString(encoded: string): Promise { if (!encoded.startsWith(ENR.RECORD_PREFIX)) { throw new Error( `"string encoded ENR must start with '${ENR.RECORD_PREFIX}'` @@ -18,7 +18,7 @@ export class EnrDecoder { return EnrDecoder.fromRLP(fromString(encoded.slice(4), "base64url")); } - static fromRLP(encoded: Uint8Array): Promise { + public static fromRLP(encoded: Uint8Array): Promise { const decoded = RLP.decode(encoded).map(hexToBytes); return fromValues(decoded); } diff --git a/packages/enr/src/encoder.ts b/packages/enr/src/encoder.ts index 00a1e98553..4eecb55067 100644 --- a/packages/enr/src/encoder.ts +++ b/packages/enr/src/encoder.ts @@ -7,7 +7,7 @@ import { ERR_NO_SIGNATURE, MAX_RECORD_SIZE } from "./constants.js"; import { ENR } from "./enr.js"; export class EnrEncoder { - static async toValues( + public static async toValues( enr: ENR, privateKey?: Uint8Array ): Promise<(ENRKey | ENRValue | number[])[]> { @@ -31,7 +31,10 @@ export class EnrEncoder { return content; } - static async toBytes(enr: ENR, privateKey?: Uint8Array): Promise { + public static async toBytes( + enr: ENR, + privateKey?: Uint8Array + ): Promise { const encoded = hexToBytes( RLP.encode(await EnrEncoder.toValues(enr, privateKey)) ); @@ -41,7 +44,10 @@ export class EnrEncoder { return encoded; } - static async toString(enr: ENR, privateKey?: Uint8Array): Promise { + public static async toString( + enr: ENR, + privateKey?: Uint8Array + ): Promise { return ( ENR.RECORD_PREFIX + toString(await EnrEncoder.toBytes(enr, privateKey), "base64url") diff --git a/packages/enr/src/enr.ts b/packages/enr/src/enr.ts index edc02f8a08..2425cb5790 100644 --- a/packages/enr/src/enr.ts +++ b/packages/enr/src/enr.ts @@ -34,7 +34,7 @@ export class ENR extends RawEnr implements IEnr { public static readonly RECORD_PREFIX = "enr:"; public peerId?: PeerId; - static async create( + public static async create( kvs: Record = {}, seq: SequenceNumber = BigInt(1), signature?: Uint8Array @@ -52,7 +52,7 @@ export class ENR extends RawEnr implements IEnr { return enr; } - get nodeId(): NodeId | undefined { + public get nodeId(): NodeId | undefined { switch (this.id) { case "v4": return this.publicKey ? v4.nodeId(this.publicKey) : undefined; @@ -60,18 +60,18 @@ export class ENR extends RawEnr implements IEnr { throw new Error(ERR_INVALID_ID); } } - getLocationMultiaddr: ( + public getLocationMultiaddr: ( protocol: TransportProtocol | TransportProtocolPerIpVersion ) => Multiaddr | undefined = locationMultiaddrFromEnrFields.bind({}, this); - get shardInfo(): ShardInfo | undefined { + public get shardInfo(): ShardInfo | undefined { if (this.rs && this.rsv) { log.warn("ENR contains both `rs` and `rsv` fields."); } return this.rs || this.rsv; } - setLocationMultiaddr(multiaddr: Multiaddr): void { + public setLocationMultiaddr(multiaddr: Multiaddr): void { const protoNames = multiaddr.protoNames(); if ( protoNames.length !== 2 && @@ -95,7 +95,7 @@ export class ENR extends RawEnr implements IEnr { } } - getAllLocationMultiaddrs(): Multiaddr[] { + public getAllLocationMultiaddrs(): Multiaddr[] { const multiaddrs = []; for (const protocol of Object.values(TransportProtocolPerIpVersion)) { @@ -115,7 +115,7 @@ export class ENR extends RawEnr implements IEnr { }); } - get peerInfo(): PeerInfo | undefined { + public get peerInfo(): PeerInfo | undefined { const id = this.peerId; if (!id) return; return { @@ -132,7 +132,7 @@ export class ENR extends RawEnr implements IEnr { * * @param protocol */ - getFullMultiaddr( + public getFullMultiaddr( protocol: TransportProtocol | TransportProtocolPerIpVersion ): Multiaddr | undefined { if (this.peerId) { @@ -147,7 +147,7 @@ export class ENR extends RawEnr implements IEnr { /** * Returns the full multiaddrs from the `multiaddrs` ENR field. */ - getFullMultiaddrs(): Multiaddr[] { + public getFullMultiaddrs(): Multiaddr[] { if (this.peerId && this.multiaddrs) { const peerId = this.peerId; return this.multiaddrs.map((ma) => { @@ -157,7 +157,7 @@ export class ENR extends RawEnr implements IEnr { return []; } - verify(data: Uint8Array, signature: Uint8Array): boolean { + public verify(data: Uint8Array, signature: Uint8Array): boolean { if (!this.get("id") || this.id !== "v4") { throw new Error(ERR_INVALID_ID); } @@ -167,7 +167,10 @@ export class ENR extends RawEnr implements IEnr { return verifySignature(signature, keccak256(data), this.publicKey); } - async sign(data: Uint8Array, privateKey: Uint8Array): Promise { + public async sign( + data: Uint8Array, + privateKey: Uint8Array + ): Promise { switch (this.id) { case "v4": this.signature = await v4.sign(privateKey, data); diff --git a/packages/enr/src/raw_enr.ts b/packages/enr/src/raw_enr.ts index b7c607880e..0629932f78 100644 --- a/packages/enr/src/raw_enr.ts +++ b/packages/enr/src/raw_enr.ts @@ -31,19 +31,19 @@ export class RawEnr extends Map { this.signature = signature; } - set(k: ENRKey, v: ENRValue): this { + public set(k: ENRKey, v: ENRValue): this { this.signature = undefined; this.seq++; return super.set(k, v); } - get id(): string { + public get id(): string { const id = this.get("id"); if (!id) throw new Error("id not found."); return bytesToUtf8(id); } - get publicKey(): Uint8Array | undefined { + public get publicKey(): Uint8Array | undefined { switch (this.id) { case "v4": return this.get("secp256k1"); @@ -52,63 +52,63 @@ export class RawEnr extends Map { } } - get rs(): ShardInfo | undefined { + public get rs(): ShardInfo | undefined { const rs = this.get("rs"); if (!rs) return undefined; return decodeRelayShard(rs); } - get rsv(): ShardInfo | undefined { + public get rsv(): ShardInfo | undefined { const rsv = this.get("rsv"); if (!rsv) return undefined; return decodeRelayShard(rsv); } - get ip(): string | undefined { + public get ip(): string | undefined { return getStringValue(this, "ip", "ip4"); } - set ip(ip: string | undefined) { + public set ip(ip: string | undefined) { setStringValue(this, "ip", "ip4", ip); } - get tcp(): number | undefined { + public get tcp(): number | undefined { return getNumberAsStringValue(this, "tcp", "tcp"); } - set tcp(port: number | undefined) { + public set tcp(port: number | undefined) { setNumberAsStringValue(this, "tcp", "tcp", port); } - get udp(): number | undefined { + public get udp(): number | undefined { return getNumberAsStringValue(this, "udp", "udp"); } - set udp(port: number | undefined) { + public set udp(port: number | undefined) { setNumberAsStringValue(this, "udp", "udp", port); } - get ip6(): string | undefined { + public get ip6(): string | undefined { return getStringValue(this, "ip6", "ip6"); } - set ip6(ip: string | undefined) { + public set ip6(ip: string | undefined) { setStringValue(this, "ip6", "ip6", ip); } - get tcp6(): number | undefined { + public get tcp6(): number | undefined { return getNumberAsStringValue(this, "tcp6", "tcp"); } - set tcp6(port: number | undefined) { + public set tcp6(port: number | undefined) { setNumberAsStringValue(this, "tcp6", "tcp", port); } - get udp6(): number | undefined { + public get udp6(): number | undefined { return getNumberAsStringValue(this, "udp6", "udp"); } - set udp6(port: number | undefined) { + public set udp6(port: number | undefined) { setNumberAsStringValue(this, "udp6", "udp", port); } @@ -124,7 +124,7 @@ export class RawEnr extends Map { * * The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less. */ - get multiaddrs(): Multiaddr[] | undefined { + public get multiaddrs(): Multiaddr[] | undefined { const raw = this.get("multiaddrs"); if (raw) return decodeMultiaddrs(raw); @@ -144,14 +144,14 @@ export class RawEnr extends Map { * The multiaddresses stored in this field must be location multiaddresses, * ie, without a peer id. */ - set multiaddrs(multiaddrs: Multiaddr[] | undefined) { + public set multiaddrs(multiaddrs: Multiaddr[] | undefined) { deleteUndefined(this, "multiaddrs", multiaddrs, encodeMultiaddrs); } /** * Get the `waku2` field from ENR. */ - get waku2(): Waku2 | undefined { + public get waku2(): Waku2 | undefined { const raw = this.get("waku2"); if (raw) return decodeWaku2(raw[0]); @@ -161,7 +161,7 @@ export class RawEnr extends Map { /** * Set the `waku2` field on the ENR. */ - set waku2(waku2: Waku2 | undefined) { + public set waku2(waku2: Waku2 | undefined) { deleteUndefined( this, "waku2", diff --git a/packages/message-encryption/src/decoded_message.ts b/packages/message-encryption/src/decoded_message.ts index 80418330c7..6aeec7e295 100644 --- a/packages/message-encryption/src/decoded_message.ts +++ b/packages/message-encryption/src/decoded_message.ts @@ -11,7 +11,7 @@ export class DecodedMessage { private readonly _decodedPayload: Uint8Array; - constructor( + public constructor( pubsubTopic: string, proto: proto.WakuMessage, decodedPayload: Uint8Array, @@ -22,7 +22,7 @@ export class DecodedMessage this._decodedPayload = decodedPayload; } - get payload(): Uint8Array { + public get payload(): Uint8Array { return this._decodedPayload; } @@ -31,7 +31,7 @@ export class DecodedMessage * * @returns true if the signature matches the public key, false if not or if no signature is present. */ - verifySignature(publicKey: Uint8Array): boolean { + public verifySignature(publicKey: Uint8Array): boolean { if (this.signaturePublicKey) { return equals(this.signaturePublicKey, publicKey); } diff --git a/packages/message-encryption/src/ecies.ts b/packages/message-encryption/src/ecies.ts index b084c6a9bc..9364a3da8f 100644 --- a/packages/message-encryption/src/ecies.ts +++ b/packages/message-encryption/src/ecies.ts @@ -33,7 +33,7 @@ export { const log = new Logger("message-encryption:ecies"); class Encoder implements IEncoder { - constructor( + public constructor( public pubsubTopic: PubsubTopic, public contentTopic: string, private publicKey: Uint8Array, @@ -46,14 +46,16 @@ class Encoder implements IEncoder { } } - async toWire(message: IMessage): Promise { + public async toWire(message: IMessage): Promise { const protoMessage = await this.toProtoObj(message); if (!protoMessage) return; return WakuMessage.encode(protoMessage); } - async toProtoObj(message: IMessage): Promise { + public async toProtoObj( + message: IMessage + ): Promise { const timestamp = message.timestamp ?? new Date(); const preparedPayload = await preCipher(message.payload, this.sigPrivKey); @@ -121,7 +123,7 @@ export function createEncoder({ } class Decoder extends DecoderV0 implements IDecoder { - constructor( + public constructor( pubsubTopic: PubsubTopic, contentTopic: string, private privateKey: Uint8Array @@ -129,7 +131,7 @@ class Decoder extends DecoderV0 implements IDecoder { super(pubsubTopic, contentTopic); } - async fromProtoObj( + public async fromProtoObj( pubsubTopic: string, protoMessage: IProtoMessage ): Promise { diff --git a/packages/message-encryption/src/symmetric.ts b/packages/message-encryption/src/symmetric.ts index 60011b8e36..fa1b88ffed 100644 --- a/packages/message-encryption/src/symmetric.ts +++ b/packages/message-encryption/src/symmetric.ts @@ -34,7 +34,7 @@ export { const log = new Logger("message-encryption:symmetric"); class Encoder implements IEncoder { - constructor( + public constructor( public pubsubTopic: PubsubTopic, public contentTopic: string, private symKey: Uint8Array, @@ -47,14 +47,16 @@ class Encoder implements IEncoder { } } - async toWire(message: IMessage): Promise { + public async toWire(message: IMessage): Promise { const protoMessage = await this.toProtoObj(message); if (!protoMessage) return; return WakuMessage.encode(protoMessage); } - async toProtoObj(message: IMessage): Promise { + public async toProtoObj( + message: IMessage + ): Promise { const timestamp = message.timestamp ?? new Date(); const preparedPayload = await preCipher(message.payload, this.sigPrivKey); @@ -118,7 +120,7 @@ export function createEncoder({ } class Decoder extends DecoderV0 implements IDecoder { - constructor( + public constructor( pubsubTopic: PubsubTopic, contentTopic: string, private symKey: Uint8Array @@ -126,7 +128,7 @@ class Decoder extends DecoderV0 implements IDecoder { super(pubsubTopic, contentTopic); } - async fromProtoObj( + public async fromProtoObj( pubsubTopic: string, protoMessage: IProtoMessage ): Promise { diff --git a/packages/relay/src/index.ts b/packages/relay/src/index.ts index c1f0addc10..831ef4c3c5 100644 --- a/packages/relay/src/index.ts +++ b/packages/relay/src/index.ts @@ -59,7 +59,7 @@ class Relay implements IRelay { */ private observers: Map>>; - constructor(libp2p: Libp2p, pubsubTopics: PubsubTopic[]) { + public constructor(libp2p: Libp2p, pubsubTopics: PubsubTopic[]) { if (!this.isRelayPubsub(libp2p.services.pubsub)) { throw Error( `Failed to initialize Relay. libp2p.pubsub does not support ${Relay.multicodec}` diff --git a/packages/relay/src/topic_only_message.ts b/packages/relay/src/topic_only_message.ts index 2335ee7320..9a06cc382f 100644 --- a/packages/relay/src/topic_only_message.ts +++ b/packages/relay/src/topic_only_message.ts @@ -13,21 +13,23 @@ export class TopicOnlyMessage implements IDecodedMessage { public meta: undefined; public ephemeral: undefined; - constructor( + public constructor( public pubsubTopic: string, private proto: ProtoTopicOnlyMessage ) {} - get contentTopic(): string { + public get contentTopic(): string { return this.proto.contentTopic; } } export class TopicOnlyDecoder implements IDecoder { - pubsubTopic = DefaultPubsubTopic; + public pubsubTopic = DefaultPubsubTopic; public contentTopic = ""; - fromWireToProtoObj(bytes: Uint8Array): Promise { + public fromWireToProtoObj( + bytes: Uint8Array + ): Promise { const protoMessage = ProtoTopicOnlyMessage.decode(bytes); return Promise.resolve({ contentTopic: protoMessage.contentTopic, @@ -40,7 +42,7 @@ export class TopicOnlyDecoder implements IDecoder { }); } - async fromProtoObj( + public async fromProtoObj( pubsubTopic: string, proto: IProtoMessage ): Promise { diff --git a/packages/sdk/src/protocols/base_protocol.ts b/packages/sdk/src/protocols/base_protocol.ts index 854c0fabce..98b72327d0 100644 --- a/packages/sdk/src/protocols/base_protocol.ts +++ b/packages/sdk/src/protocols/base_protocol.ts @@ -19,14 +19,14 @@ export class BaseProtocolSDK implements IBaseProtocolSDK { private maintainPeersIntervalId: ReturnType< typeof window.setInterval > | null = null; - log: Logger; + private log: Logger; private maintainPeersLock = false; private readonly renewPeersLocker = new RenewPeerLocker( RENEW_TIME_LOCK_DURATION ); - constructor( + public constructor( protected core: BaseProtocol, private connectionManager: ConnectionManager, options: Options @@ -39,7 +39,7 @@ export class BaseProtocolSDK implements IBaseProtocolSDK { void this.startMaintainPeersInterval(maintainPeersInterval); } - get connectedPeers(): Peer[] { + public get connectedPeers(): Peer[] { return this.peers; } @@ -237,7 +237,7 @@ export class BaseProtocolSDK implements IBaseProtocolSDK { class RenewPeerLocker { private readonly peers: Map = new Map(); - constructor(private lockDuration: number) {} + public constructor(private lockDuration: number) {} public lock(id: PeerId): void { this.peers.set(id.toString(), Date.now()); diff --git a/packages/sdk/src/protocols/filter.ts b/packages/sdk/src/protocols/filter.ts index af69f1d218..c40661a728 100644 --- a/packages/sdk/src/protocols/filter.ts +++ b/packages/sdk/src/protocols/filter.ts @@ -57,8 +57,7 @@ const DEFAULT_SUBSCRIBE_OPTIONS = { keepAlive: DEFAULT_KEEP_ALIVE }; export class SubscriptionManager implements ISubscriptionSDK { - private readonly pubsubTopic: PubsubTopic; - readonly receivedMessagesHashStr: string[] = []; + private readonly receivedMessagesHashStr: string[] = []; private keepAliveTimer: number | null = null; private readonly receivedMessagesHashes: ReceivedMessageHashes; private peerFailures: Map = new Map(); @@ -71,8 +70,8 @@ export class SubscriptionManager implements ISubscriptionSDK { SubscriptionCallback >; - constructor( - pubsubTopic: PubsubTopic, + public constructor( + private readonly pubsubTopic: PubsubTopic, private protocol: FilterCore, private getPeers: () => Peer[], private readonly renewPeer: (peerToDisconnect: PeerId) => Promise @@ -89,7 +88,7 @@ export class SubscriptionManager implements ISubscriptionSDK { allPeerIdStr.forEach((peerId) => this.missedMessagesByPeer.set(peerId, 0)); } - get messageHashes(): string[] { + public get messageHashes(): string[] { return [...this.receivedMessagesHashes.all]; } @@ -249,9 +248,9 @@ export class SubscriptionManager implements ISubscriptionSDK { } } - async processIncomingMessage( + public async processIncomingMessage( message: WakuMessage, - peerIdStr: string + peerIdStr: PeerIdStr ): Promise { const hashedMessageStr = messageHashStr( this.pubsubTopic, @@ -419,7 +418,7 @@ class FilterSDK extends BaseProtocolSDK implements IFilterSDK { private activeSubscriptions = new Map(); - constructor( + public constructor( connectionManager: ConnectionManager, libp2p: Libp2p, options?: ProtocolCreateOptions @@ -470,7 +469,7 @@ class FilterSDK extends BaseProtocolSDK implements IFilterSDK { * @param pubsubTopicShardInfo The pubsub topic to subscribe to. * @returns The subscription object. */ - async createSubscription( + public async createSubscription( pubsubTopicShardInfo: ShardingParams | PubsubTopic, options?: ProtocolUseOptions ): Promise { @@ -533,7 +532,7 @@ class FilterSDK extends BaseProtocolSDK implements IFilterSDK { * This method should not be used directly. * Instead, use `createSubscription` to create a new subscription. */ - async subscribe( + public async subscribe( decoders: IDecoder | IDecoder[], callback: Callback, options: SubscribeOptions = DEFAULT_SUBSCRIBE_OPTIONS diff --git a/packages/sdk/src/protocols/light_push.ts b/packages/sdk/src/protocols/light_push.ts index da1dd62af6..a2794b4371 100644 --- a/packages/sdk/src/protocols/light_push.ts +++ b/packages/sdk/src/protocols/light_push.ts @@ -20,7 +20,7 @@ const log = new Logger("sdk:light-push"); class LightPushSDK extends BaseProtocolSDK implements ILightPushSDK { public readonly protocol: LightPushCore; - constructor( + public constructor( connectionManager: ConnectionManager, libp2p: Libp2p, options?: ProtocolCreateOptions @@ -32,7 +32,7 @@ class LightPushSDK extends BaseProtocolSDK implements ILightPushSDK { this.protocol = this.core as LightPushCore; } - async send( + public async send( encoder: IEncoder, message: IMessage, _options?: ProtocolUseOptions diff --git a/packages/sdk/src/protocols/store.ts b/packages/sdk/src/protocols/store.ts index 647667a949..6d6deb75e4 100644 --- a/packages/sdk/src/protocols/store.ts +++ b/packages/sdk/src/protocols/store.ts @@ -25,7 +25,7 @@ const log = new Logger("waku:store:protocol"); export class StoreSDK extends BaseProtocolSDK implements IStoreSDK { public readonly protocol: StoreCore; - constructor( + public constructor( connectionManager: ConnectionManager, libp2p: Libp2p, options?: ProtocolCreateOptions @@ -58,7 +58,7 @@ export class StoreSDK extends BaseProtocolSDK implements IStoreSDK { * @throws If no decoders are provided. * @throws If no decoders are found for the provided pubsub topic. */ - async *queryGenerator( + public async *queryGenerator( decoders: IDecoder[], options?: waku_store.QueryOptions ): AsyncGenerator[]> { @@ -108,7 +108,7 @@ export class StoreSDK extends BaseProtocolSDK implements IStoreSDK { * or if an error is encountered when processing the reply, * or if two decoders with the same content topic are passed. */ - async queryWithOrderedCallback( + public async queryWithOrderedCallback( decoders: IDecoder[], callback: (message: T) => Promise | boolean | void, options?: waku_store.QueryOptions @@ -135,7 +135,7 @@ export class StoreSDK extends BaseProtocolSDK implements IStoreSDK { * or if an error is encountered when processing the reply, * or if two decoders with the same content topic are passed. */ - async queryWithPromiseCallback( + public async queryWithPromiseCallback( decoders: IDecoder[], callback: ( message: Promise @@ -154,7 +154,7 @@ export class StoreSDK extends BaseProtocolSDK implements IStoreSDK { } } - createCursor(message: IDecodedMessage): Cursor { + public createCursor(message: IDecodedMessage): Cursor { if ( !message || !message.timestamp || diff --git a/packages/sdk/src/waku.ts b/packages/sdk/src/waku.ts index 6044ea7794..c36735224f 100644 --- a/packages/sdk/src/waku.ts +++ b/packages/sdk/src/waku.ts @@ -73,7 +73,7 @@ export class WakuNode implements Waku { public connectionManager: ConnectionManager; public readonly pubsubTopics: PubsubTopic[]; - constructor( + public constructor( options: WakuOptions, libp2p: Libp2p, protocolsEnabled: ProtocolsEnabled @@ -143,7 +143,7 @@ export class WakuNode implements Waku { * @param peer The peer to dial * @param protocols Waku protocols we expect from the peer; Defaults to mounted protocols */ - async dial( + public async dial( peer: PeerId | MultiaddrInput, protocols?: Protocols[] ): Promise { @@ -202,16 +202,16 @@ export class WakuNode implements Waku { return this.libp2p.dialProtocol(peerId, codecs); } - async start(): Promise { + public async start(): Promise { await this.libp2p.start(); } - async stop(): Promise { + public async stop(): Promise { this.connectionManager.stop(); await this.libp2p.stop(); } - async subscribeToContentTopic( + public async subscribeToContentTopic( contentTopic: string, peer: Multiaddr, callback: Callback @@ -224,11 +224,11 @@ export class WakuNode implements Waku { ).subscription; } - isStarted(): boolean { + public isStarted(): boolean { return this.libp2p.status == "started"; } - isConnected(): boolean { + public isConnected(): boolean { return this.connectionManager.isConnected(); } @@ -237,7 +237,7 @@ export class WakuNode implements Waku { * * @throws if libp2p is not listening on localhost. */ - getLocalMultiaddrWithID(): string { + public getLocalMultiaddrWithID(): string { const localMultiaddr = this.libp2p .getMultiaddrs() .find((addr) => addr.toString().match(/127\.0\.0\.1/)); diff --git a/packages/tests/src/lib/dockerode.ts b/packages/tests/src/lib/dockerode.ts index fb28652fd5..45d69b7e29 100644 --- a/packages/tests/src/lib/dockerode.ts +++ b/packages/tests/src/lib/dockerode.ts @@ -79,14 +79,14 @@ export default class Dockerode { return newIp; } - get container(): Docker.Container | undefined { + public get container(): Docker.Container | undefined { if (!this.containerId) { return undefined; } return this.docker.getContainer(this.containerId); } - async startContainer( + public async startContainer( ports: Ports, args: Args, logPath: string, @@ -168,7 +168,7 @@ export default class Dockerode { return container; } - async stop(): Promise { + public async stop(): Promise { if (!this.container) { log.error("ContainerId not set"); } else { diff --git a/packages/tests/src/lib/index.ts b/packages/tests/src/lib/index.ts index 924febf82a..806f38133d 100644 --- a/packages/tests/src/lib/index.ts +++ b/packages/tests/src/lib/index.ts @@ -24,7 +24,7 @@ const log = new Logger("test:message-collector"); * that allows for the creation & handling of multiple ServiceNodes */ export class ServiceNodesFleet { - static async createAndRun( + public static async createAndRun( mochaContext: Mocha.Context, pubsubTopics: PubsubTopic[], nodesToCreate: number = 3, @@ -61,7 +61,7 @@ export class ServiceNodesFleet { * Convert a [[WakuMessage]] to a [[WakuRelayMessage]]. The latter is used * by the nwaku JSON-RPC API. */ - static toMessageRpcQuery(message: { + public static toMessageRpcQuery(message: { payload: Uint8Array; contentTopic: string; timestamp?: Date; @@ -86,7 +86,7 @@ export class ServiceNodesFleet { ); } - get type(): "go-waku" | "nwaku" { + public get type(): "go-waku" | "nwaku" { const nodeType = new Set( this.nodes.map((node) => { return node.type; @@ -98,12 +98,12 @@ export class ServiceNodesFleet { return nodeType.values().next().value; } - async start(): Promise { + public async start(): Promise { const startPromises = this.nodes.map((node) => node.start()); await Promise.all(startPromises); } - async sendRelayMessage( + public async sendRelayMessage( message: MessageRpcQuery, pubsubTopic: string = DefaultPubsubTopic ): Promise { @@ -114,7 +114,7 @@ export class ServiceNodesFleet { return relayMessages.every((message) => message); } - async confirmMessageLength(numMessages: number): Promise { + public async confirmMessageLength(numMessages: number): Promise { if (this.strictChecking) { await Promise.all( this.nodes.map(async (node) => @@ -138,9 +138,9 @@ export class ServiceNodesFleet { } class MultipleNodesMessageCollector { - callback: (msg: DecodedMessage) => void = () => {}; - messageList: Array = []; - constructor( + public callback: (msg: DecodedMessage) => void = () => {}; + protected messageList: Array = []; + public constructor( private messageCollectors: MessageCollector[], private relayNodes?: ServiceNode[], private strictChecking: boolean = false @@ -151,7 +151,7 @@ class MultipleNodesMessageCollector { }; } - get count(): number { + public get count(): number { return this.messageList.length; } @@ -167,7 +167,7 @@ class MultipleNodesMessageCollector { } } - getMessage(index: number): MessageRpcResponse | DecodedMessage { + public getMessage(index: number): MessageRpcResponse | DecodedMessage { return this.messageList[index]; } @@ -175,7 +175,7 @@ class MultipleNodesMessageCollector { * Verifies a received message against expected values on all nodes. * Returns true if any node's collector verifies the message successfully. */ - verifyReceivedMessage( + public verifyReceivedMessage( index: number, options: { expectedMessageText: string | Uint8Array | undefined; @@ -212,7 +212,7 @@ class MultipleNodesMessageCollector { /** * Waits for a total number of messages across all nodes. */ - async waitForMessages( + public async waitForMessages( numMessages: number, options?: { pubsubTopic?: string; diff --git a/packages/tests/src/lib/message_collector.ts b/packages/tests/src/lib/message_collector.ts index 154c0b7284..b801c3676b 100644 --- a/packages/tests/src/lib/message_collector.ts +++ b/packages/tests/src/lib/message_collector.ts @@ -19,10 +19,10 @@ const log = new Logger("test:message-collector"); * and offers a way to wait for incoming messages. */ export class MessageCollector { - list: Array = []; - callback: (msg: DecodedMessage) => void = () => {}; + public list: Array = []; + public callback: (msg: DecodedMessage) => void = () => {}; - constructor(private nwaku?: ServiceNode) { + public constructor(private nwaku?: ServiceNode) { if (!this.nwaku) { this.callback = (msg: DecodedMessage): void => { log.info("Got a message"); @@ -31,15 +31,15 @@ export class MessageCollector { } } - get count(): number { + public get count(): number { return this.list.length; } - getMessage(index: number): MessageRpcResponse | DecodedMessage { + public getMessage(index: number): MessageRpcResponse | DecodedMessage { return this.list[index]; } - hasMessage(topic: string, text: string): boolean { + public hasMessage(topic: string, text: string): boolean { return this.list.some((message) => { if (message.contentTopic !== topic) { return false; @@ -55,7 +55,7 @@ export class MessageCollector { } // Type guard to determine if a message is of type MessageRpcResponse - isMessageRpcResponse( + public isMessageRpcResponse( message: MessageRpcResponse | DecodedMessage ): message is MessageRpcResponse { return ( @@ -64,7 +64,7 @@ export class MessageCollector { ); } - async waitForMessages( + public async waitForMessages( numMessages: number, options?: { pubsubTopic?: string; @@ -106,7 +106,7 @@ export class MessageCollector { } } - async waitForMessagesAutosharding( + public async waitForMessagesAutosharding( numMessages: number, options?: { contentTopic: string; @@ -150,7 +150,7 @@ export class MessageCollector { } // Verifies a received message against expected values. - verifyReceivedMessage( + public verifyReceivedMessage( index: number, options: { expectedMessageText: string | Uint8Array | undefined; diff --git a/packages/tests/src/lib/service_node.ts b/packages/tests/src/lib/service_node.ts index 1e8bb63532..64cf8285a9 100644 --- a/packages/tests/src/lib/service_node.ts +++ b/packages/tests/src/lib/service_node.ts @@ -54,7 +54,7 @@ export class ServiceNode { * Convert a [[WakuMessage]] to a [[WakuRelayMessage]]. The latter is used * by the nwaku JSON-RPC API. */ - static toMessageRpcQuery(message: { + public static toMessageRpcQuery(message: { payload: Uint8Array; contentTopic: string; timestamp?: Date; @@ -75,23 +75,23 @@ export class ServiceNode { }; } - constructor(logName: string) { + public constructor(logName: string) { this.logPath = `${LOG_DIR}/wakunode_${logName}.log`; } - get type(): "go-waku" | "nwaku" { + public get type(): "go-waku" | "nwaku" { return isGoWaku ? "go-waku" : "nwaku"; } - get nodeType(): "go-waku" | "nwaku" { + public get nodeType(): "go-waku" | "nwaku" { return isGoWaku ? "go-waku" : "nwaku"; } - get containerName(): string | undefined { + public get containerName(): string | undefined { return this.docker?.container?.id; } - async start( + public async start( args: Args = {}, options: { retries?: number; @@ -200,7 +200,7 @@ export class ServiceNode { delete this.docker; } - async waitForLog(msg: string, timeout: number): Promise { + public async waitForLog(msg: string, timeout: number): Promise { return waitForLine(this.logPath, msg, timeout); } @@ -208,7 +208,7 @@ export class ServiceNode { * Calls nwaku REST API "/admin/v1/peers" to check for known peers * @throws */ - async peers(): Promise { + public async peers(): Promise { this.checkProcess(); return this.restCall( @@ -222,7 +222,7 @@ export class ServiceNode { ); } - async info(): Promise { + public async info(): Promise { this.checkProcess(); return this.restCall( @@ -233,7 +233,7 @@ export class ServiceNode { ); } - async healthy(): Promise { + public async healthy(): Promise { this.checkProcess(); return this.restCall( @@ -244,7 +244,7 @@ export class ServiceNode { ); } - async ensureSubscriptions( + public async ensureSubscriptions( pubsubTopics: string[] = [DefaultPubsubTopic] ): Promise { return this.restCall( @@ -255,7 +255,7 @@ export class ServiceNode { ); } - async messages(pubsubTopic?: string): Promise { + public async messages(pubsubTopic?: string): Promise { return this.restCall( `/relay/v1/messages/${encodeURIComponent(pubsubTopic || this?.args?.pubsubTopic?.[0] || DefaultPubsubTopic)}`, "GET", @@ -267,7 +267,7 @@ export class ServiceNode { ); } - async ensureSubscriptionsAutosharding( + public async ensureSubscriptionsAutosharding( contentTopics: string[] ): Promise { this.checkProcess(); @@ -280,7 +280,7 @@ export class ServiceNode { ); } - async sendMessage( + public async sendMessage( message: MessageRpcQuery, pubsubTopic?: string ): Promise { @@ -298,7 +298,9 @@ export class ServiceNode { ); } - async sendMessageAutosharding(message: MessageRpcQuery): Promise { + public async sendMessageAutosharding( + message: MessageRpcQuery + ): Promise { this.checkProcess(); if (typeof message.timestamp === "undefined") { @@ -313,7 +315,7 @@ export class ServiceNode { ); } - async messagesAutosharding( + public async messagesAutosharding( contentTopic: string ): Promise { this.checkProcess(); @@ -329,13 +331,13 @@ export class ServiceNode { ); } - async getPeerId(): Promise { + public async getPeerId(): Promise { if (this.peerId) return this.peerId; this.peerId = await this._getPeerId(); return this.peerId; } - async getMultiaddrWithId(): Promise { + public async getMultiaddrWithId(): Promise { if (this.multiaddrWithId) return this.multiaddrWithId; const peerId = await this.getPeerId(); @@ -362,15 +364,15 @@ export class ServiceNode { return this.peerId; } - get httpUrl(): string { + public get httpUrl(): string { return `http://127.0.0.1:${this.restPort}`; } - get pubsubTopics(): string[] { + public get pubsubTopics(): string[] { return this.args?.pubsubTopic ?? []; } - async restCall( + public async restCall( endpoint: string, method: "GET" | "POST", body: any = null, diff --git a/packages/utils/src/logger/index.ts b/packages/utils/src/logger/index.ts index 02ccec66d3..725d55f665 100644 --- a/packages/utils/src/logger/index.ts +++ b/packages/utils/src/logger/index.ts @@ -7,29 +7,29 @@ export class Logger { private _warn: Debugger; private _error: Debugger; - static createDebugNamespace(level: string, prefix?: string): string { + private static createDebugNamespace(level: string, prefix?: string): string { return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`; } - constructor(prefix?: string) { + public constructor(prefix?: string) { this._info = debug(Logger.createDebugNamespace("info", prefix)); this._warn = debug(Logger.createDebugNamespace("warn", prefix)); this._error = debug(Logger.createDebugNamespace("error", prefix)); } - get info(): Debugger { + public get info(): Debugger { return this._info; } - get warn(): Debugger { + public get warn(): Debugger { return this._warn; } - get error(): Debugger { + public get error(): Debugger { return this._error; } - log(level: "info" | "warn" | "error", ...args: unknown[]): void { + public log(level: "info" | "warn" | "error", ...args: unknown[]): void { const logger = this[level] as (...args: unknown[]) => void; logger(...args); }