-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHDKIndex.ts
More file actions
373 lines (333 loc) · 15.2 KB
/
HDKIndex.ts
File metadata and controls
373 lines (333 loc) · 15.2 KB
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*! animiq-nip76-tools - MIT License (c) 2023 David Krause (animiq.com) */
import { sha256 } from '@noble/hashes/sha256';
import { concatBytes, hexToBytes, randomBytes } from '@noble/hashes/utils';
import { base64 } from '@scure/base';
import * as nostrTools from 'nostr-tools';
import { PointerType, PrivateChannelPointer } from '../../nostr-tools/nip19-extension';
import { ContentDocument, Invitation, NostrEventDocument, NostrKinds, PostDocument, PrivateChannel, Rsvp } from '../content';
import { getCreatedAtIndexes, getReducedKey } from '../util';
import { HDKey } from './HDKey';
import { Versions } from './Versions';
import { Subject } from 'rxjs';
export enum HDKIndexType {
Private = 1, // 0001
Sequential = 1 << 1, // 0010
TimeBased = 1 << 2, // 0100
Singleton = 1 << 3, // 1000
}
export interface DocumentKeyset {
signingKey?: HDKey;
encryptKey?: HDKey
}
export interface DocumentKeysetDTO {
signingKey: string;
encryptKey: string;
}
export interface SequentialKeyset {
offset: number;
page: number;
keys: DocumentKeyset[];
}
export interface SequentialKeysetDTO {
offset: number;
page: number;
keys: DocumentKeysetDTO[];
}
export interface HDKIndexDTO {
type: HDKIndexType;
signingParent: string;
encryptParent: string;
wordset?: number[];
sequentialKeysets: SequentialKeysetDTO[];
};
export class HDKIndex {
eventTag: string;
sequentialKeysets: SequentialKeyset[] = [];
documents: ContentDocument[] = [];
parentDocument?: ContentDocument;
relays = [
{ uri: 'wss://relay.damus.io', read: true, write: true },
{ uri: 'wss://nostr.mom', read: true, write: true },
{ uri: 'wss://relay.snort.social', read: true, write: true }
];
constructor(
public type: HDKIndexType,
public signingParent: HDKey,
public encryptParent: HDKey,
public wordset?: Uint32Array
) {
if (!this.isTimeBased && !this.isSequential && !this.isSingleton) {
throw new Error('HDKIndex must either be Sequential, TimeBased or Singleton.');
}
if (this.isTimeBased && this.isSequential) {
throw new Error('HDKIndex cannot be both Sequential and TimeBased.');
}
// if (this.isPrivate && !encryptParent.privateKey) {
// throw new Error('privateKey is required on the cryptoParent when the type is Private.');
// }
if (this.isPrivate && !this.wordset) {
this.wordset = new Uint32Array((sha256(signingParent.privateKey)).buffer);
}
this.eventTag = signingParent.deriveChildKey(0).deriveChildKey(0).pubKeyHash;
}
get isPrivate(): boolean {
return (this.type & HDKIndexType.Private) === HDKIndexType.Private;
}
get isTimeBased(): boolean {
return (this.type & HDKIndexType.TimeBased) === HDKIndexType.TimeBased;
}
get isSequential(): boolean {
return (this.type & HDKIndexType.Sequential) === HDKIndexType.Sequential;
}
get isSingleton(): boolean {
return (this.type & HDKIndexType.Singleton) === HDKIndexType.Singleton;
}
getDocumentKeyset(docIndex: number, privateKey?: string): DocumentKeyset {
let signingKey: HDKey | undefined = undefined;
let encryptKey: HDKey | undefined = undefined;
if (this.isSingleton) {
signingKey = this.signingParent;
encryptKey = this.encryptParent;
} else if (this.isSequential) {
if (this.signingParent.privateKey) {
signingKey = getReducedKey({ root: this.signingParent, offset: docIndex, wordset: this.wordset!.slice(0, 4) });
encryptKey = getReducedKey({ root: this.encryptParent, offset: docIndex, wordset: this.wordset!.slice(4, 8) });
} else {
const sequentialKeyset = this.sequentialKeysets.find(x =>
docIndex >= x.offset + (x.keys.length * x.page)
&& docIndex < x.offset + (x.keys.length * (x.page + 1))
);
if (sequentialKeyset) {
const sqIndex = docIndex - sequentialKeyset.offset;
signingKey = sequentialKeyset.keys[sqIndex].signingKey;
encryptKey = sequentialKeyset.keys[sqIndex].encryptKey;
}
}
} else {
if (privateKey) {
signingKey = new HDKey({
privateKey: hexToBytes(privateKey),
chainCode: this.signingParent.chainCode,
version: this.signingParent.version
}).deriveChildKey(docIndex, false);
}
encryptKey = this.encryptParent.deriveChildKey(docIndex!, false);
}
return { signingKey, encryptKey };
}
async createDeleteEvent(doc: ContentDocument, privateKey: string): Promise<NostrEventDocument> {
const cati = getCreatedAtIndexes();
const keyset = this.getDocumentKeyset(doc.docIndex, privateKey);
const event = nostrTools.getBlankEvent() as NostrEventDocument;
event.tags = [['e', doc.nostrEvent.id]];
event.created_at = cati.created_at;
event.kind = nostrTools.Kind.EventDeletion;
event.pubkey = keyset.signingKey!.nostrPubKey;
event.content = 'delete';
event.sig = nostrTools.signEvent(event, keyset.signingKey!.hexPrivKey!) as any;
event.id = nostrTools.getEventHash(event);
return event;
}
async createEvent(doc: ContentDocument, privateKey: string): Promise<NostrEventDocument> {
if (!doc.docIndex && this.isSequential) {
throw new Error('docIndex is required to create events on sequential HDKIndexType.');
}
if (!privateKey && !this.isPrivate) {
throw new Error('privateKey is required to create non-private events.');
}
const cati = getCreatedAtIndexes();
if (this.isTimeBased) {
doc.docIndex = cati.index1;
}
const keyset = this.getDocumentKeyset(doc.docIndex, privateKey);
const keydata = keyset.encryptKey!.publicKey.slice(1);
const content = new TextEncoder().encode(doc.serialize());
const iv = randomBytes(16);
const alg = { name: 'AES-GCM', iv, length: 256 } as AesKeyAlgorithm;
const key = await globalThis.crypto.subtle.importKey('raw', keydata, alg, false, ['encrypt']);
const encrypted = new Uint8Array(await globalThis.crypto.subtle.encrypt(alg, key, content));
const event = nostrTools.getBlankEvent() as NostrEventDocument;
event.tags = [['e', this.isSequential ? keyset.signingKey!.deriveChildKey(0).pubKeyHash : this.eventTag]];
event.created_at = cati.created_at;
event.kind = 17761;
event.pubkey = keyset.signingKey!.nostrPubKey;
event.content = base64.encode(concatBytes(iv, encrypted));
event.sig = nostrTools.signEvent(event, keyset.signingKey!.hexPrivKey!) as any;
event.id = nostrTools.getEventHash(event);
doc.nostrEvent = event;
return event;
}
async readEvent(event: NostrEventDocument, sequentialIndex?: number): Promise<ContentDocument | undefined> {
if (this.isSequential && !sequentialIndex === undefined) {
throw new Error('docIndex is required to read events on sequential HDKIndexType.');
}
try {
const cati = getCreatedAtIndexes(event.created_at);
const docIndex = this.isTimeBased ? cati.index1 : sequentialIndex!;
const keyset = this.getDocumentKeyset(docIndex!);
const keydata = keyset.encryptKey!.publicKey.slice(1);
const encrypted = base64.decode(event.content);
const iv = encrypted.slice(0, 16);
const data = encrypted.slice(16);
const alg = { name: 'AES-GCM', iv, length: 256 } as AesKeyAlgorithm;
const secretKey = await globalThis.crypto.subtle.importKey('raw', keydata, alg, false, ['decrypt']);
const decrypted = new Uint8Array(await globalThis.crypto.subtle.decrypt(alg, secretKey, data));
const json = new TextDecoder().decode(decrypted);
return this.getDocumentFromJson(json, event, keyset, docIndex);
} catch (error) {
if (event.created_at > 1680204477)
console.error('HDKIndex.readEvent error', { error, event });
return undefined;
}
}
private getDocumentFromJson(json: string, event: NostrEventDocument, keyset: DocumentKeyset, docIndex?: number): ContentDocument {
const kind = parseInt(json.match(/\d+/)![0]);
const doc = HDKIndex.getContentDocument(kind);
let existing = this.documents.find(x => x.nostrEvent?.pubkey === event.pubkey);
if (doc instanceof PrivateChannel) {
(doc as PrivateChannel).setIndexKeys(keyset.signingKey!, keyset.encryptKey!, existing as PrivateChannel);
}
doc.deserialize(json);
if (docIndex) {
const publicKey = !this.isPrivate && doc.content.pubkey ? hexToBytes('02' + doc.content.pubkey) : this.signingParent.publicKey;
const signerKey = new HDKey({ publicKey, chainCode: this.signingParent.chainCode, version: this.signingParent.version });
doc.verified = signerKey.deriveChildKey(docIndex).nostrPubKey === event.pubkey;
doc.docIndex = docIndex;
}
doc.ownerPubKey = doc.content.pubkey;
doc.nostrEvent = event;
doc.dkxParent = this;
doc.ready = true;
if (existing) {
const i = this.documents.indexOf(existing);
this.documents.splice(i, 1);
}
this.documents = [...[], ...this.documents, doc].sort((a, b) => b.nostrEvent?.created_at - a.nostrEvent?.created_at);
return doc;
}
getSequentialKeyset(offset = 0, page = 0): SequentialKeyset {
const rtn: SequentialKeyset = this.sequentialKeysets.find(x => x.page === page && x.offset === offset) || {
offset,
page,
keys: []
};
if (this.isSequential && this.signingParent.privateKey) {
if (rtn.keys.length === 0) {
const start = (page * 20) + offset;
rtn.keys = Array(20).fill({}).map((_, i) => {
return {
signingKey: getReducedKey({ root: this.signingParent, offset: i + start, wordset: this.wordset!.slice(0, 4) }),
encryptKey: getReducedKey({ root: this.encryptParent, offset: i + start, wordset: this.wordset!.slice(4, 8) })
};
});
this.sequentialKeysets.push(rtn);
}
}
return rtn;
}
static relayPool = new nostrTools.SimplePool();
queryRelays(start = 0, sequentialOffset = 0, subId: string): Subject<ContentDocument> {
const subject = new Subject<ContentDocument>();
const sequentialKeyset = this.sequentialKeysets[sequentialOffset];
const filter: nostrTools.Filter = { kinds: [17761] };
if (this.isSingleton) {
filter.authors = [this.signingParent.nostrPubKey];
filter.limit = 1;
} else if (this.isSequential) {
filter.authors = sequentialKeyset.keys.map(x => x.signingKey?.nostrPubKey!);
filter.limit = sequentialKeyset.keys.length;
} else {
filter['#e'] = [this.eventTag];
filter.limit = 100;
}
// const relayPool = new nostrTools.SimplePool();
const relays = this.relays.map(x => x.uri);
const sub = HDKIndex.relayPool.sub(relays, [filter], { id: subId });
sub.on('event', async (nostrEvent: NostrEventDocument) => {
const docIndex = this.isSequential
? sequentialKeyset.keys.findIndex(x => x.signingKey?.nostrPubKey === nostrEvent.pubkey) + sequentialKeyset.offset + start
: undefined;
const doc = await this.readEvent(nostrEvent, docIndex);
if (doc) {
subject.next(doc);
}
});
sub.on('eose', () => {
sub.unsub();
subject.complete();
});
return subject;
}
toJSON(): HDKIndexDTO {
let sequentialKeysetsDTO: SequentialKeysetDTO[] = [];
if (this.isSequential) {
sequentialKeysetsDTO = this.sequentialKeysets.map(sks => ({
offset: sks.offset,
page: sks.page,
keys: sks.keys.map(x => ({
signingKey: x.signingKey!.extendedPublicKey,
encryptKey: x.encryptKey!.extendedPublicKey
}))
}));
}
return {
type: this.type,
signingParent: this.signingParent.extendedPrivateKey || this.signingParent.extendedPublicKey,
encryptParent: this.encryptParent.extendedPrivateKey || this.encryptParent.extendedPublicKey,
wordset: this.wordset ? Array.from(this.wordset) : undefined,
sequentialKeysets: sequentialKeysetsDTO
};
}
static fromJSON(jsonObj: HDKIndexDTO): HDKIndex {
const signingParent = HDKey.parseExtendedKey(jsonObj.signingParent);
const encryptParent = HDKey.parseExtendedKey(jsonObj.encryptParent);
const wordset = jsonObj.wordset ? Uint32Array.from(jsonObj.wordset) : undefined;
const hdkIndex = new HDKIndex(jsonObj.type, signingParent, encryptParent, wordset);
if (hdkIndex.isSequential) {
hdkIndex.sequentialKeysets = jsonObj.sequentialKeysets.map(sks => ({
offset: sks.offset,
page: sks.page,
keys: sks.keys.map(x => ({
signingKey: HDKey.parseExtendedKey(x.signingKey),
encryptKey: HDKey.parseExtendedKey(x.encryptKey)
}))
}));
}
return hdkIndex;
}
static fromChannelPointer(pointer: PrivateChannelPointer): HDKIndex {
if ((pointer.type & PointerType.HasBothKeys) != PointerType.HasBothKeys) {
throw new Error('Cannot create HDKIndex without both a signing and crypto parent key.')
}
const indexType = (pointer.type & PointerType.FullKeySet) === PointerType.FullKeySet
? HDKIndexType.TimeBased
: HDKIndexType.Singleton;
const signingKey = new HDKey({
publicKey: pointer.signingKey,
chainCode: pointer.signingChain || new Uint8Array(32),
version: Versions.nip76API1
});
const cryptoKey = new HDKey({
publicKey: pointer.cryptoKey,
chainCode: pointer.cryptoChain || new Uint8Array(32),
version: Versions.nip76API1
});
const channel = new HDKIndex(indexType, signingKey, cryptoKey);
return channel;
}
static getContentDocument(kind: number): ContentDocument {
switch (kind) {
case NostrKinds.ChannelMetadata:
return new PrivateChannel();
case NostrKinds.Text:
case NostrKinds.Reaction:
return new PostDocument();
case NostrKinds.PrivateChannelInvitation:
return new Invitation();
case NostrKinds.PrivateChannelRSVP:
return new Rsvp();
default:
throw new Error(`Kind ${kind} not supported.`)
}
}
}