394 lines
10 KiB
TypeScript
Raw Normal View History

import type { PeerId } from "@libp2p/interface-peer-id";
import { peerIdFromString } from "@libp2p/peer-id";
import { Multiaddr, multiaddr } from "@multiformats/multiaddr";
import { DefaultPubSubTopic } from "@waku/core";
import { isDefined } from "@waku/utils";
import { bytesToHex, hexToBytes } from "@waku/utils/bytes";
2022-02-04 14:12:00 +11:00
import debug from "debug";
import portfinder from "portfinder";
2021-03-10 17:39:53 +11:00
import { existsAsync, mkdirAsync, openAsync } from "../async_fs.js";
import { delay } from "../delay.js";
import waitForLine from "../log_file.js";
import Dockerode from "./dockerode.js";
import {
Args,
KeyPair,
LogLevel,
MessageRpcQuery,
MessageRpcResponse,
} from "./interfaces.js";
2021-03-10 17:39:53 +11:00
const log = debug("waku:node");
2021-04-06 11:00:40 +10:00
const WAKU_SERVICE_NODE_PARAMS =
process.env.WAKU_SERVICE_NODE_PARAMS ?? undefined;
2022-05-26 15:49:39 +10:00
const NODE_READY_LOG_LINE = "Node setup complete";
2021-03-10 17:39:53 +11:00
const DOCKER_IMAGE_NAME =
process.env.WAKUNODE_IMAGE || "statusteam/nim-waku:v0.17.0";
const isGoWaku = DOCKER_IMAGE_NAME.includes("go-waku");
2022-02-04 14:12:00 +11:00
const LOG_DIR = "./log";
const OneMillion = BigInt(1_000_000);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
BigInt.prototype.toJSON = function toJSON() {
return Number(this);
};
export class NimGoNode {
private docker?: Dockerode;
private peerId?: PeerId;
private multiaddrWithId?: Multiaddr;
2023-01-27 15:37:57 +11:00
private websocketPort?: number;
2022-02-01 12:54:54 +11:00
private readonly logPath: string;
private rpcPort?: number;
2021-03-10 17:39:53 +11:00
/**
* Convert a [[WakuMessage]] to a [[WakuRelayMessage]]. The latter is used
* by the nwaku JSON-RPC API.
*/
static toMessageRpcQuery(message: {
payload: Uint8Array;
contentTopic: string;
timestamp?: Date;
}): MessageRpcQuery {
if (!message.payload) {
throw "Attempting to convert empty message";
}
let timestamp;
if (message.timestamp) {
timestamp = BigInt(message.timestamp.valueOf()) * OneMillion;
}
return {
2023-03-21 12:10:56 +11:00
payload: Buffer.from(message.payload).toString("base64"),
contentTopic: message.contentTopic,
timestamp,
};
}
2021-03-25 15:49:07 +11:00
constructor(logName: string) {
this.logPath = `${LOG_DIR}/wakunode_${logName}.log`;
}
type(): "go-waku" | "nwaku" {
return isGoWaku ? "go-waku" : "nwaku";
}
feat!: filter v2 (#1332) * implement proto * implement filter v2 * add tests * minor improvements - make unsubscribe functions private in filter - enable all tests * enable all tests * readd multiaddrinput * address comment removals * unsubscribe based on contentFilters passed * update unsubscribe function parameters in test * reset interfaces & filter v1 * refactor filterv2 into 2 classes - removes generics from types on filter which means manual typecasting to filter version is required on consumer side - defaults to filterv2 - splits filterv2 into 2 classes: - one to create the subscription object with a peer which returns the second class - the other to manage all subscription functions * updates filter tests for the new API - also fixes an interface import * update `toAsyncIterator` test for Filter V1 * implement IReceiver on FilterV2 * remove return values from subscription functions * update `to_async_iterator` * address variable naming * add tsdoc comments for hidden function * address minor comments * update docs to default to filter v2 * address comments * rename `wakuFilter` to `wakuFilterV1` * chore: Remove static variables (#1371) * chore: Remove static variables - Remove internal types from `@core/interfaces` - Remove data being redundantly stored (pubsub topic) - Remove usage of static variables - Clean up callbacks and decoders when using `unsubscribe` - Clean up callbacks and decoders when using `unsubscribeAll` * fix setting activeSubscription --------- Co-authored-by: danisharora099 <danisharora099@gmail.com> * make activeSub getter and setter private * update size-limit --------- Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com>
2023-05-23 16:06:46 +05:30
get nodeType(): "go-waku" | "nwaku" {
return isGoWaku ? "go-waku" : "nwaku";
}
async start(args: Args = {}): Promise<void> {
this.docker = await Dockerode.createInstance(DOCKER_IMAGE_NAME);
try {
await existsAsync(LOG_DIR);
} catch (e) {
try {
await mkdirAsync(LOG_DIR);
} catch (e) {
// Looks like 2 tests tried to create the director at the same time,
// it can be ignored
}
}
await openAsync(this.logPath, "w");
2021-03-11 10:54:35 +11:00
const mergedArgs = defaultArgs();
// waku nodes takes some time to bind port so to decrease chances of conflict
// we also randomize the first port that portfinder will try
const startPort = Math.floor(Math.random() * (65535 - 1025) + 1025);
2022-02-01 12:54:54 +11:00
const ports: number[] = await new Promise((resolve, reject) => {
portfinder.getPorts(4, { port: startPort }, (err, ports) => {
2022-02-01 12:54:54 +11:00
if (err) reject(err);
resolve(ports);
});
});
if (isGoWaku && !args.logLevel) {
args.logLevel = LogLevel.Debug;
}
const [rpcPort, tcpPort, websocketPort, discv5UdpPort] = ports;
this.rpcPort = rpcPort;
this.websocketPort = websocketPort;
// Object.assign overrides the properties with the source (if there are conflicts)
2021-04-09 11:23:00 +10:00
Object.assign(
mergedArgs,
2022-02-01 12:54:54 +11:00
{
rpcPort,
tcpPort,
websocketPort,
...(args?.peerExchange && { discv5UdpPort }),
feat!: filter v2 (#1332) * implement proto * implement filter v2 * add tests * minor improvements - make unsubscribe functions private in filter - enable all tests * enable all tests * readd multiaddrinput * address comment removals * unsubscribe based on contentFilters passed * update unsubscribe function parameters in test * reset interfaces & filter v1 * refactor filterv2 into 2 classes - removes generics from types on filter which means manual typecasting to filter version is required on consumer side - defaults to filterv2 - splits filterv2 into 2 classes: - one to create the subscription object with a peer which returns the second class - the other to manage all subscription functions * updates filter tests for the new API - also fixes an interface import * update `toAsyncIterator` test for Filter V1 * implement IReceiver on FilterV2 * remove return values from subscription functions * update `to_async_iterator` * address variable naming * add tsdoc comments for hidden function * address minor comments * update docs to default to filter v2 * address comments * rename `wakuFilter` to `wakuFilterV1` * chore: Remove static variables (#1371) * chore: Remove static variables - Remove internal types from `@core/interfaces` - Remove data being redundantly stored (pubsub topic) - Remove usage of static variables - Clean up callbacks and decoders when using `unsubscribe` - Clean up callbacks and decoders when using `unsubscribeAll` * fix setting activeSubscription --------- Co-authored-by: danisharora099 <danisharora099@gmail.com> * make activeSub getter and setter private * update size-limit --------- Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com>
2023-05-23 16:06:46 +05:30
...(isGoWaku && { minRelayPeersToPublish: 0 }),
2022-02-01 12:54:54 +11:00
},
{ rpcAddress: "0.0.0.0" },
2021-04-09 11:23:00 +10:00
args
);
process.env.WAKUNODE2_STORE_MESSAGE_DB_URL = "";
if (this.docker.container) {
await this.docker.stop();
}
feat!: implement peer exchange (#1027) * wip -- yet to test * update: draft * wip * support passing flags manually to nwaku node * refactor peer-exchange test * switch response from uint8array to ENR * rm: unnecesary logs * implement clas * fix: for loop * init-wip: directories * setup: new package & fix circular deps * bind a response handler * wip: refactor & update test * test logs * wip code - debugging * address: comments * Update packages/core/src/lib/waku_peer_exchange/peer_discovery.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * Update packages/core/src/lib/waku_peer_exchange/peer_discovery.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * address: comments * address: comments * address: comments * address: comments * address: comments * fix: test build * refactor * fix: build * comply with API * numPeers: use number instead of bigint * fix: build * Update packages/peer-exchange/package.json Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * Update packages/peer-exchange/src/waku_peer_exchange.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * Update packages/peer-exchange/src/waku_peer_exchange.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * Update packages/peer-exchange/src/waku_peer_exchange.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * address: comments, add eslint config * Update packages/peer-exchange/.eslintrc.cjs Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * Update packages/peer-exchange/src/index.ts Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * address comments * test works with test fleet * rm: only for px test => run all tests * fix: tests * reorder packages for build, and fix imports * remove: px test doesnt work with local nodes * chore: move proto into a separate package * fix: proto dir * fix: build * fix: ci * add: index for proto * fix: ci * Update packages/proto/package.json Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com> * address comments * chore: run failing test with higher timeout * chore: run failing test with higher timeout * fix: ci Co-authored-by: fryorcraken.eth <110212804+fryorcraken@users.noreply.github.com>
2022-12-07 11:35:30 +05:30
await this.docker.startContainer(
ports,
mergedArgs,
this.logPath,
WAKU_SERVICE_NODE_PARAMS
);
2021-03-10 17:39:53 +11:00
try {
log(`Waiting to see '${NODE_READY_LOG_LINE}' in ${this.type} logs`);
await this.waitForLog(NODE_READY_LOG_LINE, 15000);
if (process.env.CI) await delay(100);
log(`${this.type} node has been started`);
} catch (error) {
log(`Error starting ${this.type}: ${error}`);
if (this.docker.container) await this.docker.stop();
throw error;
}
}
public async stop(): Promise<void> {
this.docker?.stop();
}
async waitForLog(msg: string, timeout: number): Promise<void> {
return waitForLine(this.logPath, msg, timeout);
2021-03-10 17:39:53 +11:00
}
2022-04-01 12:19:51 +11:00
/** Calls nwaku JSON-RPC API `get_waku_v2_admin_v1_peers` to check
2021-03-10 17:39:53 +11:00
* for known peers
* @throws if WakuNode isn't started.
2021-03-10 17:39:53 +11:00
*/
async peers(): Promise<string[]> {
2021-03-10 17:39:53 +11:00
this.checkProcess();
2022-02-04 14:12:00 +11:00
return this.rpcCall<string[]>("get_waku_v2_admin_v1_peers", []);
2021-03-10 17:39:53 +11:00
}
async info(): Promise<RpcInfoResponse> {
2021-03-10 17:39:53 +11:00
this.checkProcess();
2022-02-04 14:12:00 +11:00
return this.rpcCall<RpcInfoResponse>("get_waku_v2_debug_v1_info", []);
2021-03-10 17:39:53 +11:00
}
async sendMessage(
message: MessageRpcQuery,
pubSubTopic: string = DefaultPubSubTopic
): Promise<boolean> {
this.checkProcess();
if (typeof message.timestamp === "undefined") {
message.timestamp = BigInt(new Date().valueOf()) * OneMillion;
}
2022-02-04 14:12:00 +11:00
return this.rpcCall<boolean>("post_waku_v2_relay_v1_message", [
pubSubTopic,
message,
]);
}
async messages(
pubsubTopic: string = DefaultPubSubTopic
): Promise<MessageRpcResponse[]> {
this.checkProcess();
const msgs = await this.rpcCall<MessageRpcResponse[]>(
2022-02-04 14:12:00 +11:00
"get_waku_v2_relay_v1_messages",
[pubsubTopic]
2021-07-07 11:23:56 +10:00
);
return msgs.filter(isDefined);
}
async getAsymmetricKeyPair(): Promise<KeyPair> {
this.checkProcess();
const { privateKey, publicKey, seckey, pubkey } = await this.rpcCall<{
seckey: string;
pubkey: string;
privateKey: string;
publicKey: string;
2022-02-04 14:12:00 +11:00
}>("get_waku_v2_private_v1_asymmetric_keypair", []);
// To be removed once https://github.com/vacp2p/rfc/issues/507 is fixed
if (seckey) {
return { privateKey: seckey, publicKey: pubkey };
} else {
return { privateKey, publicKey };
}
}
async postAsymmetricMessage(
message: MessageRpcQuery,
publicKey: Uint8Array,
pubSubTopic?: string
): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
2022-02-04 14:12:00 +11:00
throw "Attempting to send empty message";
}
2022-02-04 14:12:00 +11:00
return this.rpcCall<boolean>("post_waku_v2_private_v1_asymmetric_message", [
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
message,
2022-02-14 10:50:02 +11:00
"0x" + bytesToHex(publicKey),
]);
}
async getAsymmetricMessages(
privateKey: Uint8Array,
pubSubTopic?: string
): Promise<MessageRpcResponse[]> {
this.checkProcess();
return await this.rpcCall<MessageRpcResponse[]>(
2022-02-04 14:12:00 +11:00
"get_waku_v2_private_v1_asymmetric_messages",
[
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
2022-02-14 10:50:02 +11:00
"0x" + bytesToHex(privateKey),
]
);
}
2022-02-14 10:50:02 +11:00
async getSymmetricKey(): Promise<Uint8Array> {
this.checkProcess();
return this.rpcCall<string>(
2022-02-04 14:12:00 +11:00
"get_waku_v2_private_v1_symmetric_key",
[]
2022-02-14 10:50:02 +11:00
).then(hexToBytes);
}
async postSymmetricMessage(
message: MessageRpcQuery,
symKey: Uint8Array,
pubSubTopic?: string
): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
2022-02-04 14:12:00 +11:00
throw "Attempting to send empty message";
}
2022-02-04 14:12:00 +11:00
return this.rpcCall<boolean>("post_waku_v2_private_v1_symmetric_message", [
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
message,
2022-02-14 10:50:02 +11:00
"0x" + bytesToHex(symKey),
]);
}
async getSymmetricMessages(
symKey: Uint8Array,
pubSubTopic?: string
): Promise<MessageRpcResponse[]> {
this.checkProcess();
return await this.rpcCall<MessageRpcResponse[]>(
2022-02-04 14:12:00 +11:00
"get_waku_v2_private_v1_symmetric_messages",
2022-02-14 10:50:02 +11:00
[
pubSubTopic ? pubSubTopic : DefaultPubSubTopic,
"0x" + bytesToHex(symKey),
]
);
}
async getPeerId(): Promise<PeerId> {
2023-01-27 15:37:57 +11:00
if (this.peerId) return this.peerId;
this.peerId = await this._getPeerId();
return this.peerId;
}
async getMultiaddrWithId(): Promise<Multiaddr> {
2023-01-27 15:37:57 +11:00
if (this.multiaddrWithId) return this.multiaddrWithId;
const peerId = await this.getPeerId();
this.multiaddrWithId = multiaddr(
`/ip4/127.0.0.1/tcp/${this.websocketPort}/ws/p2p/${peerId.toString()}`
);
return this.multiaddrWithId;
}
2023-01-27 15:37:57 +11:00
private async _getPeerId(): Promise<PeerId> {
if (this.peerId) {
return this.peerId;
}
const res = await this.info();
2023-01-27 15:37:57 +11:00
const multiaddrWithId = res.listenAddresses
.map((ma) => multiaddr(ma))
2022-02-04 14:12:00 +11:00
.find((ma) => ma.protoNames().includes("ws"));
if (!multiaddrWithId) throw `${this.type} did not return a ws multiaddr`;
2023-01-27 15:37:57 +11:00
const peerIdStr = multiaddrWithId.getPeerId();
if (!peerIdStr) throw `${this.type} multiaddr does not contain peerId`;
this.peerId = peerIdFromString(peerIdStr);
2023-01-27 15:37:57 +11:00
return this.peerId;
2021-03-10 17:39:53 +11:00
}
get rpcUrl(): string {
return `http://127.0.0.1:${this.rpcPort}/`;
2021-03-10 17:39:53 +11:00
}
private async rpcCall<T>(
2021-04-13 15:22:29 +10:00
method: string,
params: Array<string | number | unknown>
): Promise<T> {
log("RPC Query: ", method, params);
2022-02-14 09:26:22 +11:00
const res = await fetch(this.rpcUrl, {
method: "POST",
body: JSON.stringify({
2022-02-04 14:12:00 +11:00
jsonrpc: "2.0",
2021-03-10 17:39:53 +11:00
id: 1,
method,
params,
2022-02-14 09:26:22 +11:00
}),
headers: new Headers({ "Content-Type": "application/json" }),
});
const json = await res.json();
2022-11-15 14:15:29 +11:00
log(`RPC Response: `, JSON.stringify(json));
2022-02-14 09:26:22 +11:00
return json.result;
2021-03-10 17:39:53 +11:00
}
private checkProcess(): void {
if (!this.docker?.container) {
throw `${this.type} container hasn't started`;
2021-03-10 17:39:53 +11:00
}
}
}
2021-03-11 10:54:35 +11:00
export function defaultArgs(): Args {
2021-03-11 10:54:35 +11:00
return {
listenAddress: "0.0.0.0",
2021-03-11 10:54:35 +11:00
rpc: true,
relay: false,
2021-03-11 10:54:35 +11:00
rpcAdmin: true,
websocketSupport: true,
logLevel: LogLevel.Trace,
2021-03-11 10:54:35 +11:00
};
}
interface RpcInfoResponse {
2022-01-19 15:43:45 +11:00
// multiaddrs including peer id.
listenAddresses: string[];
2022-05-04 20:07:21 +10:00
enrUri?: string;
}
export function base64ToUtf8(b64: string): string {
return Buffer.from(b64, "base64").toString("utf-8");
}