@waku/enr 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/bundle/crypto-5b69130e.js +2914 -0
- package/bundle/crypto.js +1 -0
- package/bundle/index.js +30072 -0
- package/dist/constants.d.ts +4 -0
- package/dist/constants.js +8 -0
- package/dist/constants.js.map +1 -0
- package/dist/crypto.d.ts +22 -0
- package/dist/crypto.js +47 -0
- package/dist/crypto.js.map +1 -0
- package/dist/enr.d.ts +90 -0
- package/dist/enr.js +432 -0
- package/dist/enr.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/keypair/index.d.ts +8 -0
- package/dist/keypair/index.js +53 -0
- package/dist/keypair/index.js.map +1 -0
- package/dist/keypair/secp256k1.d.ts +13 -0
- package/dist/keypair/secp256k1.js +57 -0
- package/dist/keypair/secp256k1.js.map +1 -0
- package/dist/keypair/types.d.ts +13 -0
- package/dist/keypair/types.js +7 -0
- package/dist/keypair/types.js.map +1 -0
- package/dist/multiaddr_from_fields.d.ts +2 -0
- package/dist/multiaddr_from_fields.js +8 -0
- package/dist/multiaddr_from_fields.js.map +1 -0
- package/dist/multiaddrs_codec.d.ts +3 -0
- package/dist/multiaddrs_codec.js +32 -0
- package/dist/multiaddrs_codec.js.map +1 -0
- package/dist/types.d.ts +8 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/v4.d.ts +3 -0
- package/dist/v4.js +14 -0
- package/dist/v4.js.map +1 -0
- package/dist/waku2_codec.d.ts +8 -0
- package/dist/waku2_codec.js +36 -0
- package/dist/waku2_codec.js.map +1 -0
- package/package.json +191 -0
- package/src/constants.ts +10 -0
- package/src/crypto.ts +61 -0
- package/src/enr.ts +524 -0
- package/src/index.ts +6 -0
- package/src/keypair/index.ts +76 -0
- package/src/keypair/secp256k1.ts +69 -0
- package/src/keypair/types.ts +14 -0
- package/src/multiaddr_from_fields.ts +18 -0
- package/src/multiaddrs_codec.ts +50 -0
- package/src/types.ts +11 -0
- package/src/v4.ts +21 -0
- package/src/waku2_codec.ts +39 -0
package/src/enr.ts
ADDED
@@ -0,0 +1,524 @@
|
|
1
|
+
import * as RLP from "@ethersproject/rlp";
|
2
|
+
import type { PeerId } from "@libp2p/interface-peer-id";
|
3
|
+
import { Multiaddr } from "@multiformats/multiaddr";
|
4
|
+
import {
|
5
|
+
convertToBytes,
|
6
|
+
convertToString,
|
7
|
+
} from "@multiformats/multiaddr/convert";
|
8
|
+
import {
|
9
|
+
bytesToHex,
|
10
|
+
bytesToUtf8,
|
11
|
+
hexToBytes,
|
12
|
+
utf8ToBytes,
|
13
|
+
} from "@waku/byte-utils";
|
14
|
+
import debug from "debug";
|
15
|
+
import { fromString } from "uint8arrays/from-string";
|
16
|
+
import { toString } from "uint8arrays/to-string";
|
17
|
+
|
18
|
+
import {
|
19
|
+
ERR_INVALID_ID,
|
20
|
+
ERR_NO_SIGNATURE,
|
21
|
+
MAX_RECORD_SIZE,
|
22
|
+
} from "./constants.js";
|
23
|
+
import { compressPublicKey, keccak256, verifySignature } from "./crypto.js";
|
24
|
+
import {
|
25
|
+
createKeypair,
|
26
|
+
createKeypairFromPeerId,
|
27
|
+
createPeerIdFromKeypair,
|
28
|
+
IKeypair,
|
29
|
+
KeypairType,
|
30
|
+
} from "./keypair";
|
31
|
+
import { multiaddrFromFields } from "./multiaddr_from_fields";
|
32
|
+
import { decodeMultiaddrs, encodeMultiaddrs } from "./multiaddrs_codec";
|
33
|
+
import { ENRKey, ENRValue, NodeId, SequenceNumber } from "./types";
|
34
|
+
import * as v4 from "./v4";
|
35
|
+
import { decodeWaku2, encodeWaku2, Waku2 } from "./waku2_codec";
|
36
|
+
|
37
|
+
const log = debug("waku:enr");
|
38
|
+
|
39
|
+
export class ENR extends Map<ENRKey, ENRValue> {
|
40
|
+
public static readonly RECORD_PREFIX = "enr:";
|
41
|
+
public seq: SequenceNumber;
|
42
|
+
public signature: Uint8Array | null;
|
43
|
+
public peerId?: PeerId;
|
44
|
+
|
45
|
+
private constructor(
|
46
|
+
kvs: Record<ENRKey, ENRValue> = {},
|
47
|
+
seq: SequenceNumber = BigInt(1),
|
48
|
+
signature: Uint8Array | null = null
|
49
|
+
) {
|
50
|
+
super(Object.entries(kvs));
|
51
|
+
this.seq = seq;
|
52
|
+
this.signature = signature;
|
53
|
+
}
|
54
|
+
|
55
|
+
static async create(
|
56
|
+
kvs: Record<ENRKey, ENRValue> = {},
|
57
|
+
seq: SequenceNumber = BigInt(1),
|
58
|
+
signature: Uint8Array | null = null
|
59
|
+
): Promise<ENR> {
|
60
|
+
const enr = new ENR(kvs, seq, signature);
|
61
|
+
try {
|
62
|
+
const publicKey = enr.publicKey;
|
63
|
+
if (publicKey) {
|
64
|
+
const keypair = createKeypair(enr.keypairType, undefined, publicKey);
|
65
|
+
enr.peerId = await createPeerIdFromKeypair(keypair);
|
66
|
+
}
|
67
|
+
} catch (e) {
|
68
|
+
log("Could not calculate peer id for ENR", e);
|
69
|
+
}
|
70
|
+
|
71
|
+
return enr;
|
72
|
+
}
|
73
|
+
|
74
|
+
static createV4(
|
75
|
+
publicKey: Uint8Array,
|
76
|
+
kvs: Record<ENRKey, ENRValue> = {}
|
77
|
+
): Promise<ENR> {
|
78
|
+
// EIP-778 specifies that the key must be in compressed format, 33 bytes
|
79
|
+
if (publicKey.length !== 33) {
|
80
|
+
publicKey = compressPublicKey(publicKey);
|
81
|
+
}
|
82
|
+
return ENR.create({
|
83
|
+
...kvs,
|
84
|
+
id: utf8ToBytes("v4"),
|
85
|
+
secp256k1: publicKey,
|
86
|
+
});
|
87
|
+
}
|
88
|
+
|
89
|
+
static async createFromPeerId(
|
90
|
+
peerId: PeerId,
|
91
|
+
kvs: Record<ENRKey, ENRValue> = {}
|
92
|
+
): Promise<ENR> {
|
93
|
+
const keypair = await createKeypairFromPeerId(peerId);
|
94
|
+
switch (keypair.type) {
|
95
|
+
case KeypairType.secp256k1:
|
96
|
+
return ENR.createV4(keypair.publicKey, kvs);
|
97
|
+
default:
|
98
|
+
throw new Error();
|
99
|
+
}
|
100
|
+
}
|
101
|
+
|
102
|
+
static async decodeFromValues(decoded: Uint8Array[]): Promise<ENR> {
|
103
|
+
if (!Array.isArray(decoded)) {
|
104
|
+
throw new Error("Decoded ENR must be an array");
|
105
|
+
}
|
106
|
+
if (decoded.length % 2 !== 0) {
|
107
|
+
throw new Error("Decoded ENR must have an even number of elements");
|
108
|
+
}
|
109
|
+
const [signature, seq, ...kvs] = decoded;
|
110
|
+
if (!signature || Array.isArray(signature)) {
|
111
|
+
throw new Error("Decoded ENR invalid signature: must be a byte array");
|
112
|
+
}
|
113
|
+
if (!seq || Array.isArray(seq)) {
|
114
|
+
throw new Error(
|
115
|
+
"Decoded ENR invalid sequence number: must be a byte array"
|
116
|
+
);
|
117
|
+
}
|
118
|
+
const obj: Record<ENRKey, ENRValue> = {};
|
119
|
+
for (let i = 0; i < kvs.length; i += 2) {
|
120
|
+
try {
|
121
|
+
obj[bytesToUtf8(kvs[i])] = kvs[i + 1];
|
122
|
+
} catch (e) {
|
123
|
+
log("Failed to decode ENR key to UTF-8, skipping it", kvs[i], e);
|
124
|
+
}
|
125
|
+
}
|
126
|
+
// If seq is an empty array, translate as value 0
|
127
|
+
const hexSeq = "0x" + (seq.length ? bytesToHex(seq) : "00");
|
128
|
+
|
129
|
+
const enr = await ENR.create(obj, BigInt(hexSeq), signature);
|
130
|
+
|
131
|
+
const rlpEncodedBytes = hexToBytes(RLP.encode([seq, ...kvs]));
|
132
|
+
if (!enr.verify(rlpEncodedBytes, signature)) {
|
133
|
+
throw new Error("Unable to verify ENR signature");
|
134
|
+
}
|
135
|
+
return enr;
|
136
|
+
}
|
137
|
+
|
138
|
+
static decode(encoded: Uint8Array): Promise<ENR> {
|
139
|
+
const decoded = RLP.decode(encoded).map(hexToBytes);
|
140
|
+
return ENR.decodeFromValues(decoded);
|
141
|
+
}
|
142
|
+
|
143
|
+
static decodeTxt(encoded: string): Promise<ENR> {
|
144
|
+
if (!encoded.startsWith(this.RECORD_PREFIX)) {
|
145
|
+
throw new Error(
|
146
|
+
`"string encoded ENR must start with '${this.RECORD_PREFIX}'`
|
147
|
+
);
|
148
|
+
}
|
149
|
+
return ENR.decode(fromString(encoded.slice(4), "base64url"));
|
150
|
+
}
|
151
|
+
|
152
|
+
set(k: ENRKey, v: ENRValue): this {
|
153
|
+
this.signature = null;
|
154
|
+
this.seq++;
|
155
|
+
return super.set(k, v);
|
156
|
+
}
|
157
|
+
|
158
|
+
get id(): string {
|
159
|
+
const id = this.get("id");
|
160
|
+
if (!id) throw new Error("id not found.");
|
161
|
+
return bytesToUtf8(id);
|
162
|
+
}
|
163
|
+
|
164
|
+
get keypairType(): KeypairType {
|
165
|
+
switch (this.id) {
|
166
|
+
case "v4":
|
167
|
+
return KeypairType.secp256k1;
|
168
|
+
default:
|
169
|
+
throw new Error(ERR_INVALID_ID);
|
170
|
+
}
|
171
|
+
}
|
172
|
+
|
173
|
+
get publicKey(): Uint8Array | undefined {
|
174
|
+
switch (this.id) {
|
175
|
+
case "v4":
|
176
|
+
return this.get("secp256k1");
|
177
|
+
default:
|
178
|
+
throw new Error(ERR_INVALID_ID);
|
179
|
+
}
|
180
|
+
}
|
181
|
+
|
182
|
+
get keypair(): IKeypair | undefined {
|
183
|
+
if (this.publicKey) {
|
184
|
+
const publicKey = this.publicKey;
|
185
|
+
return createKeypair(this.keypairType, undefined, publicKey);
|
186
|
+
}
|
187
|
+
return;
|
188
|
+
}
|
189
|
+
|
190
|
+
get nodeId(): NodeId | undefined {
|
191
|
+
switch (this.id) {
|
192
|
+
case "v4":
|
193
|
+
return this.publicKey ? v4.nodeId(this.publicKey) : undefined;
|
194
|
+
default:
|
195
|
+
throw new Error(ERR_INVALID_ID);
|
196
|
+
}
|
197
|
+
}
|
198
|
+
|
199
|
+
get ip(): string | undefined {
|
200
|
+
const raw = this.get("ip");
|
201
|
+
if (raw) {
|
202
|
+
return convertToString("ip4", raw) as string;
|
203
|
+
} else {
|
204
|
+
return undefined;
|
205
|
+
}
|
206
|
+
}
|
207
|
+
|
208
|
+
set ip(ip: string | undefined) {
|
209
|
+
if (ip) {
|
210
|
+
this.set("ip", convertToBytes("ip4", ip));
|
211
|
+
} else {
|
212
|
+
this.delete("ip");
|
213
|
+
}
|
214
|
+
}
|
215
|
+
|
216
|
+
get tcp(): number | undefined {
|
217
|
+
const raw = this.get("tcp");
|
218
|
+
if (raw) {
|
219
|
+
return Number(convertToString("tcp", raw));
|
220
|
+
} else {
|
221
|
+
return undefined;
|
222
|
+
}
|
223
|
+
}
|
224
|
+
|
225
|
+
set tcp(port: number | undefined) {
|
226
|
+
if (port === undefined) {
|
227
|
+
this.delete("tcp");
|
228
|
+
} else {
|
229
|
+
this.set("tcp", convertToBytes("tcp", port.toString(10)));
|
230
|
+
}
|
231
|
+
}
|
232
|
+
|
233
|
+
get udp(): number | undefined {
|
234
|
+
const raw = this.get("udp");
|
235
|
+
if (raw) {
|
236
|
+
return Number(convertToString("udp", raw));
|
237
|
+
} else {
|
238
|
+
return undefined;
|
239
|
+
}
|
240
|
+
}
|
241
|
+
|
242
|
+
set udp(port: number | undefined) {
|
243
|
+
if (port === undefined) {
|
244
|
+
this.delete("udp");
|
245
|
+
} else {
|
246
|
+
this.set("udp", convertToBytes("udp", port.toString(10)));
|
247
|
+
}
|
248
|
+
}
|
249
|
+
|
250
|
+
get ip6(): string | undefined {
|
251
|
+
const raw = this.get("ip6");
|
252
|
+
if (raw) {
|
253
|
+
return convertToString("ip6", raw) as string;
|
254
|
+
} else {
|
255
|
+
return undefined;
|
256
|
+
}
|
257
|
+
}
|
258
|
+
|
259
|
+
set ip6(ip: string | undefined) {
|
260
|
+
if (ip) {
|
261
|
+
this.set("ip6", convertToBytes("ip6", ip));
|
262
|
+
} else {
|
263
|
+
this.delete("ip6");
|
264
|
+
}
|
265
|
+
}
|
266
|
+
|
267
|
+
get tcp6(): number | undefined {
|
268
|
+
const raw = this.get("tcp6");
|
269
|
+
if (raw) {
|
270
|
+
return Number(convertToString("tcp", raw));
|
271
|
+
} else {
|
272
|
+
return undefined;
|
273
|
+
}
|
274
|
+
}
|
275
|
+
|
276
|
+
set tcp6(port: number | undefined) {
|
277
|
+
if (port === undefined) {
|
278
|
+
this.delete("tcp6");
|
279
|
+
} else {
|
280
|
+
this.set("tcp6", convertToBytes("tcp", port.toString(10)));
|
281
|
+
}
|
282
|
+
}
|
283
|
+
|
284
|
+
get udp6(): number | undefined {
|
285
|
+
const raw = this.get("udp6");
|
286
|
+
if (raw) {
|
287
|
+
return Number(convertToString("udp", raw));
|
288
|
+
} else {
|
289
|
+
return undefined;
|
290
|
+
}
|
291
|
+
}
|
292
|
+
|
293
|
+
set udp6(port: number | undefined) {
|
294
|
+
if (port === undefined) {
|
295
|
+
this.delete("udp6");
|
296
|
+
} else {
|
297
|
+
this.set("udp6", convertToBytes("udp", port.toString(10)));
|
298
|
+
}
|
299
|
+
}
|
300
|
+
|
301
|
+
/**
|
302
|
+
* Get the `multiaddrs` field from ENR.
|
303
|
+
*
|
304
|
+
* This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.
|
305
|
+
* These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host
|
306
|
+
* address (e.g. `dns4`, `dnsaddr`, etc)..
|
307
|
+
*
|
308
|
+
* If the peer information only contains information that can be represented with the ENR pre-defined keys
|
309
|
+
* (ip, tcp, etc) then the usage of { @link getLocationMultiaddr } should be preferred.
|
310
|
+
*
|
311
|
+
* The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.
|
312
|
+
*/
|
313
|
+
get multiaddrs(): Multiaddr[] | undefined {
|
314
|
+
const raw = this.get("multiaddrs");
|
315
|
+
|
316
|
+
if (raw) return decodeMultiaddrs(raw);
|
317
|
+
|
318
|
+
return;
|
319
|
+
}
|
320
|
+
|
321
|
+
/**
|
322
|
+
* Set the `multiaddrs` field on the ENR.
|
323
|
+
*
|
324
|
+
* This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.
|
325
|
+
* These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host
|
326
|
+
* address (e.g. `dns4`, `dnsaddr`, etc)..
|
327
|
+
*
|
328
|
+
* If the peer information only contains information that can be represented with the ENR pre-defined keys
|
329
|
+
* (ip, tcp, etc) then the usage of { @link setLocationMultiaddr } should be preferred.
|
330
|
+
* The multiaddresses stored in this field must be location multiaddresses,
|
331
|
+
* ie, without a peer id.
|
332
|
+
*/
|
333
|
+
set multiaddrs(multiaddrs: Multiaddr[] | undefined) {
|
334
|
+
if (multiaddrs === undefined) {
|
335
|
+
this.delete("multiaddrs");
|
336
|
+
} else {
|
337
|
+
const multiaddrsBuf = encodeMultiaddrs(multiaddrs);
|
338
|
+
this.set("multiaddrs", multiaddrsBuf);
|
339
|
+
}
|
340
|
+
}
|
341
|
+
|
342
|
+
getLocationMultiaddr(
|
343
|
+
protocol: "udp" | "udp4" | "udp6" | "tcp" | "tcp4" | "tcp6"
|
344
|
+
): Multiaddr | undefined {
|
345
|
+
if (protocol === "udp") {
|
346
|
+
return (
|
347
|
+
this.getLocationMultiaddr("udp4") || this.getLocationMultiaddr("udp6")
|
348
|
+
);
|
349
|
+
}
|
350
|
+
if (protocol === "tcp") {
|
351
|
+
return (
|
352
|
+
this.getLocationMultiaddr("tcp4") || this.getLocationMultiaddr("tcp6")
|
353
|
+
);
|
354
|
+
}
|
355
|
+
const isIpv6 = protocol.endsWith("6");
|
356
|
+
const ipVal = this.get(isIpv6 ? "ip6" : "ip");
|
357
|
+
if (!ipVal) {
|
358
|
+
return;
|
359
|
+
}
|
360
|
+
|
361
|
+
const isUdp = protocol.startsWith("udp");
|
362
|
+
const isTcp = protocol.startsWith("tcp");
|
363
|
+
let protoName, protoVal;
|
364
|
+
if (isUdp) {
|
365
|
+
protoName = "udp";
|
366
|
+
protoVal = isIpv6 ? this.get("udp6") : this.get("udp");
|
367
|
+
} else if (isTcp) {
|
368
|
+
protoName = "tcp";
|
369
|
+
protoVal = isIpv6 ? this.get("tcp6") : this.get("tcp");
|
370
|
+
} else {
|
371
|
+
return;
|
372
|
+
}
|
373
|
+
|
374
|
+
if (!protoVal) {
|
375
|
+
return;
|
376
|
+
}
|
377
|
+
|
378
|
+
return multiaddrFromFields(
|
379
|
+
isIpv6 ? "ip6" : "ip4",
|
380
|
+
protoName,
|
381
|
+
ipVal,
|
382
|
+
protoVal
|
383
|
+
);
|
384
|
+
}
|
385
|
+
|
386
|
+
setLocationMultiaddr(multiaddr: Multiaddr): void {
|
387
|
+
const protoNames = multiaddr.protoNames();
|
388
|
+
if (
|
389
|
+
protoNames.length !== 2 &&
|
390
|
+
protoNames[1] !== "udp" &&
|
391
|
+
protoNames[1] !== "tcp"
|
392
|
+
) {
|
393
|
+
throw new Error("Invalid multiaddr");
|
394
|
+
}
|
395
|
+
const tuples = multiaddr.tuples();
|
396
|
+
if (!tuples[0][1] || !tuples[1][1]) {
|
397
|
+
throw new Error("Invalid multiaddr");
|
398
|
+
}
|
399
|
+
|
400
|
+
// IPv4
|
401
|
+
if (tuples[0][0] === 4) {
|
402
|
+
this.set("ip", tuples[0][1]);
|
403
|
+
this.set(protoNames[1], tuples[1][1]);
|
404
|
+
} else {
|
405
|
+
this.set("ip6", tuples[0][1]);
|
406
|
+
this.set(protoNames[1] + "6", tuples[1][1]);
|
407
|
+
}
|
408
|
+
}
|
409
|
+
|
410
|
+
/**
|
411
|
+
* Returns the full multiaddr from the ENR fields matching the provided
|
412
|
+
* `protocol` parameter.
|
413
|
+
* To return full multiaddrs from the `multiaddrs` ENR field,
|
414
|
+
* use { @link ENR.getFullMultiaddrs }.
|
415
|
+
*
|
416
|
+
* @param protocol
|
417
|
+
*/
|
418
|
+
getFullMultiaddr(
|
419
|
+
protocol: "udp" | "udp4" | "udp6" | "tcp" | "tcp4" | "tcp6"
|
420
|
+
): Multiaddr | undefined {
|
421
|
+
if (this.peerId) {
|
422
|
+
const locationMultiaddr = this.getLocationMultiaddr(protocol);
|
423
|
+
if (locationMultiaddr) {
|
424
|
+
return locationMultiaddr.encapsulate(`/p2p/${this.peerId.toString()}`);
|
425
|
+
}
|
426
|
+
}
|
427
|
+
return;
|
428
|
+
}
|
429
|
+
|
430
|
+
/**
|
431
|
+
* Returns the full multiaddrs from the `multiaddrs` ENR field.
|
432
|
+
*/
|
433
|
+
getFullMultiaddrs(): Multiaddr[] {
|
434
|
+
if (this.peerId && this.multiaddrs) {
|
435
|
+
const peerId = this.peerId;
|
436
|
+
return this.multiaddrs.map((ma) => {
|
437
|
+
return ma.encapsulate(`/p2p/${peerId.toString()}`);
|
438
|
+
});
|
439
|
+
}
|
440
|
+
return [];
|
441
|
+
}
|
442
|
+
|
443
|
+
/**
|
444
|
+
* Get the `waku2` field from ENR.
|
445
|
+
*/
|
446
|
+
get waku2(): Waku2 | undefined {
|
447
|
+
const raw = this.get("waku2");
|
448
|
+
if (raw) return decodeWaku2(raw[0]);
|
449
|
+
|
450
|
+
return;
|
451
|
+
}
|
452
|
+
|
453
|
+
/**
|
454
|
+
* Set the `waku2` field on the ENR.
|
455
|
+
*/
|
456
|
+
set waku2(waku2: Waku2 | undefined) {
|
457
|
+
if (waku2 === undefined) {
|
458
|
+
this.delete("waku2");
|
459
|
+
} else {
|
460
|
+
const byte = encodeWaku2(waku2);
|
461
|
+
this.set("waku2", new Uint8Array([byte]));
|
462
|
+
}
|
463
|
+
}
|
464
|
+
|
465
|
+
verify(data: Uint8Array, signature: Uint8Array): boolean {
|
466
|
+
if (!this.get("id") || this.id !== "v4") {
|
467
|
+
throw new Error(ERR_INVALID_ID);
|
468
|
+
}
|
469
|
+
if (!this.publicKey) {
|
470
|
+
throw new Error("Failed to verify ENR: No public key");
|
471
|
+
}
|
472
|
+
return verifySignature(signature, keccak256(data), this.publicKey);
|
473
|
+
}
|
474
|
+
|
475
|
+
async sign(data: Uint8Array, privateKey: Uint8Array): Promise<Uint8Array> {
|
476
|
+
switch (this.id) {
|
477
|
+
case "v4":
|
478
|
+
this.signature = await v4.sign(privateKey, data);
|
479
|
+
break;
|
480
|
+
default:
|
481
|
+
throw new Error(ERR_INVALID_ID);
|
482
|
+
}
|
483
|
+
return this.signature;
|
484
|
+
}
|
485
|
+
|
486
|
+
async encodeToValues(
|
487
|
+
privateKey?: Uint8Array
|
488
|
+
): Promise<(ENRKey | ENRValue | number[])[]> {
|
489
|
+
// sort keys and flatten into [k, v, k, v, ...]
|
490
|
+
const content: Array<ENRKey | ENRValue | number[]> = Array.from(this.keys())
|
491
|
+
.sort((a, b) => a.localeCompare(b))
|
492
|
+
.map((k) => [k, this.get(k)] as [ENRKey, ENRValue])
|
493
|
+
.map(([k, v]) => [utf8ToBytes(k), v])
|
494
|
+
.flat();
|
495
|
+
content.unshift(new Uint8Array([Number(this.seq)]));
|
496
|
+
if (privateKey) {
|
497
|
+
content.unshift(
|
498
|
+
await this.sign(hexToBytes(RLP.encode(content)), privateKey)
|
499
|
+
);
|
500
|
+
} else {
|
501
|
+
if (!this.signature) {
|
502
|
+
throw new Error(ERR_NO_SIGNATURE);
|
503
|
+
}
|
504
|
+
content.unshift(this.signature);
|
505
|
+
}
|
506
|
+
return content;
|
507
|
+
}
|
508
|
+
|
509
|
+
async encode(privateKey?: Uint8Array): Promise<Uint8Array> {
|
510
|
+
const encoded = hexToBytes(
|
511
|
+
RLP.encode(await this.encodeToValues(privateKey))
|
512
|
+
);
|
513
|
+
if (encoded.length >= MAX_RECORD_SIZE) {
|
514
|
+
throw new Error("ENR must be less than 300 bytes");
|
515
|
+
}
|
516
|
+
return encoded;
|
517
|
+
}
|
518
|
+
|
519
|
+
async encodeTxt(privateKey?: Uint8Array): Promise<string> {
|
520
|
+
return (
|
521
|
+
ENR.RECORD_PREFIX + toString(await this.encode(privateKey), "base64url")
|
522
|
+
);
|
523
|
+
}
|
524
|
+
}
|
package/src/index.ts
ADDED
@@ -0,0 +1,76 @@
|
|
1
|
+
import { unmarshalPrivateKey, unmarshalPublicKey } from "@libp2p/crypto/keys";
|
2
|
+
import { supportedKeys } from "@libp2p/crypto/keys";
|
3
|
+
import type { PeerId } from "@libp2p/interface-peer-id";
|
4
|
+
import { peerIdFromKeys } from "@libp2p/peer-id";
|
5
|
+
|
6
|
+
import { Secp256k1Keypair } from "./secp256k1.js";
|
7
|
+
import { IKeypair, KeypairType } from "./types.js";
|
8
|
+
|
9
|
+
export const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
|
10
|
+
export * from "./types.js";
|
11
|
+
export * from "./secp256k1.js";
|
12
|
+
|
13
|
+
export function createKeypair(
|
14
|
+
type: KeypairType,
|
15
|
+
privateKey?: Uint8Array,
|
16
|
+
publicKey?: Uint8Array
|
17
|
+
): IKeypair {
|
18
|
+
switch (type) {
|
19
|
+
case KeypairType.secp256k1:
|
20
|
+
return new Secp256k1Keypair(privateKey, publicKey);
|
21
|
+
default:
|
22
|
+
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
|
23
|
+
}
|
24
|
+
}
|
25
|
+
|
26
|
+
export async function createPeerIdFromKeypair(
|
27
|
+
keypair: IKeypair
|
28
|
+
): Promise<PeerId> {
|
29
|
+
switch (keypair.type) {
|
30
|
+
case KeypairType.secp256k1: {
|
31
|
+
const publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(
|
32
|
+
keypair.publicKey
|
33
|
+
);
|
34
|
+
|
35
|
+
const privateKey = keypair.hasPrivateKey()
|
36
|
+
? new supportedKeys.secp256k1.Secp256k1PrivateKey(keypair.privateKey)
|
37
|
+
: undefined;
|
38
|
+
|
39
|
+
return peerIdFromKeys(publicKey.bytes, privateKey?.bytes);
|
40
|
+
}
|
41
|
+
default:
|
42
|
+
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
|
43
|
+
}
|
44
|
+
}
|
45
|
+
|
46
|
+
export async function createKeypairFromPeerId(
|
47
|
+
peerId: PeerId
|
48
|
+
): Promise<IKeypair> {
|
49
|
+
let keypairType;
|
50
|
+
switch (peerId.type) {
|
51
|
+
case "RSA":
|
52
|
+
keypairType = KeypairType.rsa;
|
53
|
+
break;
|
54
|
+
case "Ed25519":
|
55
|
+
keypairType = KeypairType.ed25519;
|
56
|
+
break;
|
57
|
+
case "secp256k1":
|
58
|
+
keypairType = KeypairType.secp256k1;
|
59
|
+
break;
|
60
|
+
default:
|
61
|
+
throw new Error("Unsupported peer id type");
|
62
|
+
}
|
63
|
+
|
64
|
+
const publicKey = peerId.publicKey
|
65
|
+
? unmarshalPublicKey(peerId.publicKey)
|
66
|
+
: undefined;
|
67
|
+
const privateKey = peerId.privateKey
|
68
|
+
? await unmarshalPrivateKey(peerId.privateKey)
|
69
|
+
: undefined;
|
70
|
+
|
71
|
+
return createKeypair(
|
72
|
+
keypairType,
|
73
|
+
privateKey?.marshal(),
|
74
|
+
publicKey?.marshal()
|
75
|
+
);
|
76
|
+
}
|
@@ -0,0 +1,69 @@
|
|
1
|
+
import * as secp from "@noble/secp256k1";
|
2
|
+
|
3
|
+
import { compressPublicKey, randomBytes } from "../crypto.js";
|
4
|
+
|
5
|
+
import { IKeypair, KeypairType } from "./types.js";
|
6
|
+
|
7
|
+
export class Secp256k1Keypair implements IKeypair {
|
8
|
+
readonly type: KeypairType;
|
9
|
+
_privateKey?: Uint8Array;
|
10
|
+
readonly _publicKey?: Uint8Array;
|
11
|
+
|
12
|
+
constructor(privateKey?: Uint8Array, publicKey?: Uint8Array) {
|
13
|
+
let pub = publicKey;
|
14
|
+
if (pub) {
|
15
|
+
pub = compressPublicKey(pub);
|
16
|
+
}
|
17
|
+
if ((this._privateKey = privateKey) && !this.privateKeyVerify()) {
|
18
|
+
throw new Error("Invalid private key");
|
19
|
+
}
|
20
|
+
if ((this._publicKey = pub) && !this.publicKeyVerify()) {
|
21
|
+
throw new Error("Invalid public key");
|
22
|
+
}
|
23
|
+
|
24
|
+
this.type = KeypairType.secp256k1;
|
25
|
+
}
|
26
|
+
|
27
|
+
static async generate(): Promise<Secp256k1Keypair> {
|
28
|
+
const privateKey = randomBytes(32);
|
29
|
+
const publicKey = secp.getPublicKey(privateKey);
|
30
|
+
return new Secp256k1Keypair(privateKey, publicKey);
|
31
|
+
}
|
32
|
+
|
33
|
+
privateKeyVerify(key = this._privateKey): boolean {
|
34
|
+
if (key) {
|
35
|
+
return secp.utils.isValidPrivateKey(key);
|
36
|
+
}
|
37
|
+
return true;
|
38
|
+
}
|
39
|
+
|
40
|
+
publicKeyVerify(key = this._publicKey): boolean {
|
41
|
+
if (key) {
|
42
|
+
try {
|
43
|
+
secp.Point.fromHex(key);
|
44
|
+
return true;
|
45
|
+
} catch {
|
46
|
+
return false;
|
47
|
+
}
|
48
|
+
}
|
49
|
+
return true;
|
50
|
+
}
|
51
|
+
|
52
|
+
get privateKey(): Uint8Array {
|
53
|
+
if (!this._privateKey) {
|
54
|
+
throw new Error();
|
55
|
+
}
|
56
|
+
return this._privateKey;
|
57
|
+
}
|
58
|
+
|
59
|
+
get publicKey(): Uint8Array {
|
60
|
+
if (!this._publicKey) {
|
61
|
+
throw new Error();
|
62
|
+
}
|
63
|
+
return this._publicKey;
|
64
|
+
}
|
65
|
+
|
66
|
+
hasPrivateKey(): boolean {
|
67
|
+
return !!this._privateKey;
|
68
|
+
}
|
69
|
+
}
|
@@ -0,0 +1,14 @@
|
|
1
|
+
export enum KeypairType {
|
2
|
+
rsa = 0,
|
3
|
+
ed25519 = 1,
|
4
|
+
secp256k1 = 2,
|
5
|
+
}
|
6
|
+
|
7
|
+
export interface IKeypair {
|
8
|
+
type: KeypairType;
|
9
|
+
privateKey: Uint8Array;
|
10
|
+
publicKey: Uint8Array;
|
11
|
+
privateKeyVerify(): boolean;
|
12
|
+
publicKeyVerify(): boolean;
|
13
|
+
hasPrivateKey(): boolean;
|
14
|
+
}
|
@@ -0,0 +1,18 @@
|
|
1
|
+
import { multiaddr } from "@multiformats/multiaddr";
|
2
|
+
import type { Multiaddr } from "@multiformats/multiaddr";
|
3
|
+
import { convertToString } from "@multiformats/multiaddr/convert";
|
4
|
+
|
5
|
+
export function multiaddrFromFields(
|
6
|
+
ipFamily: string,
|
7
|
+
protocol: string,
|
8
|
+
ipBytes: Uint8Array,
|
9
|
+
protocolBytes: Uint8Array
|
10
|
+
): Multiaddr {
|
11
|
+
let ma = multiaddr("/" + ipFamily + "/" + convertToString(ipFamily, ipBytes));
|
12
|
+
|
13
|
+
ma = ma.encapsulate(
|
14
|
+
multiaddr("/" + protocol + "/" + convertToString(protocol, protocolBytes))
|
15
|
+
);
|
16
|
+
|
17
|
+
return ma;
|
18
|
+
}
|