@qntx/nostr 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +25 -0
- package/dist/builder-BphJa-Y-.d.mts +67 -0
- package/dist/builder-q0VsvnYE.mjs +158 -0
- package/dist/builder-q0VsvnYE.mjs.map +1 -0
- package/dist/client-Bd8B1mYm.mjs +835 -0
- package/dist/client-Bd8B1mYm.mjs.map +1 -0
- package/dist/client.d.mts +2 -0
- package/dist/client.mjs +2 -0
- package/dist/core.d.mts +8 -0
- package/dist/core.mjs +9 -0
- package/dist/error-B49rbDzT.d.mts +7 -0
- package/dist/error-CwBxle6N.mjs +13 -0
- package/dist/error-CwBxle6N.mjs.map +1 -0
- package/dist/error-DZEs5OuZ.mjs +24 -0
- package/dist/error-DZEs5OuZ.mjs.map +1 -0
- package/dist/error-WEFS-R-4.d.mts +20 -0
- package/dist/event-B5D2jxt_.d.mts +108 -0
- package/dist/event-CzoQEFMF.mjs +188 -0
- package/dist/event-CzoQEFMF.mjs.map +1 -0
- package/dist/filter-BxwjEkZp.mjs +113 -0
- package/dist/filter-BxwjEkZp.mjs.map +1 -0
- package/dist/filter-DUEKP3q1.d.mts +40 -0
- package/dist/gossip-3xkRRCm_.mjs +220 -0
- package/dist/gossip-3xkRRCm_.mjs.map +1 -0
- package/dist/gossip-C5RVB1UB.d.mts +71 -0
- package/dist/gossip.d.mts +3 -0
- package/dist/gossip.mjs +2 -0
- package/dist/http-6vevbBlu.d.mts +22 -0
- package/dist/http-D2rhokZo.mjs +24 -0
- package/dist/http-D2rhokZo.mjs.map +1 -0
- package/dist/index-BYMnhRIC.d.mts +161 -0
- package/dist/index-C0C4e-Gn.d.mts +55 -0
- package/dist/index-CaxrMD1A.d.mts +1 -0
- package/dist/index-DaRyjo7O.d.mts +77 -0
- package/dist/index-DgOugrpF.d.mts +275 -0
- package/dist/index-EwL6fHLo.d.mts +267 -0
- package/dist/index-k2YhCgsh.d.mts +57 -0
- package/dist/index.d.mts +22 -0
- package/dist/index.mjs +23 -0
- package/dist/key-BiGxGLhg.d.mts +37 -0
- package/dist/key-Dn-aX4x4.mjs +130 -0
- package/dist/key-Dn-aX4x4.mjs.map +1 -0
- package/dist/kind-BLl4cLOc.mjs +59 -0
- package/dist/kind-BLl4cLOc.mjs.map +1 -0
- package/dist/loaders-BNQszDAn.mjs +767 -0
- package/dist/loaders-BNQszDAn.mjs.map +1 -0
- package/dist/loaders.d.mts +3 -0
- package/dist/loaders.mjs +2 -0
- package/dist/memory-BCmhZPek.mjs +461 -0
- package/dist/memory-BCmhZPek.mjs.map +1 -0
- package/dist/message-C_Uj-Y-c.mjs +179 -0
- package/dist/message-C_Uj-Y-c.mjs.map +1 -0
- package/dist/message-DJC-Jz6T.d.mts +32 -0
- package/dist/nip17-BWq-Kfq5.d.mts +38 -0
- package/dist/nip19-D7905oIv.d.mts +63 -0
- package/dist/nip46-C_DoxiS_.d.mts +51 -0
- package/dist/nip59-DljW_sYh.d.mts +76 -0
- package/dist/nip65-Di5hZRuV.d.mts +21 -0
- package/dist/nip77-ByxlgoQO.d.mts +55 -0
- package/dist/nips/blossom.d.mts +93 -0
- package/dist/nips/blossom.mjs +325 -0
- package/dist/nips/blossom.mjs.map +1 -0
- package/dist/nips/nip04.d.mts +8 -0
- package/dist/nips/nip04.mjs +41 -0
- package/dist/nips/nip04.mjs.map +1 -0
- package/dist/nips/nip05.d.mts +89 -0
- package/dist/nips/nip05.mjs +147 -0
- package/dist/nips/nip05.mjs.map +1 -0
- package/dist/nips/nip10.d.mts +43 -0
- package/dist/nips/nip10.mjs +194 -0
- package/dist/nips/nip10.mjs.map +1 -0
- package/dist/nips/nip11.d.mts +43 -0
- package/dist/nips/nip11.mjs +99 -0
- package/dist/nips/nip11.mjs.map +1 -0
- package/dist/nips/nip13.d.mts +23 -0
- package/dist/nips/nip13.mjs +88 -0
- package/dist/nips/nip13.mjs.map +1 -0
- package/dist/nips/nip17.d.mts +2 -0
- package/dist/nips/nip17.mjs +138 -0
- package/dist/nips/nip17.mjs.map +1 -0
- package/dist/nips/nip19.d.mts +2 -0
- package/dist/nips/nip19.mjs +174 -0
- package/dist/nips/nip19.mjs.map +1 -0
- package/dist/nips/nip21.d.mts +17 -0
- package/dist/nips/nip21.mjs +29 -0
- package/dist/nips/nip21.mjs.map +1 -0
- package/dist/nips/nip27.d.mts +42 -0
- package/dist/nips/nip27.mjs +175 -0
- package/dist/nips/nip27.mjs.map +1 -0
- package/dist/nips/nip42.d.mts +12 -0
- package/dist/nips/nip42.mjs +22 -0
- package/dist/nips/nip42.mjs.map +1 -0
- package/dist/nips/nip44.d.mts +12 -0
- package/dist/nips/nip44.mjs +125 -0
- package/dist/nips/nip44.mjs.map +1 -0
- package/dist/nips/nip46.d.mts +2 -0
- package/dist/nips/nip46.mjs +132 -0
- package/dist/nips/nip46.mjs.map +1 -0
- package/dist/nips/nip49.d.mts +12 -0
- package/dist/nips/nip49.mjs +80 -0
- package/dist/nips/nip49.mjs.map +1 -0
- package/dist/nips/nip51.d.mts +88 -0
- package/dist/nips/nip51.mjs +246 -0
- package/dist/nips/nip51.mjs.map +1 -0
- package/dist/nips/nip57.d.mts +43 -0
- package/dist/nips/nip57.mjs +230 -0
- package/dist/nips/nip57.mjs.map +1 -0
- package/dist/nips/nip59.d.mts +2 -0
- package/dist/nips/nip59.mjs +171 -0
- package/dist/nips/nip59.mjs.map +1 -0
- package/dist/nips/nip65.d.mts +2 -0
- package/dist/nips/nip65.mjs +76 -0
- package/dist/nips/nip65.mjs.map +1 -0
- package/dist/nips/nip77.d.mts +2 -0
- package/dist/nips/nip77.mjs +421 -0
- package/dist/nips/nip77.mjs.map +1 -0
- package/dist/nips/nip96.d.mts +31 -0
- package/dist/nips/nip96.mjs +95 -0
- package/dist/nips/nip96.mjs.map +1 -0
- package/dist/nips/nip98.d.mts +28 -0
- package/dist/nips/nip98.mjs +91 -0
- package/dist/nips/nip98.mjs.map +1 -0
- package/dist/nostr_crypto_wasm_bg-hi5aXi5P.mjs +4 -0
- package/dist/nostr_crypto_wasm_bg.wasm +0 -0
- package/dist/pool-C_j1OmBB.mjs +1881 -0
- package/dist/pool-C_j1OmBB.mjs.map +1 -0
- package/dist/pool-DhRi7l-b.d.mts +297 -0
- package/dist/relay.d.mts +4 -0
- package/dist/relay.mjs +2 -0
- package/dist/signer-CZ6K6FUc.mjs +473 -0
- package/dist/signer-CZ6K6FUc.mjs.map +1 -0
- package/dist/signer.d.mts +3 -0
- package/dist/signer.mjs +2 -0
- package/dist/storage-DOy0iLRE.mjs +870 -0
- package/dist/storage-DOy0iLRE.mjs.map +1 -0
- package/dist/storage.d.mts +4 -0
- package/dist/storage.mjs +4 -0
- package/dist/types-BzyADqnw.d.mts +19 -0
- package/dist/types-Dn24TPFs.d.mts +43 -0
- package/dist/util-6tfLQ9JF.mjs +73 -0
- package/dist/util-6tfLQ9JF.mjs.map +1 -0
- package/dist/wasm.d.mts +19 -0
- package/dist/wasm.mjs +237 -0
- package/dist/wasm.mjs.map +1 -0
- package/package.json +204 -0
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { i as hexToBytes, r as bytesToHex, t as assertHex32 } from "../util-6tfLQ9JF.mjs";
|
|
2
|
+
import { a as NostrError } from "../error-DZEs5OuZ.mjs";
|
|
3
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
4
|
+
//#region src/nips/nip77.ts
|
|
5
|
+
/**
|
|
6
|
+
* NIP-77: Negentropy Syncing.
|
|
7
|
+
* Transport-free V1 algorithm. Does not import relay or client.
|
|
8
|
+
*
|
|
9
|
+
* @see https://github.com/nostr-protocol/nips/blob/master/77.md
|
|
10
|
+
*/
|
|
11
|
+
const PROTOCOL_VERSION = 97;
|
|
12
|
+
const DEFAULT_FRAME_SIZE_LIMIT = 6e4;
|
|
13
|
+
const MAX_NEG_ROUNDS = 1024;
|
|
14
|
+
const ID_SIZE = 32;
|
|
15
|
+
const FINGERPRINT_SIZE = 16;
|
|
16
|
+
const INFINITY = Number.MAX_VALUE;
|
|
17
|
+
const BUCKETS = 16;
|
|
18
|
+
const ID_LIST_THRESHOLD = 32;
|
|
19
|
+
const Mode = {
|
|
20
|
+
Skip: 0,
|
|
21
|
+
Fingerprint: 1,
|
|
22
|
+
IdList: 2
|
|
23
|
+
};
|
|
24
|
+
var Nip77Error = class extends NostrError {
|
|
25
|
+
constructor(message, options) {
|
|
26
|
+
super(message, options);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var EncodedBuf = class EncodedBuf {
|
|
30
|
+
#raw;
|
|
31
|
+
length;
|
|
32
|
+
constructor(buffer) {
|
|
33
|
+
if (typeof buffer === "number") {
|
|
34
|
+
this.#raw = new Uint8Array(buffer);
|
|
35
|
+
this.length = 0;
|
|
36
|
+
} else if (buffer) {
|
|
37
|
+
this.#raw = new Uint8Array(buffer);
|
|
38
|
+
this.length = buffer.length;
|
|
39
|
+
} else {
|
|
40
|
+
this.#raw = /* @__PURE__ */ new Uint8Array(512);
|
|
41
|
+
this.length = 0;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
unwrap() {
|
|
45
|
+
return this.#raw.subarray(0, this.length);
|
|
46
|
+
}
|
|
47
|
+
get capacity() {
|
|
48
|
+
return this.#raw.byteLength;
|
|
49
|
+
}
|
|
50
|
+
extend(buf) {
|
|
51
|
+
const bytes = buf instanceof EncodedBuf ? buf.unwrap() : buf;
|
|
52
|
+
const targetSize = bytes.length + this.length;
|
|
53
|
+
if (this.capacity < targetSize) {
|
|
54
|
+
const old = this.#raw;
|
|
55
|
+
const next = new Uint8Array(Math.max(this.capacity * 2, targetSize));
|
|
56
|
+
next.set(old);
|
|
57
|
+
this.#raw = next;
|
|
58
|
+
}
|
|
59
|
+
this.#raw.set(bytes, this.length);
|
|
60
|
+
this.length += bytes.length;
|
|
61
|
+
}
|
|
62
|
+
shift() {
|
|
63
|
+
if (this.length === 0) throw new Nip77Error("parse ends prematurely");
|
|
64
|
+
const first = this.#raw[0];
|
|
65
|
+
this.#raw = this.#raw.subarray(1);
|
|
66
|
+
this.length -= 1;
|
|
67
|
+
return first;
|
|
68
|
+
}
|
|
69
|
+
shiftN(n) {
|
|
70
|
+
if (this.length < n) throw new Nip77Error("parse ends prematurely");
|
|
71
|
+
const head = this.#raw.subarray(0, n);
|
|
72
|
+
this.#raw = this.#raw.subarray(n);
|
|
73
|
+
this.length -= n;
|
|
74
|
+
return head;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
function decodeVarInt(buf) {
|
|
78
|
+
let res = 0;
|
|
79
|
+
for (;;) {
|
|
80
|
+
const byte = buf.shift();
|
|
81
|
+
res = res << 7 | byte & 127;
|
|
82
|
+
if ((byte & 128) === 0) break;
|
|
83
|
+
}
|
|
84
|
+
return res;
|
|
85
|
+
}
|
|
86
|
+
function encodeVarInt(n) {
|
|
87
|
+
if (n === 0) return new EncodedBuf(new Uint8Array([0]));
|
|
88
|
+
const digits = [];
|
|
89
|
+
let value = n;
|
|
90
|
+
while (value !== 0) {
|
|
91
|
+
digits.push(value & 127);
|
|
92
|
+
value >>>= 7;
|
|
93
|
+
}
|
|
94
|
+
digits.reverse();
|
|
95
|
+
for (let i = 0; i < digits.length - 1; i++) digits[i] |= 128;
|
|
96
|
+
return new EncodedBuf(new Uint8Array(digits));
|
|
97
|
+
}
|
|
98
|
+
function getBytes(buf, n) {
|
|
99
|
+
return buf.shiftN(n);
|
|
100
|
+
}
|
|
101
|
+
var Accumulator = class {
|
|
102
|
+
#buf;
|
|
103
|
+
constructor() {
|
|
104
|
+
this.#buf = new Uint8Array(ID_SIZE);
|
|
105
|
+
}
|
|
106
|
+
add(other) {
|
|
107
|
+
const view = new DataView(this.#buf.buffer, this.#buf.byteOffset, this.#buf.byteLength);
|
|
108
|
+
const otherView = new DataView(other.buffer, other.byteOffset, other.byteLength);
|
|
109
|
+
let carry = 0;
|
|
110
|
+
for (let i = 0; i < 8; i++) {
|
|
111
|
+
const offset = i * 4;
|
|
112
|
+
const next = view.getUint32(offset, true) + carry + otherView.getUint32(offset, true);
|
|
113
|
+
carry = next > 4294967295 ? 1 : 0;
|
|
114
|
+
view.setUint32(offset, next >>> 0, true);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
fingerprint(n) {
|
|
118
|
+
const input = new EncodedBuf();
|
|
119
|
+
input.extend(this.#buf);
|
|
120
|
+
input.extend(encodeVarInt(n));
|
|
121
|
+
return sha256(input.unwrap()).subarray(0, FINGERPRINT_SIZE);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
function compareBytes(a, b) {
|
|
125
|
+
const n = Math.min(a.byteLength, b.byteLength);
|
|
126
|
+
for (let i = 0; i < n; i++) {
|
|
127
|
+
if (a[i] < b[i]) return -1;
|
|
128
|
+
if (a[i] > b[i]) return 1;
|
|
129
|
+
}
|
|
130
|
+
if (a.byteLength > b.byteLength) return 1;
|
|
131
|
+
if (a.byteLength < b.byteLength) return -1;
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
function compareNegItems(a, b) {
|
|
135
|
+
if (a.timestamp !== b.timestamp) return a.timestamp - b.timestamp;
|
|
136
|
+
return compareBytes(a.id, b.id);
|
|
137
|
+
}
|
|
138
|
+
var NegentropyStorageVector = class {
|
|
139
|
+
#items = [];
|
|
140
|
+
#sealed = false;
|
|
141
|
+
insert(timestamp, id) {
|
|
142
|
+
if (this.#sealed) throw new Nip77Error("already sealed");
|
|
143
|
+
if (timestamp === INFINITY) throw new Nip77Error("timestamp is reserved infinity");
|
|
144
|
+
const idb = hexToBytes(assertHex32(id, "event id"));
|
|
145
|
+
this.#items.push({
|
|
146
|
+
timestamp,
|
|
147
|
+
id: idb
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
seal() {
|
|
151
|
+
if (this.#sealed) throw new Nip77Error("already sealed");
|
|
152
|
+
this.#sealed = true;
|
|
153
|
+
this.#items.sort(compareNegItems);
|
|
154
|
+
for (let i = 1; i < this.#items.length; i++) if (compareNegItems(this.#items[i - 1], this.#items[i]) === 0) throw new Nip77Error("duplicate item inserted");
|
|
155
|
+
}
|
|
156
|
+
size() {
|
|
157
|
+
this.#checkSealed();
|
|
158
|
+
return this.#items.length;
|
|
159
|
+
}
|
|
160
|
+
iterate(begin, end, cb) {
|
|
161
|
+
this.#checkSealed();
|
|
162
|
+
this.#checkBounds(begin, end);
|
|
163
|
+
for (let i = begin; i < end; i++) if (!cb(this.#items[i], i)) break;
|
|
164
|
+
}
|
|
165
|
+
findLowerBound(begin, end, bound) {
|
|
166
|
+
this.#checkSealed();
|
|
167
|
+
this.#checkBounds(begin, end);
|
|
168
|
+
let first = begin;
|
|
169
|
+
let count = end - begin;
|
|
170
|
+
while (count > 0) {
|
|
171
|
+
const step = Math.floor(count / 2);
|
|
172
|
+
const it = first + step;
|
|
173
|
+
if (compareNegItems(this.#items[it], bound) < 0) {
|
|
174
|
+
first = it + 1;
|
|
175
|
+
count -= step + 1;
|
|
176
|
+
} else count = step;
|
|
177
|
+
}
|
|
178
|
+
return first;
|
|
179
|
+
}
|
|
180
|
+
fingerprint(begin, end) {
|
|
181
|
+
const acc = new Accumulator();
|
|
182
|
+
this.iterate(begin, end, (item) => {
|
|
183
|
+
acc.add(item.id);
|
|
184
|
+
return true;
|
|
185
|
+
});
|
|
186
|
+
return acc.fingerprint(end - begin);
|
|
187
|
+
}
|
|
188
|
+
#checkSealed() {
|
|
189
|
+
if (!this.#sealed) throw new Nip77Error("not sealed");
|
|
190
|
+
}
|
|
191
|
+
#checkBounds(begin, end) {
|
|
192
|
+
if (begin > end || end > this.#items.length) throw new Nip77Error("bad range");
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
function storageFromItems(items) {
|
|
196
|
+
const storage = new NegentropyStorageVector();
|
|
197
|
+
const seen = /* @__PURE__ */ new Set();
|
|
198
|
+
for (const item of items) {
|
|
199
|
+
const id = item.id.toLowerCase();
|
|
200
|
+
if (seen.has(id)) continue;
|
|
201
|
+
seen.add(id);
|
|
202
|
+
storage.insert(item.created_at, id);
|
|
203
|
+
}
|
|
204
|
+
storage.seal();
|
|
205
|
+
return storage;
|
|
206
|
+
}
|
|
207
|
+
function storageFromEvents(events) {
|
|
208
|
+
return storageFromItems(events);
|
|
209
|
+
}
|
|
210
|
+
var Negentropy = class {
|
|
211
|
+
#storage;
|
|
212
|
+
#frameSizeLimit;
|
|
213
|
+
#initiator = false;
|
|
214
|
+
#lastTimestampIn = 0;
|
|
215
|
+
#lastTimestampOut = 0;
|
|
216
|
+
constructor(storage, frameSizeLimit = DEFAULT_FRAME_SIZE_LIMIT) {
|
|
217
|
+
if (frameSizeLimit !== 0 && frameSizeLimit < 4096) throw new Nip77Error("frameSizeLimit too small");
|
|
218
|
+
this.#storage = storage;
|
|
219
|
+
this.#frameSizeLimit = frameSizeLimit;
|
|
220
|
+
}
|
|
221
|
+
initiate() {
|
|
222
|
+
this.#initiator = true;
|
|
223
|
+
const output = new EncodedBuf();
|
|
224
|
+
output.extend(new Uint8Array([97]));
|
|
225
|
+
this.#splitRange(0, this.#storage.size(), this.#bound(INFINITY), output);
|
|
226
|
+
return bytesToHex(output.unwrap());
|
|
227
|
+
}
|
|
228
|
+
reconcile(queryMsg) {
|
|
229
|
+
const have = [];
|
|
230
|
+
const need = [];
|
|
231
|
+
const query = new EncodedBuf(hexToBytes(queryMsg));
|
|
232
|
+
this.#lastTimestampIn = 0;
|
|
233
|
+
this.#lastTimestampOut = 0;
|
|
234
|
+
const fullOutput = new EncodedBuf();
|
|
235
|
+
fullOutput.extend(new Uint8Array([97]));
|
|
236
|
+
const protocolVersion = query.shift();
|
|
237
|
+
if (protocolVersion < 96 || protocolVersion > 111) throw new Nip77Error("invalid negentropy protocol version byte");
|
|
238
|
+
if (protocolVersion !== 97) throw new Nip77Error(`unsupported negentropy protocol version requested: ${protocolVersion - 96}`);
|
|
239
|
+
const storageSize = this.#storage.size();
|
|
240
|
+
let prevBound = this.#bound(0);
|
|
241
|
+
let prevIndex = 0;
|
|
242
|
+
let skip = false;
|
|
243
|
+
while (query.length !== 0) {
|
|
244
|
+
const o = new EncodedBuf();
|
|
245
|
+
const doSkip = () => {
|
|
246
|
+
if (!skip) return;
|
|
247
|
+
skip = false;
|
|
248
|
+
o.extend(this.#encodeBound(prevBound));
|
|
249
|
+
o.extend(encodeVarInt(Mode.Skip));
|
|
250
|
+
};
|
|
251
|
+
const currBound = this.#decodeBound(query);
|
|
252
|
+
const mode = decodeVarInt(query);
|
|
253
|
+
const lower = prevIndex;
|
|
254
|
+
const upper = this.#storage.findLowerBound(prevIndex, storageSize, currBound);
|
|
255
|
+
if (mode === Mode.Skip) skip = true;
|
|
256
|
+
else if (mode === Mode.Fingerprint) {
|
|
257
|
+
if (compareBytes(getBytes(query, FINGERPRINT_SIZE), this.#storage.fingerprint(lower, upper)) !== 0) {
|
|
258
|
+
doSkip();
|
|
259
|
+
this.#splitRange(lower, upper, currBound, o);
|
|
260
|
+
} else skip = true;
|
|
261
|
+
} else if (mode === Mode.IdList) {
|
|
262
|
+
const numIds = decodeVarInt(query);
|
|
263
|
+
const theirElems = /* @__PURE__ */ new Map();
|
|
264
|
+
for (let i = 0; i < numIds; i++) {
|
|
265
|
+
const e = getBytes(query, ID_SIZE);
|
|
266
|
+
theirElems.set(bytesToHex(e), e);
|
|
267
|
+
}
|
|
268
|
+
if (this.#initiator) {
|
|
269
|
+
skip = true;
|
|
270
|
+
this.#storage.iterate(lower, upper, (item) => {
|
|
271
|
+
const id = bytesToHex(item.id);
|
|
272
|
+
if (!theirElems.has(id)) have.push(id);
|
|
273
|
+
else theirElems.delete(id);
|
|
274
|
+
return true;
|
|
275
|
+
});
|
|
276
|
+
for (const id of theirElems.keys()) need.push(id);
|
|
277
|
+
} else {
|
|
278
|
+
doSkip();
|
|
279
|
+
o.extend(this.#encodeBound(currBound));
|
|
280
|
+
o.extend(encodeVarInt(Mode.IdList));
|
|
281
|
+
const ourIds = [];
|
|
282
|
+
this.#storage.iterate(lower, upper, (item) => {
|
|
283
|
+
ourIds.push(item.id);
|
|
284
|
+
return true;
|
|
285
|
+
});
|
|
286
|
+
o.extend(encodeVarInt(ourIds.length));
|
|
287
|
+
for (const id of ourIds) o.extend(id);
|
|
288
|
+
}
|
|
289
|
+
} else throw new Nip77Error("unexpected mode");
|
|
290
|
+
if (this.#exceededFrameSizeLimit(fullOutput.length + o.length)) {
|
|
291
|
+
const remainingFingerprint = this.#storage.fingerprint(upper, storageSize);
|
|
292
|
+
fullOutput.extend(this.#encodeBound(this.#bound(INFINITY)));
|
|
293
|
+
fullOutput.extend(encodeVarInt(Mode.Fingerprint));
|
|
294
|
+
fullOutput.extend(remainingFingerprint);
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
fullOutput.extend(o);
|
|
298
|
+
prevIndex = upper;
|
|
299
|
+
prevBound = currBound;
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
have,
|
|
303
|
+
need,
|
|
304
|
+
nextMessage: fullOutput.length === 1 ? null : bytesToHex(fullOutput.unwrap())
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
#bound(timestamp, id) {
|
|
308
|
+
return {
|
|
309
|
+
timestamp,
|
|
310
|
+
id: id ?? /* @__PURE__ */ new Uint8Array(0)
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
#splitRange(lower, upper, upperBound, o) {
|
|
314
|
+
const numElems = upper - lower;
|
|
315
|
+
if (numElems < ID_LIST_THRESHOLD) {
|
|
316
|
+
o.extend(this.#encodeBound(upperBound));
|
|
317
|
+
o.extend(encodeVarInt(Mode.IdList));
|
|
318
|
+
o.extend(encodeVarInt(numElems));
|
|
319
|
+
this.#storage.iterate(lower, upper, (item) => {
|
|
320
|
+
o.extend(item.id);
|
|
321
|
+
return true;
|
|
322
|
+
});
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const itemsPerBucket = Math.floor(numElems / BUCKETS);
|
|
326
|
+
const bucketsWithExtra = numElems % BUCKETS;
|
|
327
|
+
let curr = lower;
|
|
328
|
+
for (let i = 0; i < BUCKETS; i++) {
|
|
329
|
+
const bucketSize = itemsPerBucket + (i < bucketsWithExtra ? 1 : 0);
|
|
330
|
+
const ourFingerprint = this.#storage.fingerprint(curr, curr + bucketSize);
|
|
331
|
+
curr += bucketSize;
|
|
332
|
+
let nextBound;
|
|
333
|
+
if (curr === upper) nextBound = upperBound;
|
|
334
|
+
else {
|
|
335
|
+
let prevItem;
|
|
336
|
+
let currItem;
|
|
337
|
+
this.#storage.iterate(curr - 1, curr + 1, (item, index) => {
|
|
338
|
+
if (index === curr - 1) prevItem = item;
|
|
339
|
+
else currItem = item;
|
|
340
|
+
return true;
|
|
341
|
+
});
|
|
342
|
+
nextBound = this.#minimalBound(prevItem, currItem);
|
|
343
|
+
}
|
|
344
|
+
o.extend(this.#encodeBound(nextBound));
|
|
345
|
+
o.extend(encodeVarInt(Mode.Fingerprint));
|
|
346
|
+
o.extend(ourFingerprint);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
#exceededFrameSizeLimit(n) {
|
|
350
|
+
if (this.#frameSizeLimit === 0) return false;
|
|
351
|
+
return n > this.#frameSizeLimit - 200;
|
|
352
|
+
}
|
|
353
|
+
#decodeTimestampIn(encoded) {
|
|
354
|
+
let timestamp = decodeVarInt(encoded);
|
|
355
|
+
timestamp = timestamp === 0 ? INFINITY : timestamp - 1;
|
|
356
|
+
if (this.#lastTimestampIn === INFINITY || timestamp === INFINITY) {
|
|
357
|
+
this.#lastTimestampIn = INFINITY;
|
|
358
|
+
return INFINITY;
|
|
359
|
+
}
|
|
360
|
+
timestamp += this.#lastTimestampIn;
|
|
361
|
+
this.#lastTimestampIn = timestamp;
|
|
362
|
+
return timestamp;
|
|
363
|
+
}
|
|
364
|
+
#decodeBound(encoded) {
|
|
365
|
+
const timestamp = this.#decodeTimestampIn(encoded);
|
|
366
|
+
const len = decodeVarInt(encoded);
|
|
367
|
+
if (len > ID_SIZE) throw new Nip77Error("bound key too long");
|
|
368
|
+
return {
|
|
369
|
+
timestamp,
|
|
370
|
+
id: getBytes(encoded, len)
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
#encodeTimestampOut(timestamp) {
|
|
374
|
+
if (timestamp === INFINITY) {
|
|
375
|
+
this.#lastTimestampOut = INFINITY;
|
|
376
|
+
return encodeVarInt(0);
|
|
377
|
+
}
|
|
378
|
+
const temp = timestamp;
|
|
379
|
+
timestamp -= this.#lastTimestampOut;
|
|
380
|
+
this.#lastTimestampOut = temp;
|
|
381
|
+
return encodeVarInt(timestamp + 1);
|
|
382
|
+
}
|
|
383
|
+
#encodeBound(key) {
|
|
384
|
+
const output = new EncodedBuf();
|
|
385
|
+
output.extend(this.#encodeTimestampOut(key.timestamp));
|
|
386
|
+
output.extend(encodeVarInt(key.id.length));
|
|
387
|
+
output.extend(key.id);
|
|
388
|
+
return output;
|
|
389
|
+
}
|
|
390
|
+
#minimalBound(prev, curr) {
|
|
391
|
+
if (curr.timestamp !== prev.timestamp) return this.#bound(curr.timestamp);
|
|
392
|
+
let shared = 0;
|
|
393
|
+
for (let i = 0; i < ID_SIZE; i++) {
|
|
394
|
+
if (curr.id[i] !== prev.id[i]) break;
|
|
395
|
+
shared += 1;
|
|
396
|
+
}
|
|
397
|
+
return this.#bound(curr.timestamp, curr.id.subarray(0, shared + 1));
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
/** Drive initiate/reconcile until nextMessage is null. Transport-free. */
|
|
401
|
+
async function runNegSession(opts) {
|
|
402
|
+
const neg = new Negentropy(opts.storage, opts.frameSizeLimit);
|
|
403
|
+
const have = /* @__PURE__ */ new Set();
|
|
404
|
+
const need = /* @__PURE__ */ new Set();
|
|
405
|
+
opts.openingSend(neg.initiate());
|
|
406
|
+
for (let round = 0; round < MAX_NEG_ROUNDS; round++) {
|
|
407
|
+
const out = neg.reconcile(await opts.next());
|
|
408
|
+
for (const id of out.have) have.add(id);
|
|
409
|
+
for (const id of out.need) need.add(id);
|
|
410
|
+
if (out.nextMessage === null) return {
|
|
411
|
+
have: [...have],
|
|
412
|
+
need: [...need]
|
|
413
|
+
};
|
|
414
|
+
opts.msgSend(out.nextMessage);
|
|
415
|
+
}
|
|
416
|
+
throw new Nip77Error("negentropy exceeded max rounds");
|
|
417
|
+
}
|
|
418
|
+
//#endregion
|
|
419
|
+
export { DEFAULT_FRAME_SIZE_LIMIT, MAX_NEG_ROUNDS, Negentropy, NegentropyStorageVector, Nip77Error, PROTOCOL_VERSION, runNegSession, storageFromEvents, storageFromItems };
|
|
420
|
+
|
|
421
|
+
//# sourceMappingURL=nip77.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nip77.mjs","names":["#raw","#buf","#sealed","#items","#checkSealed","#checkBounds","#storage","#frameSizeLimit","#initiator","#splitRange","#bound","#lastTimestampIn","#lastTimestampOut","#encodeBound","#decodeBound","#exceededFrameSizeLimit","#minimalBound","#decodeTimestampIn","#encodeTimestampOut"],"sources":["../../src/nips/nip77.ts"],"sourcesContent":["/**\n * NIP-77: Negentropy Syncing.\n * Transport-free V1 algorithm. Does not import relay or client.\n *\n * @see https://github.com/nostr-protocol/nips/blob/master/77.md\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { NostrError } from \"../core/error.ts\";\nimport type { Event } from \"../core/event.ts\";\nimport { assertHex32, bytesToHex, hexToBytes } from \"../core/util.ts\";\n\nexport const PROTOCOL_VERSION = 0x61;\nexport const DEFAULT_FRAME_SIZE_LIMIT = 60_000;\nexport const MAX_NEG_ROUNDS = 1024;\n\nconst ID_SIZE = 32;\nconst FINGERPRINT_SIZE = 16;\nconst INFINITY = Number.MAX_VALUE;\nconst BUCKETS = 16;\nconst ID_LIST_THRESHOLD = BUCKETS * 2;\n\nconst Mode = {\n Skip: 0,\n Fingerprint: 1,\n IdList: 2,\n} as const;\n\nexport class Nip77Error extends NostrError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n }\n}\n\nexport type NegItem = {\n timestamp: number;\n id: Uint8Array;\n};\n\nexport type ReconcileOutcome = {\n /** Event ids the local side holds that the peer does not. */\n have: string[];\n /** Event ids the peer holds that the local side does not. */\n need: string[];\n /** Next NEG-MSG hex, or null when the session converged. */\n nextMessage: string | null;\n};\n\nclass EncodedBuf {\n #raw: Uint8Array;\n length: number;\n\n constructor(buffer?: Uint8Array | number) {\n if (typeof buffer === \"number\") {\n this.#raw = new Uint8Array(buffer);\n this.length = 0;\n } else if (buffer) {\n this.#raw = new Uint8Array(buffer);\n this.length = buffer.length;\n } else {\n this.#raw = new Uint8Array(512);\n this.length = 0;\n }\n }\n\n unwrap(): Uint8Array {\n return this.#raw.subarray(0, this.length);\n }\n\n get capacity(): number {\n return this.#raw.byteLength;\n }\n\n extend(buf: Uint8Array | EncodedBuf): void {\n const bytes = buf instanceof EncodedBuf ? buf.unwrap() : buf;\n const targetSize = bytes.length + this.length;\n if (this.capacity < targetSize) {\n const old = this.#raw;\n const next = new Uint8Array(Math.max(this.capacity * 2, targetSize));\n next.set(old);\n this.#raw = next;\n }\n this.#raw.set(bytes, this.length);\n this.length += bytes.length;\n }\n\n shift(): number {\n if (this.length === 0) throw new Nip77Error(\"parse ends prematurely\");\n const first = this.#raw[0]!;\n this.#raw = this.#raw.subarray(1);\n this.length -= 1;\n return first;\n }\n\n shiftN(n: number): Uint8Array {\n if (this.length < n) throw new Nip77Error(\"parse ends prematurely\");\n const head = this.#raw.subarray(0, n);\n this.#raw = this.#raw.subarray(n);\n this.length -= n;\n return head;\n }\n}\n\nfunction decodeVarInt(buf: EncodedBuf): number {\n let res = 0;\n for (;;) {\n const byte = buf.shift();\n res = (res << 7) | (byte & 127);\n if ((byte & 128) === 0) break;\n }\n return res;\n}\n\nfunction encodeVarInt(n: number): EncodedBuf {\n if (n === 0) return new EncodedBuf(new Uint8Array([0]));\n const digits: number[] = [];\n let value = n;\n while (value !== 0) {\n digits.push(value & 127);\n value >>>= 7;\n }\n digits.reverse();\n for (let i = 0; i < digits.length - 1; i++) digits[i] |= 128;\n return new EncodedBuf(new Uint8Array(digits));\n}\n\nfunction getBytes(buf: EncodedBuf, n: number): Uint8Array {\n return buf.shiftN(n);\n}\n\nclass Accumulator {\n #buf: Uint8Array;\n\n constructor() {\n this.#buf = new Uint8Array(ID_SIZE);\n }\n\n add(other: Uint8Array): void {\n const view = new DataView(this.#buf.buffer, this.#buf.byteOffset, this.#buf.byteLength);\n const otherView = new DataView(other.buffer, other.byteOffset, other.byteLength);\n let carry = 0;\n for (let i = 0; i < 8; i++) {\n const offset = i * 4;\n const next = view.getUint32(offset, true) + carry + otherView.getUint32(offset, true);\n carry = next > 0xffffffff ? 1 : 0;\n view.setUint32(offset, next >>> 0, true);\n }\n }\n\n fingerprint(n: number): Uint8Array {\n const input = new EncodedBuf();\n input.extend(this.#buf);\n input.extend(encodeVarInt(n));\n return sha256(input.unwrap()).subarray(0, FINGERPRINT_SIZE);\n }\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n const n = Math.min(a.byteLength, b.byteLength);\n for (let i = 0; i < n; i++) {\n if (a[i]! < b[i]!) return -1;\n if (a[i]! > b[i]!) return 1;\n }\n if (a.byteLength > b.byteLength) return 1;\n if (a.byteLength < b.byteLength) return -1;\n return 0;\n}\n\nfunction compareNegItems(a: NegItem, b: NegItem): number {\n if (a.timestamp !== b.timestamp) return a.timestamp - b.timestamp;\n return compareBytes(a.id, b.id);\n}\n\nexport class NegentropyStorageVector {\n #items: NegItem[] = [];\n #sealed = false;\n\n insert(timestamp: number, id: string): void {\n if (this.#sealed) throw new Nip77Error(\"already sealed\");\n if (timestamp === INFINITY) throw new Nip77Error(\"timestamp is reserved infinity\");\n const idb = hexToBytes(assertHex32(id, \"event id\"));\n this.#items.push({ timestamp, id: idb });\n }\n\n seal(): void {\n if (this.#sealed) throw new Nip77Error(\"already sealed\");\n this.#sealed = true;\n this.#items.sort(compareNegItems);\n for (let i = 1; i < this.#items.length; i++) {\n if (compareNegItems(this.#items[i - 1]!, this.#items[i]!) === 0) {\n throw new Nip77Error(\"duplicate item inserted\");\n }\n }\n }\n\n size(): number {\n this.#checkSealed();\n return this.#items.length;\n }\n\n iterate(begin: number, end: number, cb: (item: NegItem, i: number) => boolean): void {\n this.#checkSealed();\n this.#checkBounds(begin, end);\n for (let i = begin; i < end; i++) {\n if (!cb(this.#items[i]!, i)) break;\n }\n }\n\n findLowerBound(begin: number, end: number, bound: NegItem): number {\n this.#checkSealed();\n this.#checkBounds(begin, end);\n let first = begin;\n let count = end - begin;\n while (count > 0) {\n const step = Math.floor(count / 2);\n const it = first + step;\n if (compareNegItems(this.#items[it]!, bound) < 0) {\n first = it + 1;\n count -= step + 1;\n } else {\n count = step;\n }\n }\n return first;\n }\n\n fingerprint(begin: number, end: number): Uint8Array {\n const acc = new Accumulator();\n this.iterate(begin, end, (item) => {\n acc.add(item.id);\n return true;\n });\n return acc.fingerprint(end - begin);\n }\n\n #checkSealed(): void {\n if (!this.#sealed) throw new Nip77Error(\"not sealed\");\n }\n\n #checkBounds(begin: number, end: number): void {\n if (begin > end || end > this.#items.length) throw new Nip77Error(\"bad range\");\n }\n}\n\nexport function storageFromItems(\n items: readonly { id: string; created_at: number }[],\n): NegentropyStorageVector {\n const storage = new NegentropyStorageVector();\n const seen = new Set<string>();\n for (const item of items) {\n const id = item.id.toLowerCase();\n if (seen.has(id)) continue;\n seen.add(id);\n storage.insert(item.created_at, id);\n }\n storage.seal();\n return storage;\n}\n\nexport function storageFromEvents(\n events: readonly Pick<Event, \"id\" | \"created_at\">[],\n): NegentropyStorageVector {\n return storageFromItems(events);\n}\n\ntype Bound = { timestamp: number; id: Uint8Array };\n\nexport class Negentropy {\n readonly #storage: NegentropyStorageVector;\n readonly #frameSizeLimit: number;\n #initiator = false;\n #lastTimestampIn = 0;\n #lastTimestampOut = 0;\n\n constructor(storage: NegentropyStorageVector, frameSizeLimit = DEFAULT_FRAME_SIZE_LIMIT) {\n if (frameSizeLimit !== 0 && frameSizeLimit < 4096) {\n throw new Nip77Error(\"frameSizeLimit too small\");\n }\n this.#storage = storage;\n this.#frameSizeLimit = frameSizeLimit;\n }\n\n initiate(): string {\n this.#initiator = true;\n const output = new EncodedBuf();\n output.extend(new Uint8Array([PROTOCOL_VERSION]));\n this.#splitRange(0, this.#storage.size(), this.#bound(INFINITY), output);\n return bytesToHex(output.unwrap());\n }\n\n reconcile(queryMsg: string): ReconcileOutcome {\n const have: string[] = [];\n const need: string[] = [];\n const query = new EncodedBuf(hexToBytes(queryMsg));\n\n this.#lastTimestampIn = 0;\n this.#lastTimestampOut = 0;\n\n const fullOutput = new EncodedBuf();\n fullOutput.extend(new Uint8Array([PROTOCOL_VERSION]));\n\n const protocolVersion = query.shift();\n if (protocolVersion < 0x60 || protocolVersion > 0x6f) {\n throw new Nip77Error(\"invalid negentropy protocol version byte\");\n }\n if (protocolVersion !== PROTOCOL_VERSION) {\n throw new Nip77Error(\n `unsupported negentropy protocol version requested: ${protocolVersion - 0x60}`,\n );\n }\n\n const storageSize = this.#storage.size();\n let prevBound = this.#bound(0);\n let prevIndex = 0;\n let skip = false;\n\n while (query.length !== 0) {\n const o = new EncodedBuf();\n const doSkip = (): void => {\n if (!skip) return;\n skip = false;\n o.extend(this.#encodeBound(prevBound));\n o.extend(encodeVarInt(Mode.Skip));\n };\n\n const currBound = this.#decodeBound(query);\n const mode = decodeVarInt(query);\n const lower = prevIndex;\n const upper = this.#storage.findLowerBound(prevIndex, storageSize, currBound);\n\n if (mode === Mode.Skip) {\n skip = true;\n } else if (mode === Mode.Fingerprint) {\n const theirFingerprint = getBytes(query, FINGERPRINT_SIZE);\n const ourFingerprint = this.#storage.fingerprint(lower, upper);\n if (compareBytes(theirFingerprint, ourFingerprint) !== 0) {\n doSkip();\n this.#splitRange(lower, upper, currBound, o);\n } else {\n skip = true;\n }\n } else if (mode === Mode.IdList) {\n const numIds = decodeVarInt(query);\n const theirElems = new Map<string, Uint8Array>();\n for (let i = 0; i < numIds; i++) {\n const e = getBytes(query, ID_SIZE);\n theirElems.set(bytesToHex(e), e);\n }\n\n if (this.#initiator) {\n skip = true;\n this.#storage.iterate(lower, upper, (item) => {\n const id = bytesToHex(item.id);\n if (!theirElems.has(id)) have.push(id);\n else theirElems.delete(id);\n return true;\n });\n for (const id of theirElems.keys()) need.push(id);\n } else {\n doSkip();\n o.extend(this.#encodeBound(currBound));\n o.extend(encodeVarInt(Mode.IdList));\n const ourIds: Uint8Array[] = [];\n this.#storage.iterate(lower, upper, (item) => {\n ourIds.push(item.id);\n return true;\n });\n o.extend(encodeVarInt(ourIds.length));\n for (const id of ourIds) o.extend(id);\n }\n } else {\n throw new Nip77Error(\"unexpected mode\");\n }\n\n if (this.#exceededFrameSizeLimit(fullOutput.length + o.length)) {\n const remainingFingerprint = this.#storage.fingerprint(upper, storageSize);\n fullOutput.extend(this.#encodeBound(this.#bound(INFINITY)));\n fullOutput.extend(encodeVarInt(Mode.Fingerprint));\n fullOutput.extend(remainingFingerprint);\n break;\n }\n fullOutput.extend(o);\n prevIndex = upper;\n prevBound = currBound;\n }\n\n return {\n have,\n need,\n nextMessage: fullOutput.length === 1 ? null : bytesToHex(fullOutput.unwrap()),\n };\n }\n\n #bound(timestamp: number, id?: Uint8Array): Bound {\n return { timestamp, id: id ?? new Uint8Array(0) };\n }\n\n #splitRange(lower: number, upper: number, upperBound: Bound, o: EncodedBuf): void {\n const numElems = upper - lower;\n if (numElems < ID_LIST_THRESHOLD) {\n o.extend(this.#encodeBound(upperBound));\n o.extend(encodeVarInt(Mode.IdList));\n o.extend(encodeVarInt(numElems));\n this.#storage.iterate(lower, upper, (item) => {\n o.extend(item.id);\n return true;\n });\n return;\n }\n\n const itemsPerBucket = Math.floor(numElems / BUCKETS);\n const bucketsWithExtra = numElems % BUCKETS;\n let curr = lower;\n for (let i = 0; i < BUCKETS; i++) {\n const bucketSize = itemsPerBucket + (i < bucketsWithExtra ? 1 : 0);\n const ourFingerprint = this.#storage.fingerprint(curr, curr + bucketSize);\n curr += bucketSize;\n let nextBound: Bound;\n if (curr === upper) {\n nextBound = upperBound;\n } else {\n let prevItem: NegItem | undefined;\n let currItem: NegItem | undefined;\n this.#storage.iterate(curr - 1, curr + 1, (item, index) => {\n if (index === curr - 1) prevItem = item;\n else currItem = item;\n return true;\n });\n nextBound = this.#minimalBound(prevItem!, currItem!);\n }\n o.extend(this.#encodeBound(nextBound));\n o.extend(encodeVarInt(Mode.Fingerprint));\n o.extend(ourFingerprint);\n }\n }\n\n #exceededFrameSizeLimit(n: number): boolean {\n if (this.#frameSizeLimit === 0) return false;\n return n > this.#frameSizeLimit - 200;\n }\n\n #decodeTimestampIn(encoded: EncodedBuf): number {\n let timestamp = decodeVarInt(encoded);\n timestamp = timestamp === 0 ? INFINITY : timestamp - 1;\n if (this.#lastTimestampIn === INFINITY || timestamp === INFINITY) {\n this.#lastTimestampIn = INFINITY;\n return INFINITY;\n }\n timestamp += this.#lastTimestampIn;\n this.#lastTimestampIn = timestamp;\n return timestamp;\n }\n\n #decodeBound(encoded: EncodedBuf): Bound {\n const timestamp = this.#decodeTimestampIn(encoded);\n const len = decodeVarInt(encoded);\n if (len > ID_SIZE) throw new Nip77Error(\"bound key too long\");\n return { timestamp, id: getBytes(encoded, len) };\n }\n\n #encodeTimestampOut(timestamp: number): EncodedBuf {\n if (timestamp === INFINITY) {\n this.#lastTimestampOut = INFINITY;\n return encodeVarInt(0);\n }\n const temp = timestamp;\n timestamp -= this.#lastTimestampOut;\n this.#lastTimestampOut = temp;\n return encodeVarInt(timestamp + 1);\n }\n\n #encodeBound(key: Bound): EncodedBuf {\n const output = new EncodedBuf();\n output.extend(this.#encodeTimestampOut(key.timestamp));\n output.extend(encodeVarInt(key.id.length));\n output.extend(key.id);\n return output;\n }\n\n #minimalBound(prev: NegItem, curr: NegItem): Bound {\n if (curr.timestamp !== prev.timestamp) return this.#bound(curr.timestamp);\n let shared = 0;\n for (let i = 0; i < ID_SIZE; i++) {\n if (curr.id[i] !== prev.id[i]) break;\n shared += 1;\n }\n return this.#bound(curr.timestamp, curr.id.subarray(0, shared + 1));\n }\n}\n\n/** Drive initiate/reconcile until nextMessage is null. Transport-free. */\nexport async function runNegSession(opts: {\n storage: NegentropyStorageVector;\n frameSizeLimit?: number;\n openingSend: (hex: string) => void;\n msgSend: (hex: string) => void;\n next: () => Promise<string>;\n}): Promise<{ have: string[]; need: string[] }> {\n const neg = new Negentropy(opts.storage, opts.frameSizeLimit);\n const have = new Set<string>();\n const need = new Set<string>();\n opts.openingSend(neg.initiate());\n for (let round = 0; round < MAX_NEG_ROUNDS; round++) {\n const out = neg.reconcile(await opts.next());\n for (const id of out.have) have.add(id);\n for (const id of out.need) need.add(id);\n if (out.nextMessage === null) return { have: [...have], need: [...need] };\n opts.msgSend(out.nextMessage);\n }\n throw new Nip77Error(\"negentropy exceeded max rounds\");\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,mBAAmB;AAChC,MAAa,2BAA2B;AACxC,MAAa,iBAAiB;AAE9B,MAAM,UAAU;AAChB,MAAM,mBAAmB;AACzB,MAAM,WAAW,OAAO;AACxB,MAAM,UAAU;AAChB,MAAM,oBAAoB;AAE1B,MAAM,OAAO;CACX,MAAM;CACN,aAAa;CACb,QAAQ;AACV;AAEA,IAAa,aAAb,cAAgC,WAAW;CACzC,YAAY,SAAiB,SAAwB;EACnD,MAAM,SAAS,OAAO;CACxB;AACF;AAgBA,IAAM,aAAN,MAAM,WAAW;CACf;CACA;CAEA,YAAY,QAA8B;EACxC,IAAI,OAAO,WAAW,UAAU;GAC9B,KAAKA,OAAO,IAAI,WAAW,MAAM;GACjC,KAAK,SAAS;EAChB,OAAO,IAAI,QAAQ;GACjB,KAAKA,OAAO,IAAI,WAAW,MAAM;GACjC,KAAK,SAAS,OAAO;EACvB,OAAO;GACL,KAAKA,uBAAO,IAAI,WAAW,GAAG;GAC9B,KAAK,SAAS;EAChB;CACF;CAEA,SAAqB;EACnB,OAAO,KAAKA,KAAK,SAAS,GAAG,KAAK,MAAM;CA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AAI,QAAQ,GAAG,QAAQ,gBAAgB,SAAS;EACnD,MAAM,MAAM,IAAI,UAAU,MAAM,KAAK,KAAK,CAAC;EAC3C,KAAK,MAAM,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;EACtC,KAAK,MAAM,MAAM,IAAI,MAAM,KAAK,IAAI,EAAE;EACtC,IAAI,IAAI,gBAAgB,MAAM,OAAO;GAAE,MAAM,CAAC,GAAG,IAAI;GAAG,MAAM,CAAC,GAAG,IAAI;EAAE;EACxE,KAAK,QAAQ,IAAI,WAAW;CAC9B;CACA,MAAM,IAAI,WAAW,gCAAgC;AACvD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { a as NostrError } from "../error-WEFS-R-4.mjs";
|
|
2
|
+
import { t as ManualFetch } from "../http-6vevbBlu.mjs";
|
|
3
|
+
//#region src/nips/nip96.d.ts
|
|
4
|
+
type Nip96Fetch = ManualFetch;
|
|
5
|
+
type Nip96ServerInfo = {
|
|
6
|
+
api_url: string;
|
|
7
|
+
download_url?: string;
|
|
8
|
+
delegated_to_url?: string;
|
|
9
|
+
content_types?: string[];
|
|
10
|
+
};
|
|
11
|
+
type Nip96UploadResult = {
|
|
12
|
+
url: string;
|
|
13
|
+
tags: string[][];
|
|
14
|
+
};
|
|
15
|
+
declare class Nip96Error extends NostrError {}
|
|
16
|
+
/** Parse `{ status, nip94_event.tags }` and require a `url` tag. */
|
|
17
|
+
declare function parseNip96UploadResponse(json: unknown): Nip96UploadResult;
|
|
18
|
+
/** GET `${service}/.well-known/nostr/nip96.json` with `redirect: "manual"`. */
|
|
19
|
+
declare function fetchNip96Info(serviceUrl: string, opts?: {
|
|
20
|
+
fetch?: Nip96Fetch;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}): Promise<Nip96ServerInfo>;
|
|
23
|
+
/** POST `apiUrl` as multipart `file`. `authorization` is a prebuilt NIP-98 header. */
|
|
24
|
+
declare function uploadNip96(apiUrl: string, file: Blob, authorization: string, opts?: {
|
|
25
|
+
fetch?: Nip96Fetch;
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
extraFields?: Record<string, string>;
|
|
28
|
+
}): Promise<Nip96UploadResult>;
|
|
29
|
+
//#endregion
|
|
30
|
+
export { Nip96Error, Nip96Fetch, Nip96ServerInfo, Nip96UploadResult, fetchNip96Info, parseNip96UploadResponse, uploadNip96 };
|
|
31
|
+
//# sourceMappingURL=nip96.d.mts.map
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { a as NostrError } from "../error-DZEs5OuZ.mjs";
|
|
2
|
+
import { n as requireGlobalFetch, t as fetchManual } from "../http-D2rhokZo.mjs";
|
|
3
|
+
//#region src/nips/nip96.ts
|
|
4
|
+
/**
|
|
5
|
+
* NIP-96: HTTP file storage (unrecommended; NIP-B7 preferred).
|
|
6
|
+
* Authorization is a prebuilt NIP-98 header — this module does not import nip98.
|
|
7
|
+
*
|
|
8
|
+
* @see https://github.com/nostr-protocol/nips/blob/master/96.md
|
|
9
|
+
*/
|
|
10
|
+
const WELL_KNOWN_PATH = "/.well-known/nostr/nip96.json";
|
|
11
|
+
var Nip96Error = class extends NostrError {};
|
|
12
|
+
function serverInfoUrl(serviceUrl) {
|
|
13
|
+
return `${serviceUrl.replace(/\/+$/, "")}${WELL_KNOWN_PATH}`;
|
|
14
|
+
}
|
|
15
|
+
function errorMessageFromBody(json) {
|
|
16
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) return void 0;
|
|
17
|
+
const message = json.message;
|
|
18
|
+
if (typeof message !== "string") return void 0;
|
|
19
|
+
return message.trim() || void 0;
|
|
20
|
+
}
|
|
21
|
+
/** Non-OK: prefer NIP-96 JSON `message`; never require a `url` tag. */
|
|
22
|
+
async function throwHttpError(prefix, res) {
|
|
23
|
+
let detail;
|
|
24
|
+
try {
|
|
25
|
+
detail = errorMessageFromBody(await res.json());
|
|
26
|
+
} catch {}
|
|
27
|
+
throw new Nip96Error(detail ? `${prefix} HTTP ${res.status}: ${detail}` : `${prefix} HTTP ${res.status}`);
|
|
28
|
+
}
|
|
29
|
+
function parseNip96ServerInfo(json) {
|
|
30
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) throw new Nip96Error("NIP-96 server info must be a JSON object");
|
|
31
|
+
const raw = json;
|
|
32
|
+
if (typeof raw.api_url !== "string") throw new Nip96Error("missing api_url");
|
|
33
|
+
const info = { api_url: raw.api_url };
|
|
34
|
+
if (typeof raw.download_url === "string") info.download_url = raw.download_url;
|
|
35
|
+
if (typeof raw.delegated_to_url === "string") info.delegated_to_url = raw.delegated_to_url;
|
|
36
|
+
if (Array.isArray(raw.content_types) && raw.content_types.every((t) => typeof t === "string")) info.content_types = [...raw.content_types];
|
|
37
|
+
return info;
|
|
38
|
+
}
|
|
39
|
+
/** Parse `{ status, nip94_event.tags }` and require a `url` tag. */
|
|
40
|
+
function parseNip96UploadResponse(json) {
|
|
41
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) throw new Nip96Error("NIP-96 upload response must be a JSON object");
|
|
42
|
+
const event = json.nip94_event;
|
|
43
|
+
const rawTags = event && typeof event === "object" && !Array.isArray(event) ? event.tags : void 0;
|
|
44
|
+
if (!Array.isArray(rawTags)) throw new Nip96Error("upload response without url");
|
|
45
|
+
const tags = [];
|
|
46
|
+
for (const tag of rawTags) {
|
|
47
|
+
if (!Array.isArray(tag) || tag.some((item) => typeof item !== "string")) throw new Nip96Error("invalid nip94_event.tags");
|
|
48
|
+
tags.push([...tag]);
|
|
49
|
+
}
|
|
50
|
+
const url = tags.find((tag) => tag[0] === "url")?.[1];
|
|
51
|
+
if (!url) throw new Nip96Error("upload response without url");
|
|
52
|
+
return {
|
|
53
|
+
url,
|
|
54
|
+
tags
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** GET `${service}/.well-known/nostr/nip96.json` with `redirect: "manual"`. */
|
|
58
|
+
async function fetchNip96Info(serviceUrl, opts) {
|
|
59
|
+
const url = serverInfoUrl(serviceUrl);
|
|
60
|
+
const fetchImpl = opts?.fetch ?? requireGlobalFetch(() => new Nip96Error("no fetch implementation available; pass opts.fetch"));
|
|
61
|
+
const res = await fetchManual(fetchImpl, url, { signal: opts?.signal }, (cause) => new Nip96Error(`NIP-96 server info request failed: ${url}`, { cause: cause instanceof Error ? cause : void 0 }));
|
|
62
|
+
if (!res.ok) await throwHttpError("NIP-96 server info", res);
|
|
63
|
+
let json;
|
|
64
|
+
try {
|
|
65
|
+
json = await res.json();
|
|
66
|
+
} catch (cause) {
|
|
67
|
+
throw new Nip96Error("invalid NIP-96 server info JSON", { cause: cause instanceof Error ? cause : void 0 });
|
|
68
|
+
}
|
|
69
|
+
return parseNip96ServerInfo(json);
|
|
70
|
+
}
|
|
71
|
+
/** POST `apiUrl` as multipart `file`. `authorization` is a prebuilt NIP-98 header. */
|
|
72
|
+
async function uploadNip96(apiUrl, file, authorization, opts) {
|
|
73
|
+
const fetchImpl = opts?.fetch ?? requireGlobalFetch(() => new Nip96Error("no fetch implementation available; pass opts.fetch"));
|
|
74
|
+
const body = new FormData();
|
|
75
|
+
body.append("file", file);
|
|
76
|
+
if (opts?.extraFields) for (const [name, value] of Object.entries(opts.extraFields)) body.append(name, value);
|
|
77
|
+
const res = await fetchManual(fetchImpl, apiUrl, {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { Authorization: authorization },
|
|
80
|
+
body,
|
|
81
|
+
signal: opts?.signal
|
|
82
|
+
}, (cause) => new Nip96Error(`NIP-96 upload request failed: ${apiUrl}`, { cause: cause instanceof Error ? cause : void 0 }));
|
|
83
|
+
if (!res.ok) await throwHttpError("NIP-96 upload", res);
|
|
84
|
+
let json;
|
|
85
|
+
try {
|
|
86
|
+
json = await res.json();
|
|
87
|
+
} catch (cause) {
|
|
88
|
+
throw new Nip96Error("invalid NIP-96 upload response JSON", { cause: cause instanceof Error ? cause : void 0 });
|
|
89
|
+
}
|
|
90
|
+
return parseNip96UploadResponse(json);
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
export { Nip96Error, fetchNip96Info, parseNip96UploadResponse, uploadNip96 };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=nip96.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nip96.mjs","names":[],"sources":["../../src/nips/nip96.ts"],"sourcesContent":["/**\n * NIP-96: HTTP file storage (unrecommended; NIP-B7 preferred).\n * Authorization is a prebuilt NIP-98 header — this module does not import nip98.\n *\n * @see https://github.com/nostr-protocol/nips/blob/master/96.md\n */\nimport { NostrError } from \"../core/error.ts\";\nimport { fetchManual, requireGlobalFetch, type ManualFetch } from \"./http.ts\";\n\nconst WELL_KNOWN_PATH = \"/.well-known/nostr/nip96.json\";\n\nexport type Nip96Fetch = ManualFetch;\n\nexport type Nip96ServerInfo = {\n api_url: string;\n download_url?: string;\n delegated_to_url?: string;\n content_types?: string[];\n};\n\nexport type Nip96UploadResult = {\n url: string;\n tags: string[][];\n};\n\nexport class Nip96Error extends NostrError {}\n\nfunction serverInfoUrl(serviceUrl: string): string {\n return `${serviceUrl.replace(/\\/+$/, \"\")}${WELL_KNOWN_PATH}`;\n}\n\nfunction errorMessageFromBody(json: unknown): string | undefined {\n if (!json || typeof json !== \"object\" || Array.isArray(json)) return undefined;\n const message = (json as { message?: unknown }).message;\n if (typeof message !== \"string\") return undefined;\n const text = message.trim();\n return text || undefined;\n}\n\n/** Non-OK: prefer NIP-96 JSON `message`; never require a `url` tag. */\nasync function throwHttpError(\n prefix: string,\n res: Awaited<ReturnType<Nip96Fetch>>,\n): Promise<never> {\n let detail: string | undefined;\n try {\n detail = errorMessageFromBody(await res.json());\n } catch {\n // body is optional on error\n }\n throw new Nip96Error(\n detail ? `${prefix} HTTP ${res.status}: ${detail}` : `${prefix} HTTP ${res.status}`,\n );\n}\n\nfunction parseNip96ServerInfo(json: unknown): Nip96ServerInfo {\n if (!json || typeof json !== \"object\" || Array.isArray(json)) {\n throw new Nip96Error(\"NIP-96 server info must be a JSON object\");\n }\n const raw = json as Record<string, unknown>;\n if (typeof raw.api_url !== \"string\") {\n throw new Nip96Error(\"missing api_url\");\n }\n\n const info: Nip96ServerInfo = { api_url: raw.api_url };\n if (typeof raw.download_url === \"string\") info.download_url = raw.download_url;\n if (typeof raw.delegated_to_url === \"string\") info.delegated_to_url = raw.delegated_to_url;\n if (Array.isArray(raw.content_types) && raw.content_types.every((t) => typeof t === \"string\")) {\n info.content_types = [...raw.content_types];\n }\n return info;\n}\n\n/** Parse `{ status, nip94_event.tags }` and require a `url` tag. */\nexport function parseNip96UploadResponse(json: unknown): Nip96UploadResult {\n if (!json || typeof json !== \"object\" || Array.isArray(json)) {\n throw new Nip96Error(\"NIP-96 upload response must be a JSON object\");\n }\n const event = (json as { nip94_event?: unknown }).nip94_event;\n const rawTags =\n event && typeof event === \"object\" && !Array.isArray(event)\n ? (event as { tags?: unknown }).tags\n : undefined;\n if (!Array.isArray(rawTags)) {\n throw new Nip96Error(\"upload response without url\");\n }\n\n const tags: string[][] = [];\n for (const tag of rawTags) {\n if (!Array.isArray(tag) || tag.some((item) => typeof item !== \"string\")) {\n throw new Nip96Error(\"invalid nip94_event.tags\");\n }\n tags.push([...tag]);\n }\n\n const url = tags.find((tag) => tag[0] === \"url\")?.[1];\n if (!url) {\n throw new Nip96Error(\"upload response without url\");\n }\n return { url, tags };\n}\n\n/** GET `${service}/.well-known/nostr/nip96.json` with `redirect: \"manual\"`. */\nexport async function fetchNip96Info(\n serviceUrl: string,\n opts?: { fetch?: Nip96Fetch; signal?: AbortSignal },\n): Promise<Nip96ServerInfo> {\n const url = serverInfoUrl(serviceUrl);\n const fetchImpl =\n opts?.fetch ??\n requireGlobalFetch(() => new Nip96Error(\"no fetch implementation available; pass opts.fetch\"));\n\n const res = await fetchManual(\n fetchImpl,\n url,\n { signal: opts?.signal },\n (cause) =>\n new Nip96Error(`NIP-96 server info request failed: ${url}`, {\n cause: cause instanceof Error ? cause : undefined,\n }),\n );\n if (!res.ok) {\n await throwHttpError(\"NIP-96 server info\", res);\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (cause) {\n throw new Nip96Error(\"invalid NIP-96 server info JSON\", {\n cause: cause instanceof Error ? cause : undefined,\n });\n }\n return parseNip96ServerInfo(json);\n}\n\n/** POST `apiUrl` as multipart `file`. `authorization` is a prebuilt NIP-98 header. */\nexport async function uploadNip96(\n apiUrl: string,\n file: Blob,\n authorization: string,\n opts?: { fetch?: Nip96Fetch; signal?: AbortSignal; extraFields?: Record<string, string> },\n): Promise<Nip96UploadResult> {\n const fetchImpl =\n opts?.fetch ??\n requireGlobalFetch(() => new Nip96Error(\"no fetch implementation available; pass opts.fetch\"));\n const body = new FormData();\n body.append(\"file\", file);\n if (opts?.extraFields) {\n for (const [name, value] of Object.entries(opts.extraFields)) {\n body.append(name, value);\n }\n }\n\n const res = await fetchManual(\n fetchImpl,\n apiUrl,\n {\n method: \"POST\",\n headers: { Authorization: authorization },\n body,\n signal: opts?.signal,\n },\n (cause) =>\n new Nip96Error(`NIP-96 upload request failed: ${apiUrl}`, {\n cause: cause instanceof Error ? cause : undefined,\n }),\n );\n if (!res.ok) {\n await throwHttpError(\"NIP-96 upload\", res);\n }\n\n let json: unknown;\n try {\n json = await res.json();\n } catch (cause) {\n throw new Nip96Error(\"invalid NIP-96 upload response JSON\", {\n cause: cause instanceof Error ? cause : undefined,\n });\n }\n return parseNip96UploadResponse(json);\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,kBAAkB;AAgBxB,IAAa,aAAb,cAAgC,WAAW,CAAC;AAE5C,SAAS,cAAc,YAA4B;CACjD,OAAO,GAAG,WAAW,QAAQ,QAAQ,EAAE,IAAI;AAC7C;AAEA,SAAS,qBAAqB,MAAmC;CAC/D,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAA;CACrE,MAAM,UAAW,KAA+B;CAChD,IAAI,OAAO,YAAY,UAAU,OAAO,KAAA;CAExC,OADa,QAAQ,KACX,K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,CACL;CACA,IAAI,CAAC,IAAI,IACP,MAAM,eAAe,iBAAiB,GAAG;CAG3C,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,IAAI,KAAK;CACxB,SAAS,OAAO;EACd,MAAM,IAAI,WAAW,uCAAuC,EAC1D,OAAO,iBAAiB,QAAQ,QAAQ,KAAA,EAC1C,CAAC;CACH;CACA,OAAO,yBAAyB,IAAI;AACtC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { n as EventTemplate, t as Event } from "../event-B5D2jxt_.mjs";
|
|
2
|
+
import { a as NostrError } from "../error-WEFS-R-4.mjs";
|
|
3
|
+
//#region src/nips/nip98.d.ts
|
|
4
|
+
declare class Nip98Error extends NostrError {}
|
|
5
|
+
/**
|
|
6
|
+
* Sign a kind 27235 auth event and encode it as a NIP-98 token.
|
|
7
|
+
* Uses standard base64 (`@scure/base`), not base64url.
|
|
8
|
+
*/
|
|
9
|
+
declare function getToken(url: string, method: string, sign: (template: EventTemplate) => Promise<Event> | Event, opts?: {
|
|
10
|
+
includeAuthorizationScheme?: boolean;
|
|
11
|
+
content?: string;
|
|
12
|
+
payload?: unknown;
|
|
13
|
+
now?: number;
|
|
14
|
+
}): Promise<string>;
|
|
15
|
+
/** Decode a NIP-98 token (with or without the `Nostr ` scheme) into an event. */
|
|
16
|
+
declare function unpackEventFromToken(token: string): Event;
|
|
17
|
+
/**
|
|
18
|
+
* True when `event` is a valid NIP-98 auth event for `url` + `method`.
|
|
19
|
+
* Verifies signature, kind 27235, timestamp window, `u`, `method`,
|
|
20
|
+
* and optional `payload` tag.
|
|
21
|
+
*/
|
|
22
|
+
declare function validateAuthEvent(event: Event, url: string, method: string, opts?: {
|
|
23
|
+
payload?: unknown;
|
|
24
|
+
maxSkewSec?: number;
|
|
25
|
+
}): boolean;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { Nip98Error, getToken, unpackEventFromToken, validateAuthEvent };
|
|
28
|
+
//# sourceMappingURL=nip98.d.mts.map
|