nip-114: filter.ids_only, HAVE message

This commit is contained in:
Martti Malmi 2024-01-16 13:23:57 +02:00
parent 7c1f2c539f
commit 579589f635
5 changed files with 27 additions and 1 deletions

View File

@ -6,6 +6,7 @@ import { Connection, RelaySettings } from "./connection";
import { NostrEvent, OkResponse, TaggedNostrEvent } from "./nostr";
import { pickRelaysForReply } from "./outbox-model";
import { SystemInterface } from ".";
import LRUSet from "@snort/shared/src/LRUSet";
export interface NostrConnectionPoolEvents {
connected: (address: string, wasReconnect: boolean) => void;
@ -38,6 +39,7 @@ export class DefaultConnectionPool extends EventEmitter<NostrConnectionPoolEvent
* All currently connected websockets
*/
#sockets = new Map<string, Connection>();
#requestedIds = new LRUSet<string>(1000);
constructor(system: SystemInterface) {
super();
@ -69,6 +71,20 @@ export class DefaultConnectionPool extends EventEmitter<NostrConnectionPoolEvent
}
this.emit("event", addr, s, e);
});
c.on("have", async (s, id) => {
this.#log("%s have: %s %o", c.Address, s, id);
if (this.#requestedIds.has(id)) {
// already requested from this or another relay
return;
}
this.#requestedIds.add(id);
if (await this.#system.eventsCache.get(id)) {
// already have it locally
// TODO better local cache / db
return;
}
c.QueueReq(["REQ", "*", { ids: [id] }], () => {});
});
c.on("eose", s => this.emit("eose", addr, s));
c.on("disconnect", code => this.emit("disconnect", addr, code));
c.on("connected", r => this.emit("connected", addr, r));

View File

@ -28,6 +28,7 @@ interface ConnectionEvents {
disconnect: (code: number) => void;
auth: (challenge: string, relay: string, cb: (ev: NostrEvent) => void) => void;
notice: (msg: string) => void;
have: (sub: string, ids: u256) => void; // NIP-114
unknownMessage: (obj: Array<any>) => void;
}
@ -210,6 +211,11 @@ export class Connection extends EventEmitter<ConnectionEvents> {
// todo: stats events received
break;
}
// NIP-114: GetMatchingEventIds
case "HAVE": {
this.emit("have", msg[1] as string, msg[2] as u256);
break;
}
case "EOSE": {
this.emit("eose", msg[1] as string);
break;

View File

@ -1,3 +1,4 @@
export enum Nips {
Search = 50,
GetMatchingEventIds = 114,
}

View File

@ -37,7 +37,7 @@ export type MaybeHexKey = HexKey | undefined;
*/
export type u256 = string;
export type ReqCommand = [cmd: "REQ", id: string, ...filters: Array<ReqFilter>];
export type ReqCommand = [cmd: "REQ" | "IDS", id: string, ...filters: Array<ReqFilter>];
/**
* Raw REQ filter object

View File

@ -394,6 +394,9 @@ export class Query extends EventEmitter<QueryEvents> {
#sendQueryInternal(c: Connection, q: BuiltRawReqFilter) {
let filters = q.filters;
if (c.SupportsNip(Nips.GetMatchingEventIds)) {
filters = filters.map(f => ({ ...f, ids_only: true }));
}
const qt = new QueryTrace(c.Address, filters, c.Id);
qt.on("close", x => c.closeReq(x));