aboutsummaryrefslogtreecommitdiffstats
path: root/lib/nostr.ts
blob: 5ef8af3d269b9056dc00a574237c1b12a53aa9ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import config from "$config";
import { g, s } from "$lib/db";
import { l } from "$lib/logging";
import { count, scan } from "$lib/strfry";
import { fail } from "$lib/utils";
import { finalizeEvent, getPublicKey, nip19 } from "nostr-tools";
import { AbstractSimplePool } from "nostr-tools/abstract-pool";
import { Relay } from "nostr-tools/relay";

export const serverPubkey = getPublicKey(
  nip19.decode(config.nostrKey).data as Uint8Array,
);

const alwaysTrue: any = (t: Event) => {
  t[Symbol("verified")] = true;
  return true;
};
export const pool = new AbstractSimplePool({ verifyEvent: alwaysTrue });
const opts = { maxWait: 2000 };

export const anon = (pubkey) => ({
  username: pubkey.substr(0, 6),
  pubkey,
  anon: true,
  follows: [],
  followers: [],
});

export async function send(ev, url = config.nostr) {
  if (!ev?.id) return;
  const r = await Relay.connect(url);
  await r.publish(ev);
  r.close();
}

export async function handleZap(invoice) {
  try {
    const pubkey = serverPubkey;
    const sk = nip19.decode(config.nostrKey).data as Uint8Array;
    const zapreq = JSON.parse(invoice.description);

    if (!zapreq.tags || zapreq.tags.length === 0) {
      fail("No tags found");
    }

    const ptags = zapreq.tags.filter(
      (t) => t?.length && t.length >= 2 && t[0] === "p",
    );

    if (ptags.length !== 1) {
      fail("None or multiple p tags found");
    }

    const etags = zapreq.tags.filter(
      (t) => t?.length && t.length >= 2 && t[0] === "e",
    );

    if (!(etags.length === 0 || etags.length === 1)) {
      fail("Expected none or 1 e tags");
    }

    const relays_tag = zapreq.tags.find(
      (t) => t?.length && t.length >= 2 && t[0] === "relays",
    );

    if (!relays_tag) {
      fail("No relays tag found");
    }

    const relays = relays_tag.slice(1).filter((r) => r?.startsWith("ws"));
    const etag = etags.length > 0 && etags[0];
    const ptag = ptags[0];

    const kind = 9735;
    const created_at = invoice.paid_at;
    const content = zapreq.content;

    const tags = [ptag];
    if (etag) tags.push(etag);

    tags.push(["bolt11", invoice.bolt11]);
    tags.push(["description", invoice.description]);
    tags.push(["preimage", invoice.payment_preimage]);

    const ev = { pubkey, kind, created_at, content, tags };
    const signed = await finalizeEvent(ev, sk);

    l("sending receipt");

    relays.map(async (url) => {
      try {
        const r = await Relay.connect(url);
        await r.publish(signed);
        setTimeout(() => r.close(), 1000);
      } catch (e) {}
    });
  } catch (e) {
    warn("failed to send receipt", e.message);
  }
}

export const getRelays = async (pubkey): Promise<any> => {
  const { relays } = config;
  const filter = { authors: [pubkey], kinds: [10002] };
  const result = await scan(filter);

  let read = relays;
  let write = relays;

  if (result.length) {
    const { tags } = result[0];
    read = [];
    write = [];
    for (const r of tags) {
      if (r[0] !== "r") continue;
      if (!r[2] || r[2] === "write") write.push(r[1]);
      if (!r[2] || r[2] === "read") read.push(r[1]);
    }
  } else
    pool
      .get(relays, filter)
      .then(send)
      .catch(() => {});

  return { read, write };
};

export const getProfile = async (pubkey, relays = [config.nostr]) => {
  let profile = await g(`${pubkey}:profile`);

  if (!profile) {
    const pubkeys = [pubkey];
    let filter: any = { authors: pubkeys, kinds: [0] };

    let ev = await pool.get(relays, filter, opts);

    if (!ev) {
      ({ write: relays } = await getRelays(pubkey));
      ev = await pool.get(relays, filter, opts);
    }

    if (!ev) {
      filter = { cache: ["user_infos", { pubkeys }] };
      ev = (await pool.querySync([config.cache], filter, opts)).find(
        (e) => e.kind === 0,
      );
    }

    if (ev) {
      send(ev);
      profile = JSON.parse(ev.content);
    } else {
      profile = anon(pubkey);
    }
  }

  await s(`${pubkey}:profile`, profile);
  return profile;
};

export const getCount = async (pubkey) => {
  try {
    const result = await scan({ authors: [pubkey], kinds: [3] });
    const follows = result.length
      ? result[0].tags.filter((t) => t[0] === "p").length
      : 0;

    const [followers] = await count({ "#p": [pubkey], kinds: [3] });
    return { follows, followers };
  } catch (e) {
    console.log(e);
  }
};