@waku/enr 0.0.27-6a2d787.0 โ 0.0.27-98208d5.0
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/index.js +727 -1388
- package/dist/.tsbuildinfo +1 -1
- package/dist/creator.d.ts +1 -1
- package/dist/creator.js +1 -2
- package/dist/creator.js.map +1 -1
- package/dist/decoder.js +1 -1
- package/dist/decoder.js.map +1 -1
- package/dist/enr.d.ts +1 -1
- package/dist/enr.js +2 -2
- package/dist/enr.js.map +1 -1
- package/dist/peer_id.d.ts +3 -4
- package/dist/peer_id.js +7 -24
- package/dist/peer_id.js.map +1 -1
- package/package.json +1 -1
- package/src/creator.ts +2 -3
- package/src/decoder.ts +1 -1
- package/src/enr.ts +3 -3
- package/src/peer_id.ts +9 -34
package/bundle/index.js
CHANGED
@@ -241,11 +241,12 @@ class Decoder {
|
|
241
241
|
constructor(name, prefix, baseDecode) {
|
242
242
|
this.name = name;
|
243
243
|
this.prefix = prefix;
|
244
|
+
const prefixCodePoint = prefix.codePointAt(0);
|
244
245
|
/* c8 ignore next 3 */
|
245
|
-
if (
|
246
|
+
if (prefixCodePoint === undefined) {
|
246
247
|
throw new Error('Invalid prefix character');
|
247
248
|
}
|
248
|
-
this.prefixCodePoint =
|
249
|
+
this.prefixCodePoint = prefixCodePoint;
|
249
250
|
this.baseDecode = baseDecode;
|
250
251
|
}
|
251
252
|
decode(text) {
|
@@ -449,7 +450,14 @@ var base2$1 = /*#__PURE__*/Object.freeze({
|
|
449
450
|
|
450
451
|
const alphabet = Array.from('๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ');
|
451
452
|
const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
|
452
|
-
const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
|
453
|
+
const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
|
454
|
+
const codePoint = c.codePointAt(0);
|
455
|
+
if (codePoint == null) {
|
456
|
+
throw new Error(`Invalid character: ${c}`);
|
457
|
+
}
|
458
|
+
p[codePoint] = i;
|
459
|
+
return p;
|
460
|
+
}, ([])));
|
453
461
|
function encode$4(data) {
|
454
462
|
return data.reduce((p, c) => {
|
455
463
|
p += alphabetBytesToChars[c];
|
@@ -459,8 +467,12 @@ function encode$4(data) {
|
|
459
467
|
function decode$5(str) {
|
460
468
|
const byts = [];
|
461
469
|
for (const char of str) {
|
462
|
-
const
|
463
|
-
if (
|
470
|
+
const codePoint = char.codePointAt(0);
|
471
|
+
if (codePoint == null) {
|
472
|
+
throw new Error(`Invalid character: ${char}`);
|
473
|
+
}
|
474
|
+
const byt = alphabetCharsToBytes[codePoint];
|
475
|
+
if (byt == null) {
|
464
476
|
throw new Error(`Non-base256emoji character: ${char}`);
|
465
477
|
}
|
466
478
|
byts.push(byt);
|
@@ -733,7 +745,7 @@ function encodingLength$1(int) {
|
|
733
745
|
/**
|
734
746
|
* Creates a multihash digest.
|
735
747
|
*/
|
736
|
-
function create
|
748
|
+
function create(code, digest) {
|
737
749
|
const size = digest.byteLength;
|
738
750
|
const sizeOffset = encodingLength$1(code);
|
739
751
|
const digestOffset = sizeOffset + encodingLength$1(size);
|
@@ -792,7 +804,7 @@ const code = 0x0;
|
|
792
804
|
const name = 'identity';
|
793
805
|
const encode$2 = coerce;
|
794
806
|
function digest(input) {
|
795
|
-
return create
|
807
|
+
return create(code, encode$2(input));
|
796
808
|
}
|
797
809
|
const identity = { code, name, encode: encode$2, digest };
|
798
810
|
|
@@ -816,9 +828,9 @@ class Hasher {
|
|
816
828
|
if (input instanceof Uint8Array) {
|
817
829
|
const result = this.encode(input);
|
818
830
|
return result instanceof Uint8Array
|
819
|
-
? create
|
831
|
+
? create(this.code, result)
|
820
832
|
/* c8 ignore next 1 */
|
821
|
-
: result.then(digest => create
|
833
|
+
: result.then(digest => create(this.code, digest));
|
822
834
|
}
|
823
835
|
else {
|
824
836
|
throw Error('Unknown type, must be binary type');
|
@@ -918,7 +930,7 @@ class CID {
|
|
918
930
|
switch (this.version) {
|
919
931
|
case 0: {
|
920
932
|
const { code, digest } = this.multihash;
|
921
|
-
const multihash = create
|
933
|
+
const multihash = create(code, digest);
|
922
934
|
return (CID.createV1(this.code, multihash));
|
923
935
|
}
|
924
936
|
case 1: {
|
@@ -1148,9 +1160,13 @@ function parseCIDtoBytes(source, base) {
|
|
1148
1160
|
const decoder = base ?? base32;
|
1149
1161
|
return [base32.prefix, decoder.decode(source)];
|
1150
1162
|
}
|
1163
|
+
case base36.prefix: {
|
1164
|
+
const decoder = base ?? base36;
|
1165
|
+
return [base36.prefix, decoder.decode(source)];
|
1166
|
+
}
|
1151
1167
|
default: {
|
1152
1168
|
if (base == null) {
|
1153
|
-
throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');
|
1169
|
+
throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
|
1154
1170
|
}
|
1155
1171
|
return [source[0], base.decode(source)];
|
1156
1172
|
}
|
@@ -3056,7 +3072,7 @@ async function sign$1(message, privateKey) {
|
|
3056
3072
|
function keccak256(input) {
|
3057
3073
|
return new Uint8Array(sha3.keccak256.arrayBuffer(input));
|
3058
3074
|
}
|
3059
|
-
function compressPublicKey
|
3075
|
+
function compressPublicKey(publicKey) {
|
3060
3076
|
if (publicKey.length === 64) {
|
3061
3077
|
publicKey = concat$2([new Uint8Array([4]), publicKey], 65);
|
3062
3078
|
}
|
@@ -3125,23 +3141,6 @@ const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLen
|
|
3125
3141
|
// The rotate right (circular right shift) operation for uint32
|
3126
3142
|
const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
|
3127
3143
|
new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
|
3128
|
-
// There is no setImmediate in browser and setTimeout is slow.
|
3129
|
-
// call of async fn will return Promise, which will be fullfiled only on
|
3130
|
-
// next scheduler queue processing step and this is exactly what we need.
|
3131
|
-
const nextTick = async () => { };
|
3132
|
-
// Returns control to thread each 'tick' ms to avoid blocking
|
3133
|
-
async function asyncLoop(iters, tick, cb) {
|
3134
|
-
let ts = Date.now();
|
3135
|
-
for (let i = 0; i < iters; i++) {
|
3136
|
-
cb(i);
|
3137
|
-
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
|
3138
|
-
const diff = Date.now() - ts;
|
3139
|
-
if (diff >= 0 && diff < tick)
|
3140
|
-
continue;
|
3141
|
-
await nextTick();
|
3142
|
-
ts += diff;
|
3143
|
-
}
|
3144
|
-
}
|
3145
3144
|
/**
|
3146
3145
|
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
3147
3146
|
*/
|
@@ -3186,13 +3185,6 @@ class Hash {
|
|
3186
3185
|
return this._cloneInto();
|
3187
3186
|
}
|
3188
3187
|
}
|
3189
|
-
const toStr = {}.toString;
|
3190
|
-
function checkOpts(defaults, opts) {
|
3191
|
-
if (opts !== undefined && toStr.call(opts) !== '[object Object]')
|
3192
|
-
throw new Error('Options should be object or undefined');
|
3193
|
-
const merged = Object.assign(defaults, opts);
|
3194
|
-
return merged;
|
3195
|
-
}
|
3196
3188
|
function wrapConstructor(hashCons) {
|
3197
3189
|
const hashC = (msg) => hashCons().update(toBytes$1(msg)).digest();
|
3198
3190
|
const tmp = hashCons();
|
@@ -3204,14 +3196,20 @@ function wrapConstructor(hashCons) {
|
|
3204
3196
|
/**
|
3205
3197
|
* Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
|
3206
3198
|
*/
|
3207
|
-
function randomBytes
|
3199
|
+
function randomBytes(bytesLength = 32) {
|
3208
3200
|
if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
|
3209
3201
|
return crypto$1.getRandomValues(new Uint8Array(bytesLength));
|
3210
3202
|
}
|
3203
|
+
// Legacy Node.js compatibility
|
3204
|
+
if (crypto$1 && typeof crypto$1.randomBytes === 'function') {
|
3205
|
+
return crypto$1.randomBytes(bytesLength);
|
3206
|
+
}
|
3211
3207
|
throw new Error('crypto.getRandomValues must be defined');
|
3212
3208
|
}
|
3213
3209
|
|
3214
|
-
|
3210
|
+
/**
|
3211
|
+
* Polyfill for Safari 14
|
3212
|
+
*/
|
3215
3213
|
function setBigUint64(view, byteOffset, value, isLE) {
|
3216
3214
|
if (typeof view.setBigUint64 === 'function')
|
3217
3215
|
return view.setBigUint64(byteOffset, value, isLE);
|
@@ -3224,9 +3222,13 @@ function setBigUint64(view, byteOffset, value, isLE) {
|
|
3224
3222
|
view.setUint32(byteOffset + h, wh, isLE);
|
3225
3223
|
view.setUint32(byteOffset + l, wl, isLE);
|
3226
3224
|
}
|
3227
|
-
|
3225
|
+
/**
|
3226
|
+
* Choice: a ? b : c
|
3227
|
+
*/
|
3228
3228
|
const Chi = (a, b, c) => (a & b) ^ (~a & c);
|
3229
|
-
|
3229
|
+
/**
|
3230
|
+
* Majority function, true if any two inputs is true
|
3231
|
+
*/
|
3230
3232
|
const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
|
3231
3233
|
/**
|
3232
3234
|
* Merkle-Damgard hash construction base class.
|
@@ -3621,7 +3623,7 @@ function requireMs () {
|
|
3621
3623
|
* @api public
|
3622
3624
|
*/
|
3623
3625
|
|
3624
|
-
ms = function(val, options) {
|
3626
|
+
ms = function (val, options) {
|
3625
3627
|
options = options || {};
|
3626
3628
|
var type = typeof val;
|
3627
3629
|
if (type === 'string' && val.length > 0) {
|
@@ -4340,34 +4342,6 @@ let Logger$1 = class Logger {
|
|
4340
4342
|
}
|
4341
4343
|
};
|
4342
4344
|
|
4343
|
-
const peerIdSymbol = Symbol.for('@libp2p/peer-id');
|
4344
|
-
|
4345
|
-
/**
|
4346
|
-
* When this error is thrown it means an operation was aborted,
|
4347
|
-
* usually in response to the `abort` event being emitted by an
|
4348
|
-
* AbortSignal.
|
4349
|
-
*/
|
4350
|
-
class CodeError extends Error {
|
4351
|
-
code;
|
4352
|
-
props;
|
4353
|
-
constructor(message, code, props) {
|
4354
|
-
super(message);
|
4355
|
-
this.code = code;
|
4356
|
-
this.name = props?.name ?? 'CodeError';
|
4357
|
-
this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
|
4358
|
-
}
|
4359
|
-
}
|
4360
|
-
class AggregateCodeError extends AggregateError {
|
4361
|
-
code;
|
4362
|
-
props;
|
4363
|
-
constructor(errors, message, code, props) {
|
4364
|
-
super(errors, message);
|
4365
|
-
this.code = code;
|
4366
|
-
this.name = props?.name ?? 'AggregateCodeError';
|
4367
|
-
this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
|
4368
|
-
}
|
4369
|
-
}
|
4370
|
-
|
4371
4345
|
/**
|
4372
4346
|
* Returns true if the two passed Uint8Arrays have the same content
|
4373
4347
|
*/
|
@@ -5425,6 +5399,12 @@ const DNS_CODES = [
|
|
5425
5399
|
getProtocol('dns6').code,
|
5426
5400
|
getProtocol('dnsaddr').code
|
5427
5401
|
];
|
5402
|
+
class NoAvailableResolverError extends Error {
|
5403
|
+
constructor(message = 'No available resolver') {
|
5404
|
+
super(message);
|
5405
|
+
this.name = 'NoAvailableResolverError';
|
5406
|
+
}
|
5407
|
+
}
|
5428
5408
|
/**
|
5429
5409
|
* Creates a {@link Multiaddr} from a {@link MultiaddrInput}
|
5430
5410
|
*/
|
@@ -5594,7 +5574,7 @@ class Multiaddr {
|
|
5594
5574
|
}
|
5595
5575
|
const resolver = resolvers.get(resolvableProto.name);
|
5596
5576
|
if (resolver == null) {
|
5597
|
-
throw new
|
5577
|
+
throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);
|
5598
5578
|
}
|
5599
5579
|
const result = await resolver(this, options);
|
5600
5580
|
return result.map(str => multiaddr(str));
|
@@ -5808,13 +5788,30 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
|
|
5808
5788
|
return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
|
5809
5789
|
}
|
5810
5790
|
|
5811
|
-
|
5812
|
-
|
5813
|
-
|
5791
|
+
/**
|
5792
|
+
* When this error is thrown it means an operation was aborted,
|
5793
|
+
* usually in response to the `abort` event being emitted by an
|
5794
|
+
* AbortSignal.
|
5795
|
+
*/
|
5796
|
+
/**
|
5797
|
+
* Thrown when invalid parameters are passed to a function or method call
|
5798
|
+
*/
|
5799
|
+
class InvalidParametersError extends Error {
|
5800
|
+
static name = 'InvalidParametersError';
|
5801
|
+
constructor(message = 'Invalid parameters') {
|
5802
|
+
super(message);
|
5803
|
+
this.name = 'InvalidParametersError';
|
5804
|
+
}
|
5805
|
+
}
|
5806
|
+
/**
|
5807
|
+
* Thrown when a public key is invalid
|
5808
|
+
*/
|
5809
|
+
class InvalidPublicKeyError extends Error {
|
5810
|
+
static name = 'InvalidPublicKeyError';
|
5811
|
+
constructor(message = 'Invalid public key') {
|
5812
|
+
super(message);
|
5813
|
+
this.name = 'InvalidPublicKeyError';
|
5814
5814
|
}
|
5815
|
-
return typeof thing.then === 'function' &&
|
5816
|
-
typeof thing.catch === 'function' &&
|
5817
|
-
typeof thing.finally === 'function';
|
5818
5815
|
}
|
5819
5816
|
|
5820
5817
|
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
@@ -6902,6 +6899,60 @@ function wNAF(c, bits) {
|
|
6902
6899
|
},
|
6903
6900
|
};
|
6904
6901
|
}
|
6902
|
+
/**
|
6903
|
+
* Pippenger algorithm for multi-scalar multiplication (MSM).
|
6904
|
+
* MSM is basically (Pa + Qb + Rc + ...).
|
6905
|
+
* 30x faster vs naive addition on L=4096, 10x faster with precomputes.
|
6906
|
+
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
6907
|
+
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
6908
|
+
* @param c Curve Point constructor
|
6909
|
+
* @param field field over CURVE.N - important that it's not over CURVE.P
|
6910
|
+
* @param points array of L curve points
|
6911
|
+
* @param scalars array of L scalars (aka private keys / bigints)
|
6912
|
+
*/
|
6913
|
+
function pippenger(c, field, points, scalars) {
|
6914
|
+
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
6915
|
+
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
6916
|
+
// TODO:
|
6917
|
+
// - https://eprint.iacr.org/2024/750.pdf
|
6918
|
+
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
6919
|
+
// 0 is accepted in scalars
|
6920
|
+
if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
|
6921
|
+
throw new Error('arrays of points and scalars must have equal length');
|
6922
|
+
scalars.forEach((s, i) => {
|
6923
|
+
if (!field.isValid(s))
|
6924
|
+
throw new Error(`wrong scalar at index ${i}`);
|
6925
|
+
});
|
6926
|
+
points.forEach((p, i) => {
|
6927
|
+
if (!(p instanceof c))
|
6928
|
+
throw new Error(`wrong point at index ${i}`);
|
6929
|
+
});
|
6930
|
+
const wbits = bitLen(BigInt(points.length));
|
6931
|
+
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
|
6932
|
+
const MASK = (1 << windowSize) - 1;
|
6933
|
+
const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array
|
6934
|
+
const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
|
6935
|
+
let sum = c.ZERO;
|
6936
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
6937
|
+
buckets.fill(c.ZERO);
|
6938
|
+
for (let j = 0; j < scalars.length; j++) {
|
6939
|
+
const scalar = scalars[j];
|
6940
|
+
const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));
|
6941
|
+
buckets[wbits] = buckets[wbits].add(points[j]);
|
6942
|
+
}
|
6943
|
+
let resI = c.ZERO; // not using this will do small speed-up, but will lose ct
|
6944
|
+
// Skip first bucket, because it is zero
|
6945
|
+
for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
|
6946
|
+
sumI = sumI.add(buckets[j]);
|
6947
|
+
resI = resI.add(sumI);
|
6948
|
+
}
|
6949
|
+
sum = sum.add(resI);
|
6950
|
+
if (i !== 0)
|
6951
|
+
for (let j = 0; j < windowSize; j++)
|
6952
|
+
sum = sum.double();
|
6953
|
+
}
|
6954
|
+
return sum;
|
6955
|
+
}
|
6905
6956
|
function validateBasic(curve) {
|
6906
6957
|
validateField(curve.Fp);
|
6907
6958
|
validateObject(curve, {
|
@@ -6956,6 +7007,7 @@ function twistedEdwards(curveDef) {
|
|
6956
7007
|
const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
|
6957
7008
|
const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
|
6958
7009
|
const modP = Fp.create; // Function overrides
|
7010
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
6959
7011
|
// sqrt(u/v)
|
6960
7012
|
const uvRatio = CURVE.uvRatio ||
|
6961
7013
|
((u, v) => {
|
@@ -7054,6 +7106,10 @@ function twistedEdwards(curveDef) {
|
|
7054
7106
|
const toInv = Fp.invertBatch(points.map((p) => p.ez));
|
7055
7107
|
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
|
7056
7108
|
}
|
7109
|
+
// Multiscalar Multiplication
|
7110
|
+
static msm(points, scalars) {
|
7111
|
+
return pippenger(Point, Fn, points, scalars);
|
7112
|
+
}
|
7057
7113
|
// "Private method", don't use it directly
|
7058
7114
|
_setWindowSize(windowSize) {
|
7059
7115
|
wnaf.setWindowSize(this, windowSize);
|
@@ -7429,7 +7485,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
|
|
7429
7485
|
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
|
7430
7486
|
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
|
7431
7487
|
hash: sha512,
|
7432
|
-
randomBytes
|
7488
|
+
randomBytes,
|
7433
7489
|
adjustScalarBytes,
|
7434
7490
|
// dom2
|
7435
7491
|
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
|
@@ -7442,176 +7498,46 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
|
|
7442
7498
|
const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
|
7443
7499
|
|
7444
7500
|
const PUBLIC_KEY_BYTE_LENGTH = 32;
|
7445
|
-
const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
|
7446
|
-
const KEYS_BYTE_LENGTH = 32;
|
7447
|
-
function generateKey$2() {
|
7448
|
-
// the actual private key (32 bytes)
|
7449
|
-
const privateKeyRaw = ed25519.utils.randomPrivateKey();
|
7450
|
-
const publicKey = ed25519.getPublicKey(privateKeyRaw);
|
7451
|
-
// concatenated the public key to the private key
|
7452
|
-
const privateKey = concatKeys(privateKeyRaw, publicKey);
|
7453
|
-
return {
|
7454
|
-
privateKey,
|
7455
|
-
publicKey
|
7456
|
-
};
|
7457
|
-
}
|
7458
|
-
/**
|
7459
|
-
* Generate keypair from a 32 byte uint8array
|
7460
|
-
*/
|
7461
|
-
function generateKeyFromSeed(seed) {
|
7462
|
-
if (seed.length !== KEYS_BYTE_LENGTH) {
|
7463
|
-
throw new TypeError('"seed" must be 32 bytes in length.');
|
7464
|
-
}
|
7465
|
-
else if (!(seed instanceof Uint8Array)) {
|
7466
|
-
throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
|
7467
|
-
}
|
7468
|
-
// based on node forges algorithm, the seed is used directly as private key
|
7469
|
-
const privateKeyRaw = seed;
|
7470
|
-
const publicKey = ed25519.getPublicKey(privateKeyRaw);
|
7471
|
-
const privateKey = concatKeys(privateKeyRaw, publicKey);
|
7472
|
-
return {
|
7473
|
-
privateKey,
|
7474
|
-
publicKey
|
7475
|
-
};
|
7476
|
-
}
|
7477
|
-
function hashAndSign$2(privateKey, msg) {
|
7478
|
-
const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
|
7479
|
-
return ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
|
7480
|
-
}
|
7481
7501
|
function hashAndVerify$2(publicKey, sig, msg) {
|
7482
7502
|
return ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
|
7483
7503
|
}
|
7484
|
-
function concatKeys(privateKeyRaw, publicKey) {
|
7485
|
-
const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
|
7486
|
-
for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
|
7487
|
-
privateKey[i] = privateKeyRaw[i];
|
7488
|
-
privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
|
7489
|
-
}
|
7490
|
-
return privateKey;
|
7491
|
-
}
|
7492
7504
|
|
7493
|
-
|
7494
|
-
|
7495
|
-
|
7496
|
-
|
7497
|
-
|
7498
|
-
const nativeCrypto = win.crypto;
|
7499
|
-
if (nativeCrypto?.subtle == null) {
|
7500
|
-
throw Object.assign(new Error('Missing Web Crypto API. ' +
|
7501
|
-
'The most likely cause of this error is that this page is being accessed ' +
|
7502
|
-
'from an insecure context (i.e. not HTTPS). For more information and ' +
|
7503
|
-
'possible resolutions see ' +
|
7504
|
-
'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });
|
7505
|
-
}
|
7506
|
-
return nativeCrypto;
|
7505
|
+
class Ed25519PublicKey {
|
7506
|
+
type = 'Ed25519';
|
7507
|
+
raw;
|
7508
|
+
constructor(key) {
|
7509
|
+
this.raw = ensureEd25519Key(key, PUBLIC_KEY_BYTE_LENGTH);
|
7507
7510
|
}
|
7508
|
-
|
7509
|
-
|
7510
|
-
|
7511
|
-
|
7512
|
-
|
7513
|
-
|
7514
|
-
|
7515
|
-
|
7516
|
-
|
7517
|
-
|
7518
|
-
|
7519
|
-
|
7520
|
-
const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
|
7521
|
-
// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
|
7522
|
-
function create(opts) {
|
7523
|
-
const algorithm = 'AES-GCM';
|
7524
|
-
let keyLength = 16;
|
7525
|
-
const nonceLength = 12;
|
7526
|
-
const digest = 'SHA-256';
|
7527
|
-
const saltLength = 16;
|
7528
|
-
const iterations = 32767;
|
7529
|
-
const crypto = webcrypto.get();
|
7530
|
-
keyLength *= 8; // Browser crypto uses bits instead of bytes
|
7531
|
-
/**
|
7532
|
-
* Uses the provided password to derive a pbkdf2 key. The key
|
7533
|
-
* will then be used to encrypt the data.
|
7534
|
-
*/
|
7535
|
-
async function encrypt(data, password) {
|
7536
|
-
const salt = crypto.getRandomValues(new Uint8Array(saltLength));
|
7537
|
-
const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));
|
7538
|
-
const aesGcm = { name: algorithm, iv: nonce };
|
7539
|
-
if (typeof password === 'string') {
|
7540
|
-
password = fromString(password);
|
7541
|
-
}
|
7542
|
-
let cryptoKey;
|
7543
|
-
if (password.length === 0) {
|
7544
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
|
7545
|
-
try {
|
7546
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7547
|
-
const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7548
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);
|
7549
|
-
}
|
7550
|
-
catch {
|
7551
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
|
7552
|
-
}
|
7553
|
-
}
|
7554
|
-
else {
|
7555
|
-
// Derive a key using PBKDF2.
|
7556
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7557
|
-
const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7558
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);
|
7559
|
-
}
|
7560
|
-
// Encrypt the string.
|
7561
|
-
const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);
|
7562
|
-
return concat$1([salt, aesGcm.iv, new Uint8Array(ciphertext)]);
|
7563
|
-
}
|
7564
|
-
/**
|
7565
|
-
* Uses the provided password to derive a pbkdf2 key. The key
|
7566
|
-
* will then be used to decrypt the data. The options used to create
|
7567
|
-
* this decryption cipher must be the same as those used to create
|
7568
|
-
* the encryption cipher.
|
7569
|
-
*/
|
7570
|
-
async function decrypt(data, password) {
|
7571
|
-
const salt = data.subarray(0, saltLength);
|
7572
|
-
const nonce = data.subarray(saltLength, saltLength + nonceLength);
|
7573
|
-
const ciphertext = data.subarray(saltLength + nonceLength);
|
7574
|
-
const aesGcm = { name: algorithm, iv: nonce };
|
7575
|
-
if (typeof password === 'string') {
|
7576
|
-
password = fromString(password);
|
7577
|
-
}
|
7578
|
-
let cryptoKey;
|
7579
|
-
if (password.length === 0) {
|
7580
|
-
try {
|
7581
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7582
|
-
const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7583
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);
|
7584
|
-
}
|
7585
|
-
catch {
|
7586
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);
|
7587
|
-
}
|
7511
|
+
toMultihash() {
|
7512
|
+
return identity.digest(publicKeyToProtobuf(this));
|
7513
|
+
}
|
7514
|
+
toCID() {
|
7515
|
+
return CID.createV1(114, this.toMultihash());
|
7516
|
+
}
|
7517
|
+
toString() {
|
7518
|
+
return base58btc.encode(this.toMultihash().bytes).substring(1);
|
7519
|
+
}
|
7520
|
+
equals(key) {
|
7521
|
+
if (key == null || !(key.raw instanceof Uint8Array)) {
|
7522
|
+
return false;
|
7588
7523
|
}
|
7589
|
-
|
7590
|
-
|
7591
|
-
|
7592
|
-
|
7593
|
-
|
7594
|
-
}
|
7595
|
-
// Decrypt the string.
|
7596
|
-
const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);
|
7597
|
-
return new Uint8Array(plaintext);
|
7598
|
-
}
|
7599
|
-
const cipher = {
|
7600
|
-
encrypt,
|
7601
|
-
decrypt
|
7602
|
-
};
|
7603
|
-
return cipher;
|
7524
|
+
return equals(this.raw, key.raw);
|
7525
|
+
}
|
7526
|
+
verify(data, sig) {
|
7527
|
+
return hashAndVerify$2(this.raw, sig, data);
|
7528
|
+
}
|
7604
7529
|
}
|
7605
7530
|
|
7606
|
-
|
7607
|
-
|
7608
|
-
|
7609
|
-
|
7610
|
-
|
7611
|
-
|
7612
|
-
|
7613
|
-
|
7614
|
-
|
7531
|
+
function unmarshalEd25519PublicKey(bytes) {
|
7532
|
+
bytes = ensureEd25519Key(bytes, PUBLIC_KEY_BYTE_LENGTH);
|
7533
|
+
return new Ed25519PublicKey(bytes);
|
7534
|
+
}
|
7535
|
+
function ensureEd25519Key(key, length) {
|
7536
|
+
key = Uint8Array.from(key ?? []);
|
7537
|
+
if (key.length !== length) {
|
7538
|
+
throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);
|
7539
|
+
}
|
7540
|
+
return key;
|
7615
7541
|
}
|
7616
7542
|
|
7617
7543
|
const f32 = new Float32Array([-0]);
|
@@ -8820,13 +8746,13 @@ var KeyType;
|
|
8820
8746
|
(function (KeyType) {
|
8821
8747
|
KeyType["RSA"] = "RSA";
|
8822
8748
|
KeyType["Ed25519"] = "Ed25519";
|
8823
|
-
KeyType["
|
8749
|
+
KeyType["secp256k1"] = "secp256k1";
|
8824
8750
|
})(KeyType || (KeyType = {}));
|
8825
8751
|
var __KeyTypeValues;
|
8826
8752
|
(function (__KeyTypeValues) {
|
8827
8753
|
__KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
|
8828
8754
|
__KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
|
8829
|
-
__KeyTypeValues[__KeyTypeValues["
|
8755
|
+
__KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
|
8830
8756
|
})(__KeyTypeValues || (__KeyTypeValues = {}));
|
8831
8757
|
(function (KeyType) {
|
8832
8758
|
KeyType.codec = () => {
|
@@ -8853,21 +8779,24 @@ var PublicKey;
|
|
8853
8779
|
if (opts.lengthDelimited !== false) {
|
8854
8780
|
w.ldelim();
|
8855
8781
|
}
|
8856
|
-
}, (reader, length) => {
|
8782
|
+
}, (reader, length, opts = {}) => {
|
8857
8783
|
const obj = {};
|
8858
8784
|
const end = length == null ? reader.len : reader.pos + length;
|
8859
8785
|
while (reader.pos < end) {
|
8860
8786
|
const tag = reader.uint32();
|
8861
8787
|
switch (tag >>> 3) {
|
8862
|
-
case 1:
|
8788
|
+
case 1: {
|
8863
8789
|
obj.Type = KeyType.codec().decode(reader);
|
8864
8790
|
break;
|
8865
|
-
|
8791
|
+
}
|
8792
|
+
case 2: {
|
8866
8793
|
obj.Data = reader.bytes();
|
8867
8794
|
break;
|
8868
|
-
|
8795
|
+
}
|
8796
|
+
default: {
|
8869
8797
|
reader.skipType(tag & 7);
|
8870
8798
|
break;
|
8799
|
+
}
|
8871
8800
|
}
|
8872
8801
|
}
|
8873
8802
|
return obj;
|
@@ -8878,8 +8807,8 @@ var PublicKey;
|
|
8878
8807
|
PublicKey.encode = (obj) => {
|
8879
8808
|
return encodeMessage(obj, PublicKey.codec());
|
8880
8809
|
};
|
8881
|
-
PublicKey.decode = (buf) => {
|
8882
|
-
return decodeMessage(buf, PublicKey.codec());
|
8810
|
+
PublicKey.decode = (buf, opts) => {
|
8811
|
+
return decodeMessage(buf, PublicKey.codec(), opts);
|
8883
8812
|
};
|
8884
8813
|
})(PublicKey || (PublicKey = {}));
|
8885
8814
|
var PrivateKey;
|
@@ -8902,21 +8831,24 @@ var PrivateKey;
|
|
8902
8831
|
if (opts.lengthDelimited !== false) {
|
8903
8832
|
w.ldelim();
|
8904
8833
|
}
|
8905
|
-
}, (reader, length) => {
|
8834
|
+
}, (reader, length, opts = {}) => {
|
8906
8835
|
const obj = {};
|
8907
8836
|
const end = length == null ? reader.len : reader.pos + length;
|
8908
8837
|
while (reader.pos < end) {
|
8909
8838
|
const tag = reader.uint32();
|
8910
8839
|
switch (tag >>> 3) {
|
8911
|
-
case 1:
|
8840
|
+
case 1: {
|
8912
8841
|
obj.Type = KeyType.codec().decode(reader);
|
8913
8842
|
break;
|
8914
|
-
|
8843
|
+
}
|
8844
|
+
case 2: {
|
8915
8845
|
obj.Data = reader.bytes();
|
8916
8846
|
break;
|
8917
|
-
|
8847
|
+
}
|
8848
|
+
default: {
|
8918
8849
|
reader.skipType(tag & 7);
|
8919
8850
|
break;
|
8851
|
+
}
|
8920
8852
|
}
|
8921
8853
|
}
|
8922
8854
|
return obj;
|
@@ -8927,393 +8859,122 @@ var PrivateKey;
|
|
8927
8859
|
PrivateKey.encode = (obj) => {
|
8928
8860
|
return encodeMessage(obj, PrivateKey.codec());
|
8929
8861
|
};
|
8930
|
-
PrivateKey.decode = (buf) => {
|
8931
|
-
return decodeMessage(buf, PrivateKey.codec());
|
8862
|
+
PrivateKey.decode = (buf, opts) => {
|
8863
|
+
return decodeMessage(buf, PrivateKey.codec(), opts);
|
8932
8864
|
};
|
8933
8865
|
})(PrivateKey || (PrivateKey = {}));
|
8934
8866
|
|
8935
|
-
|
8936
|
-
|
8937
|
-
|
8938
|
-
|
8939
|
-
|
8940
|
-
|
8941
|
-
|
8942
|
-
|
8943
|
-
|
8944
|
-
|
8945
|
-
|
8946
|
-
|
8947
|
-
|
8948
|
-
|
8949
|
-
|
8950
|
-
|
8951
|
-
|
8952
|
-
|
8953
|
-
|
8867
|
+
/*!
|
8868
|
+
* MIT License
|
8869
|
+
*
|
8870
|
+
* Copyright (c) 2017-2022 Peculiar Ventures, LLC
|
8871
|
+
*
|
8872
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
8873
|
+
* of this software and associated documentation files (the "Software"), to deal
|
8874
|
+
* in the Software without restriction, including without limitation the rights
|
8875
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
8876
|
+
* copies of the Software, and to permit persons to whom the Software is
|
8877
|
+
* furnished to do so, subject to the following conditions:
|
8878
|
+
*
|
8879
|
+
* The above copyright notice and this permission notice shall be included in all
|
8880
|
+
* copies or substantial portions of the Software.
|
8881
|
+
*
|
8882
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
8883
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
8884
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
8885
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
8886
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
8887
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
8888
|
+
* SOFTWARE.
|
8889
|
+
*
|
8890
|
+
*/
|
8891
|
+
|
8892
|
+
const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
|
8893
|
+
class BufferSourceConverter {
|
8894
|
+
static isArrayBuffer(data) {
|
8895
|
+
return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
|
8954
8896
|
}
|
8955
|
-
|
8956
|
-
|
8957
|
-
|
8958
|
-
return p.then(({ bytes }) => bytes);
|
8897
|
+
static toArrayBuffer(data) {
|
8898
|
+
if (this.isArrayBuffer(data)) {
|
8899
|
+
return data;
|
8959
8900
|
}
|
8960
|
-
|
8961
|
-
|
8962
|
-
}
|
8963
|
-
|
8964
|
-
|
8965
|
-
|
8966
|
-
|
8967
|
-
|
8968
|
-
|
8969
|
-
this._key = ensureKey(key, PRIVATE_KEY_BYTE_LENGTH);
|
8970
|
-
this._publicKey = ensureKey(publicKey, PUBLIC_KEY_BYTE_LENGTH);
|
8971
|
-
}
|
8972
|
-
sign(message) {
|
8973
|
-
return hashAndSign$2(this._key, message);
|
8901
|
+
if (data.byteLength === data.buffer.byteLength) {
|
8902
|
+
return data.buffer;
|
8903
|
+
}
|
8904
|
+
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
|
8905
|
+
return data.buffer;
|
8906
|
+
}
|
8907
|
+
return this.toUint8Array(data.buffer)
|
8908
|
+
.slice(data.byteOffset, data.byteOffset + data.byteLength)
|
8909
|
+
.buffer;
|
8974
8910
|
}
|
8975
|
-
|
8976
|
-
return
|
8911
|
+
static toUint8Array(data) {
|
8912
|
+
return this.toView(data, Uint8Array);
|
8977
8913
|
}
|
8978
|
-
|
8979
|
-
|
8914
|
+
static toView(data, type) {
|
8915
|
+
if (data.constructor === type) {
|
8916
|
+
return data;
|
8917
|
+
}
|
8918
|
+
if (this.isArrayBuffer(data)) {
|
8919
|
+
return new type(data);
|
8920
|
+
}
|
8921
|
+
if (this.isArrayBufferView(data)) {
|
8922
|
+
return new type(data.buffer, data.byteOffset, data.byteLength);
|
8923
|
+
}
|
8924
|
+
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
|
8980
8925
|
}
|
8981
|
-
|
8982
|
-
return
|
8983
|
-
|
8984
|
-
Data: this.marshal()
|
8985
|
-
}).subarray();
|
8926
|
+
static isBufferSource(data) {
|
8927
|
+
return this.isArrayBufferView(data)
|
8928
|
+
|| this.isArrayBuffer(data);
|
8986
8929
|
}
|
8987
|
-
|
8988
|
-
return
|
8930
|
+
static isArrayBufferView(data) {
|
8931
|
+
return ArrayBuffer.isView(data)
|
8932
|
+
|| (data && this.isArrayBuffer(data.buffer));
|
8989
8933
|
}
|
8990
|
-
|
8991
|
-
const
|
8992
|
-
|
8993
|
-
if (
|
8994
|
-
|
8934
|
+
static isEqual(a, b) {
|
8935
|
+
const aView = BufferSourceConverter.toUint8Array(a);
|
8936
|
+
const bView = BufferSourceConverter.toUint8Array(b);
|
8937
|
+
if (aView.length !== bView.byteLength) {
|
8938
|
+
return false;
|
8995
8939
|
}
|
8996
|
-
|
8997
|
-
|
8940
|
+
for (let i = 0; i < aView.length; i++) {
|
8941
|
+
if (aView[i] !== bView[i]) {
|
8942
|
+
return false;
|
8943
|
+
}
|
8998
8944
|
}
|
8999
|
-
return
|
9000
|
-
}
|
9001
|
-
/**
|
9002
|
-
* Gets the ID of the key.
|
9003
|
-
*
|
9004
|
-
* The key id is the base58 encoding of the identity multihash containing its public key.
|
9005
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
9006
|
-
* of the PKCS SubjectPublicKeyInfo.
|
9007
|
-
*
|
9008
|
-
* @returns {Promise<string>}
|
9009
|
-
*/
|
9010
|
-
async id() {
|
9011
|
-
const encoding = identity.digest(this.public.bytes);
|
9012
|
-
return base58btc.encode(encoding.bytes).substring(1);
|
8945
|
+
return true;
|
9013
8946
|
}
|
9014
|
-
|
9015
|
-
|
9016
|
-
|
9017
|
-
|
9018
|
-
|
9019
|
-
|
8947
|
+
static concat(...args) {
|
8948
|
+
let buffers;
|
8949
|
+
if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
|
8950
|
+
buffers = args[0];
|
8951
|
+
}
|
8952
|
+
else if (Array.isArray(args[0]) && args[1] instanceof Function) {
|
8953
|
+
buffers = args[0];
|
9020
8954
|
}
|
9021
8955
|
else {
|
9022
|
-
|
8956
|
+
if (args[args.length - 1] instanceof Function) {
|
8957
|
+
buffers = args.slice(0, args.length - 1);
|
8958
|
+
}
|
8959
|
+
else {
|
8960
|
+
buffers = args;
|
8961
|
+
}
|
9023
8962
|
}
|
9024
|
-
|
9025
|
-
|
9026
|
-
|
9027
|
-
|
9028
|
-
|
9029
|
-
|
9030
|
-
const
|
9031
|
-
|
9032
|
-
|
9033
|
-
|
9034
|
-
|
9035
|
-
|
9036
|
-
|
9037
|
-
|
9038
|
-
|
9039
|
-
function unmarshalEd25519PublicKey(bytes) {
|
9040
|
-
bytes = ensureKey(bytes, PUBLIC_KEY_BYTE_LENGTH);
|
9041
|
-
return new Ed25519PublicKey(bytes);
|
9042
|
-
}
|
9043
|
-
async function generateKeyPair$2() {
|
9044
|
-
const { privateKey, publicKey } = generateKey$2();
|
9045
|
-
return new Ed25519PrivateKey(privateKey, publicKey);
|
9046
|
-
}
|
9047
|
-
async function generateKeyPairFromSeed(seed) {
|
9048
|
-
const { privateKey, publicKey } = generateKeyFromSeed(seed);
|
9049
|
-
return new Ed25519PrivateKey(privateKey, publicKey);
|
9050
|
-
}
|
9051
|
-
function ensureKey(key, length) {
|
9052
|
-
key = Uint8Array.from(key ?? []);
|
9053
|
-
if (key.length !== length) {
|
9054
|
-
throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
|
9055
|
-
}
|
9056
|
-
return key;
|
9057
|
-
}
|
9058
|
-
|
9059
|
-
var Ed25519 = /*#__PURE__*/Object.freeze({
|
9060
|
-
__proto__: null,
|
9061
|
-
Ed25519PrivateKey: Ed25519PrivateKey,
|
9062
|
-
Ed25519PublicKey: Ed25519PublicKey,
|
9063
|
-
generateKeyPair: generateKeyPair$2,
|
9064
|
-
generateKeyPairFromSeed: generateKeyPairFromSeed,
|
9065
|
-
unmarshalEd25519PrivateKey: unmarshalEd25519PrivateKey,
|
9066
|
-
unmarshalEd25519PublicKey: unmarshalEd25519PublicKey
|
9067
|
-
});
|
9068
|
-
|
9069
|
-
/**
|
9070
|
-
* Generates a Uint8Array with length `number` populated by random bytes
|
9071
|
-
*/
|
9072
|
-
function randomBytes(length) {
|
9073
|
-
if (isNaN(length) || length <= 0) {
|
9074
|
-
throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
|
9075
|
-
}
|
9076
|
-
return randomBytes$1(length);
|
9077
|
-
}
|
9078
|
-
|
9079
|
-
// HMAC (RFC 2104)
|
9080
|
-
class HMAC extends Hash {
|
9081
|
-
constructor(hash$1, _key) {
|
9082
|
-
super();
|
9083
|
-
this.finished = false;
|
9084
|
-
this.destroyed = false;
|
9085
|
-
hash(hash$1);
|
9086
|
-
const key = toBytes$1(_key);
|
9087
|
-
this.iHash = hash$1.create();
|
9088
|
-
if (typeof this.iHash.update !== 'function')
|
9089
|
-
throw new Error('Expected instance of class which extends utils.Hash');
|
9090
|
-
this.blockLen = this.iHash.blockLen;
|
9091
|
-
this.outputLen = this.iHash.outputLen;
|
9092
|
-
const blockLen = this.blockLen;
|
9093
|
-
const pad = new Uint8Array(blockLen);
|
9094
|
-
// blockLen can be bigger than outputLen
|
9095
|
-
pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
|
9096
|
-
for (let i = 0; i < pad.length; i++)
|
9097
|
-
pad[i] ^= 0x36;
|
9098
|
-
this.iHash.update(pad);
|
9099
|
-
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
|
9100
|
-
this.oHash = hash$1.create();
|
9101
|
-
// Undo internal XOR && apply outer XOR
|
9102
|
-
for (let i = 0; i < pad.length; i++)
|
9103
|
-
pad[i] ^= 0x36 ^ 0x5c;
|
9104
|
-
this.oHash.update(pad);
|
9105
|
-
pad.fill(0);
|
9106
|
-
}
|
9107
|
-
update(buf) {
|
9108
|
-
exists(this);
|
9109
|
-
this.iHash.update(buf);
|
9110
|
-
return this;
|
9111
|
-
}
|
9112
|
-
digestInto(out) {
|
9113
|
-
exists(this);
|
9114
|
-
bytes(out, this.outputLen);
|
9115
|
-
this.finished = true;
|
9116
|
-
this.iHash.digestInto(out);
|
9117
|
-
this.oHash.update(out);
|
9118
|
-
this.oHash.digestInto(out);
|
9119
|
-
this.destroy();
|
9120
|
-
}
|
9121
|
-
digest() {
|
9122
|
-
const out = new Uint8Array(this.oHash.outputLen);
|
9123
|
-
this.digestInto(out);
|
9124
|
-
return out;
|
9125
|
-
}
|
9126
|
-
_cloneInto(to) {
|
9127
|
-
// Create new instance without calling constructor since key already in state and we don't know it.
|
9128
|
-
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
9129
|
-
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
9130
|
-
to = to;
|
9131
|
-
to.finished = finished;
|
9132
|
-
to.destroyed = destroyed;
|
9133
|
-
to.blockLen = blockLen;
|
9134
|
-
to.outputLen = outputLen;
|
9135
|
-
to.oHash = oHash._cloneInto(to.oHash);
|
9136
|
-
to.iHash = iHash._cloneInto(to.iHash);
|
9137
|
-
return to;
|
9138
|
-
}
|
9139
|
-
destroy() {
|
9140
|
-
this.destroyed = true;
|
9141
|
-
this.oHash.destroy();
|
9142
|
-
this.iHash.destroy();
|
9143
|
-
}
|
9144
|
-
}
|
9145
|
-
/**
|
9146
|
-
* HMAC: RFC2104 message authentication code.
|
9147
|
-
* @param hash - function that would be used e.g. sha256
|
9148
|
-
* @param key - message key
|
9149
|
-
* @param message - message data
|
9150
|
-
*/
|
9151
|
-
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
9152
|
-
hmac.create = (hash, key) => new HMAC(hash, key);
|
9153
|
-
|
9154
|
-
// Common prologue and epilogue for sync/async functions
|
9155
|
-
function pbkdf2Init(hash$1, _password, _salt, _opts) {
|
9156
|
-
hash(hash$1);
|
9157
|
-
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
|
9158
|
-
const { c, dkLen, asyncTick } = opts;
|
9159
|
-
number(c);
|
9160
|
-
number(dkLen);
|
9161
|
-
number(asyncTick);
|
9162
|
-
if (c < 1)
|
9163
|
-
throw new Error('PBKDF2: iterations (c) should be >= 1');
|
9164
|
-
const password = toBytes$1(_password);
|
9165
|
-
const salt = toBytes$1(_salt);
|
9166
|
-
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
|
9167
|
-
const DK = new Uint8Array(dkLen);
|
9168
|
-
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
9169
|
-
const PRF = hmac.create(hash$1, password);
|
9170
|
-
const PRFSalt = PRF._cloneInto().update(salt);
|
9171
|
-
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
|
9172
|
-
}
|
9173
|
-
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
|
9174
|
-
PRF.destroy();
|
9175
|
-
PRFSalt.destroy();
|
9176
|
-
if (prfW)
|
9177
|
-
prfW.destroy();
|
9178
|
-
u.fill(0);
|
9179
|
-
return DK;
|
9180
|
-
}
|
9181
|
-
async function pbkdf2Async(hash, password, salt, opts) {
|
9182
|
-
const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
|
9183
|
-
let prfW; // Working copy
|
9184
|
-
const arr = new Uint8Array(4);
|
9185
|
-
const view = createView(arr);
|
9186
|
-
const u = new Uint8Array(PRF.outputLen);
|
9187
|
-
// DK = T1 + T2 + โฏ + Tdklen/hlen
|
9188
|
-
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
|
9189
|
-
// Ti = F(Password, Salt, c, i)
|
9190
|
-
const Ti = DK.subarray(pos, pos + PRF.outputLen);
|
9191
|
-
view.setInt32(0, ti, false);
|
9192
|
-
// F(Password, Salt, c, i) = U1 ^ U2 ^ โฏ ^ Uc
|
9193
|
-
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
9194
|
-
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
|
9195
|
-
Ti.set(u.subarray(0, Ti.length));
|
9196
|
-
await asyncLoop(c - 1, asyncTick, () => {
|
9197
|
-
// Uc = PRF(Password, Ucโ1)
|
9198
|
-
PRF._cloneInto(prfW).update(u).digestInto(u);
|
9199
|
-
for (let i = 0; i < Ti.length; i++)
|
9200
|
-
Ti[i] ^= u[i];
|
9201
|
-
});
|
9202
|
-
}
|
9203
|
-
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
|
9204
|
-
}
|
9205
|
-
|
9206
|
-
/*!
|
9207
|
-
* MIT License
|
9208
|
-
*
|
9209
|
-
* Copyright (c) 2017-2022 Peculiar Ventures, LLC
|
9210
|
-
*
|
9211
|
-
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
9212
|
-
* of this software and associated documentation files (the "Software"), to deal
|
9213
|
-
* in the Software without restriction, including without limitation the rights
|
9214
|
-
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9215
|
-
* copies of the Software, and to permit persons to whom the Software is
|
9216
|
-
* furnished to do so, subject to the following conditions:
|
9217
|
-
*
|
9218
|
-
* The above copyright notice and this permission notice shall be included in all
|
9219
|
-
* copies or substantial portions of the Software.
|
9220
|
-
*
|
9221
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
9222
|
-
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
9223
|
-
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
9224
|
-
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
9225
|
-
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
9226
|
-
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
9227
|
-
* SOFTWARE.
|
9228
|
-
*
|
9229
|
-
*/
|
9230
|
-
|
9231
|
-
const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
|
9232
|
-
class BufferSourceConverter {
|
9233
|
-
static isArrayBuffer(data) {
|
9234
|
-
return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
|
9235
|
-
}
|
9236
|
-
static toArrayBuffer(data) {
|
9237
|
-
if (this.isArrayBuffer(data)) {
|
9238
|
-
return data;
|
9239
|
-
}
|
9240
|
-
if (data.byteLength === data.buffer.byteLength) {
|
9241
|
-
return data.buffer;
|
9242
|
-
}
|
9243
|
-
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
|
9244
|
-
return data.buffer;
|
9245
|
-
}
|
9246
|
-
return this.toUint8Array(data.buffer)
|
9247
|
-
.slice(data.byteOffset, data.byteOffset + data.byteLength)
|
9248
|
-
.buffer;
|
9249
|
-
}
|
9250
|
-
static toUint8Array(data) {
|
9251
|
-
return this.toView(data, Uint8Array);
|
9252
|
-
}
|
9253
|
-
static toView(data, type) {
|
9254
|
-
if (data.constructor === type) {
|
9255
|
-
return data;
|
9256
|
-
}
|
9257
|
-
if (this.isArrayBuffer(data)) {
|
9258
|
-
return new type(data);
|
9259
|
-
}
|
9260
|
-
if (this.isArrayBufferView(data)) {
|
9261
|
-
return new type(data.buffer, data.byteOffset, data.byteLength);
|
9262
|
-
}
|
9263
|
-
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
|
9264
|
-
}
|
9265
|
-
static isBufferSource(data) {
|
9266
|
-
return this.isArrayBufferView(data)
|
9267
|
-
|| this.isArrayBuffer(data);
|
9268
|
-
}
|
9269
|
-
static isArrayBufferView(data) {
|
9270
|
-
return ArrayBuffer.isView(data)
|
9271
|
-
|| (data && this.isArrayBuffer(data.buffer));
|
9272
|
-
}
|
9273
|
-
static isEqual(a, b) {
|
9274
|
-
const aView = BufferSourceConverter.toUint8Array(a);
|
9275
|
-
const bView = BufferSourceConverter.toUint8Array(b);
|
9276
|
-
if (aView.length !== bView.byteLength) {
|
9277
|
-
return false;
|
9278
|
-
}
|
9279
|
-
for (let i = 0; i < aView.length; i++) {
|
9280
|
-
if (aView[i] !== bView[i]) {
|
9281
|
-
return false;
|
9282
|
-
}
|
9283
|
-
}
|
9284
|
-
return true;
|
9285
|
-
}
|
9286
|
-
static concat(...args) {
|
9287
|
-
let buffers;
|
9288
|
-
if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
|
9289
|
-
buffers = args[0];
|
9290
|
-
}
|
9291
|
-
else if (Array.isArray(args[0]) && args[1] instanceof Function) {
|
9292
|
-
buffers = args[0];
|
9293
|
-
}
|
9294
|
-
else {
|
9295
|
-
if (args[args.length - 1] instanceof Function) {
|
9296
|
-
buffers = args.slice(0, args.length - 1);
|
9297
|
-
}
|
9298
|
-
else {
|
9299
|
-
buffers = args;
|
9300
|
-
}
|
9301
|
-
}
|
9302
|
-
let size = 0;
|
9303
|
-
for (const buffer of buffers) {
|
9304
|
-
size += buffer.byteLength;
|
9305
|
-
}
|
9306
|
-
const res = new Uint8Array(size);
|
9307
|
-
let offset = 0;
|
9308
|
-
for (const buffer of buffers) {
|
9309
|
-
const view = this.toUint8Array(buffer);
|
9310
|
-
res.set(view, offset);
|
9311
|
-
offset += view.length;
|
9312
|
-
}
|
9313
|
-
if (args[args.length - 1] instanceof Function) {
|
9314
|
-
return this.toView(res, args[args.length - 1]);
|
9315
|
-
}
|
9316
|
-
return res.buffer;
|
8963
|
+
let size = 0;
|
8964
|
+
for (const buffer of buffers) {
|
8965
|
+
size += buffer.byteLength;
|
8966
|
+
}
|
8967
|
+
const res = new Uint8Array(size);
|
8968
|
+
let offset = 0;
|
8969
|
+
for (const buffer of buffers) {
|
8970
|
+
const view = this.toUint8Array(buffer);
|
8971
|
+
res.set(view, offset);
|
8972
|
+
offset += view.length;
|
8973
|
+
}
|
8974
|
+
if (args[args.length - 1] instanceof Function) {
|
8975
|
+
return this.toView(res, args[args.length - 1]);
|
8976
|
+
}
|
8977
|
+
return res.buffer;
|
9317
8978
|
}
|
9318
8979
|
}
|
9319
8980
|
|
@@ -12454,272 +12115,44 @@ _a = TIME;
|
|
12454
12115
|
TIME.NAME = "TIME";
|
12455
12116
|
|
12456
12117
|
/**
|
12457
|
-
*
|
12118
|
+
* Signing a message failed
|
12458
12119
|
*/
|
12459
|
-
function pkcs1ToJwk(bytes) {
|
12460
|
-
const { result } = fromBER(bytes);
|
12461
|
-
// @ts-expect-error this looks fragile but DER is a canonical format so we are
|
12462
|
-
// safe to have deeply property chains like this
|
12463
|
-
const values = result.valueBlock.value;
|
12464
|
-
const key = {
|
12465
|
-
n: toString$1(bnToBuf(values[1].toBigInt()), 'base64url'),
|
12466
|
-
e: toString$1(bnToBuf(values[2].toBigInt()), 'base64url'),
|
12467
|
-
d: toString$1(bnToBuf(values[3].toBigInt()), 'base64url'),
|
12468
|
-
p: toString$1(bnToBuf(values[4].toBigInt()), 'base64url'),
|
12469
|
-
q: toString$1(bnToBuf(values[5].toBigInt()), 'base64url'),
|
12470
|
-
dp: toString$1(bnToBuf(values[6].toBigInt()), 'base64url'),
|
12471
|
-
dq: toString$1(bnToBuf(values[7].toBigInt()), 'base64url'),
|
12472
|
-
qi: toString$1(bnToBuf(values[8].toBigInt()), 'base64url'),
|
12473
|
-
kty: 'RSA',
|
12474
|
-
alg: 'RS256'
|
12475
|
-
};
|
12476
|
-
return key;
|
12477
|
-
}
|
12478
12120
|
/**
|
12479
|
-
*
|
12121
|
+
* Verifying a message signature failed
|
12480
12122
|
*/
|
12481
|
-
|
12482
|
-
|
12483
|
-
|
12123
|
+
class VerificationError extends Error {
|
12124
|
+
constructor(message = 'An error occurred while verifying a message') {
|
12125
|
+
super(message);
|
12126
|
+
this.name = 'VerificationError';
|
12484
12127
|
}
|
12485
|
-
const root = new Sequence({
|
12486
|
-
value: [
|
12487
|
-
new Integer({ value: 0 }),
|
12488
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
|
12489
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url'))),
|
12490
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.d, 'base64url'))),
|
12491
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.p, 'base64url'))),
|
12492
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.q, 'base64url'))),
|
12493
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.dp, 'base64url'))),
|
12494
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.dq, 'base64url'))),
|
12495
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.qi, 'base64url')))
|
12496
|
-
]
|
12497
|
-
});
|
12498
|
-
const der = root.toBER();
|
12499
|
-
return new Uint8Array(der, 0, der.byteLength);
|
12500
|
-
}
|
12501
|
-
/**
|
12502
|
-
* Convert a PKCIX in ASN1 DER format to a JWK key
|
12503
|
-
*/
|
12504
|
-
function pkixToJwk(bytes) {
|
12505
|
-
const { result } = fromBER(bytes);
|
12506
|
-
// @ts-expect-error this looks fragile but DER is a canonical format so we are
|
12507
|
-
// safe to have deeply property chains like this
|
12508
|
-
const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
|
12509
|
-
return {
|
12510
|
-
kty: 'RSA',
|
12511
|
-
n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
|
12512
|
-
e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
|
12513
|
-
};
|
12514
12128
|
}
|
12515
12129
|
/**
|
12516
|
-
*
|
12130
|
+
* WebCrypto was not available in the current context
|
12517
12131
|
*/
|
12518
|
-
|
12519
|
-
|
12520
|
-
|
12132
|
+
class WebCryptoMissingError extends Error {
|
12133
|
+
constructor(message = 'Missing Web Crypto API') {
|
12134
|
+
super(message);
|
12135
|
+
this.name = 'WebCryptoMissingError';
|
12521
12136
|
}
|
12522
|
-
const root = new Sequence({
|
12523
|
-
value: [
|
12524
|
-
new Sequence({
|
12525
|
-
value: [
|
12526
|
-
// rsaEncryption
|
12527
|
-
new ObjectIdentifier({
|
12528
|
-
value: '1.2.840.113549.1.1.1'
|
12529
|
-
}),
|
12530
|
-
new Null()
|
12531
|
-
]
|
12532
|
-
}),
|
12533
|
-
// this appears to be a bug in asn1js.js - this should really be a Sequence
|
12534
|
-
// and not a BitString but it generates the same bytes as node-forge so ๐คทโโ๏ธ
|
12535
|
-
new BitString({
|
12536
|
-
valueHex: new Sequence({
|
12537
|
-
value: [
|
12538
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
|
12539
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url')))
|
12540
|
-
]
|
12541
|
-
}).toBER()
|
12542
|
-
})
|
12543
|
-
]
|
12544
|
-
});
|
12545
|
-
const der = root.toBER();
|
12546
|
-
return new Uint8Array(der, 0, der.byteLength);
|
12547
12137
|
}
|
12548
|
-
|
12549
|
-
|
12550
|
-
|
12551
|
-
|
12552
|
-
|
12553
|
-
|
12554
|
-
|
12555
|
-
|
12556
|
-
|
12557
|
-
|
12558
|
-
|
12559
|
-
|
12560
|
-
|
12561
|
-
}
|
12562
|
-
return u8;
|
12563
|
-
}
|
12564
|
-
function bufToBn(u8) {
|
12565
|
-
const hex = [];
|
12566
|
-
u8.forEach(function (i) {
|
12567
|
-
let h = i.toString(16);
|
12568
|
-
if (h.length % 2 > 0) {
|
12569
|
-
h = `0${h}`;
|
12138
|
+
|
12139
|
+
/* eslint-env browser */
|
12140
|
+
// Check native crypto exists and is enabled (In insecure context `self.crypto`
|
12141
|
+
// exists but `self.crypto.subtle` does not).
|
12142
|
+
var webcrypto = {
|
12143
|
+
get(win = globalThis) {
|
12144
|
+
const nativeCrypto = win.crypto;
|
12145
|
+
if (nativeCrypto?.subtle == null) {
|
12146
|
+
throw new WebCryptoMissingError('Missing Web Crypto API. ' +
|
12147
|
+
'The most likely cause of this error is that this page is being accessed ' +
|
12148
|
+
'from an insecure context (i.e. not HTTPS). For more information and ' +
|
12149
|
+
'possible resolutions see ' +
|
12150
|
+
'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');
|
12570
12151
|
}
|
12571
|
-
|
12572
|
-
}
|
12573
|
-
|
12574
|
-
}
|
12575
|
-
const SALT_LENGTH = 16;
|
12576
|
-
const KEY_SIZE = 32;
|
12577
|
-
const ITERATIONS = 10000;
|
12578
|
-
async function exportToPem(privateKey, password) {
|
12579
|
-
const crypto = webcrypto.get();
|
12580
|
-
// PrivateKeyInfo
|
12581
|
-
const keyWrapper = new Sequence({
|
12582
|
-
value: [
|
12583
|
-
// version (0)
|
12584
|
-
new Integer({ value: 0 }),
|
12585
|
-
// privateKeyAlgorithm
|
12586
|
-
new Sequence({
|
12587
|
-
value: [
|
12588
|
-
// rsaEncryption OID
|
12589
|
-
new ObjectIdentifier({
|
12590
|
-
value: '1.2.840.113549.1.1.1'
|
12591
|
-
}),
|
12592
|
-
new Null()
|
12593
|
-
]
|
12594
|
-
}),
|
12595
|
-
// PrivateKey
|
12596
|
-
new OctetString({
|
12597
|
-
valueHex: privateKey.marshal()
|
12598
|
-
})
|
12599
|
-
]
|
12600
|
-
});
|
12601
|
-
const keyBuf = keyWrapper.toBER();
|
12602
|
-
const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);
|
12603
|
-
const salt = randomBytes(SALT_LENGTH);
|
12604
|
-
const encryptionKey = await pbkdf2Async(sha512, password, salt, {
|
12605
|
-
c: ITERATIONS,
|
12606
|
-
dkLen: KEY_SIZE
|
12607
|
-
});
|
12608
|
-
const iv = randomBytes(16);
|
12609
|
-
const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);
|
12610
|
-
const encrypted = await crypto.subtle.encrypt({
|
12611
|
-
name: 'AES-CBC',
|
12612
|
-
iv
|
12613
|
-
}, cryptoKey, keyArr);
|
12614
|
-
const pbkdf2Params = new Sequence({
|
12615
|
-
value: [
|
12616
|
-
// salt
|
12617
|
-
new OctetString({ valueHex: salt }),
|
12618
|
-
// iteration count
|
12619
|
-
new Integer({ value: ITERATIONS }),
|
12620
|
-
// key length
|
12621
|
-
new Integer({ value: KEY_SIZE }),
|
12622
|
-
// AlgorithmIdentifier
|
12623
|
-
new Sequence({
|
12624
|
-
value: [
|
12625
|
-
// hmacWithSHA512
|
12626
|
-
new ObjectIdentifier({ value: '1.2.840.113549.2.11' }),
|
12627
|
-
new Null()
|
12628
|
-
]
|
12629
|
-
})
|
12630
|
-
]
|
12631
|
-
});
|
12632
|
-
const encryptionAlgorithm = new Sequence({
|
12633
|
-
value: [
|
12634
|
-
// pkcs5PBES2
|
12635
|
-
new ObjectIdentifier({
|
12636
|
-
value: '1.2.840.113549.1.5.13'
|
12637
|
-
}),
|
12638
|
-
new Sequence({
|
12639
|
-
value: [
|
12640
|
-
// keyDerivationFunc
|
12641
|
-
new Sequence({
|
12642
|
-
value: [
|
12643
|
-
// pkcs5PBKDF2
|
12644
|
-
new ObjectIdentifier({
|
12645
|
-
value: '1.2.840.113549.1.5.12'
|
12646
|
-
}),
|
12647
|
-
// PBKDF2-params
|
12648
|
-
pbkdf2Params
|
12649
|
-
]
|
12650
|
-
}),
|
12651
|
-
// encryptionScheme
|
12652
|
-
new Sequence({
|
12653
|
-
value: [
|
12654
|
-
// aes256-CBC
|
12655
|
-
new ObjectIdentifier({
|
12656
|
-
value: '2.16.840.1.101.3.4.1.42'
|
12657
|
-
}),
|
12658
|
-
// iv
|
12659
|
-
new OctetString({
|
12660
|
-
valueHex: iv
|
12661
|
-
})
|
12662
|
-
]
|
12663
|
-
})
|
12664
|
-
]
|
12665
|
-
})
|
12666
|
-
]
|
12667
|
-
});
|
12668
|
-
const finalWrapper = new Sequence({
|
12669
|
-
value: [
|
12670
|
-
encryptionAlgorithm,
|
12671
|
-
new OctetString({ valueHex: encrypted })
|
12672
|
-
]
|
12673
|
-
});
|
12674
|
-
const finalWrapperBuf = finalWrapper.toBER();
|
12675
|
-
const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);
|
12676
|
-
return [
|
12677
|
-
'-----BEGIN ENCRYPTED PRIVATE KEY-----',
|
12678
|
-
...toString$1(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),
|
12679
|
-
'-----END ENCRYPTED PRIVATE KEY-----'
|
12680
|
-
].join('\n');
|
12681
|
-
}
|
12152
|
+
return nativeCrypto;
|
12153
|
+
}
|
12154
|
+
};
|
12682
12155
|
|
12683
|
-
async function generateKey$1(bits) {
|
12684
|
-
const pair = await webcrypto.get().subtle.generateKey({
|
12685
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12686
|
-
modulusLength: bits,
|
12687
|
-
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
12688
|
-
hash: { name: 'SHA-256' }
|
12689
|
-
}, true, ['sign', 'verify']);
|
12690
|
-
const keys = await exportKey(pair);
|
12691
|
-
return {
|
12692
|
-
privateKey: keys[0],
|
12693
|
-
publicKey: keys[1]
|
12694
|
-
};
|
12695
|
-
}
|
12696
|
-
// Takes a jwk key
|
12697
|
-
async function unmarshalPrivateKey$1(key) {
|
12698
|
-
const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12699
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12700
|
-
hash: { name: 'SHA-256' }
|
12701
|
-
}, true, ['sign']);
|
12702
|
-
const pair = [
|
12703
|
-
privateKey,
|
12704
|
-
await derivePublicFromPrivate(key)
|
12705
|
-
];
|
12706
|
-
const keys = await exportKey({
|
12707
|
-
privateKey: pair[0],
|
12708
|
-
publicKey: pair[1]
|
12709
|
-
});
|
12710
|
-
return {
|
12711
|
-
privateKey: keys[0],
|
12712
|
-
publicKey: keys[1]
|
12713
|
-
};
|
12714
|
-
}
|
12715
|
-
async function hashAndSign$1(key, msg) {
|
12716
|
-
const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12717
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12718
|
-
hash: { name: 'SHA-256' }
|
12719
|
-
}, false, ['sign']);
|
12720
|
-
const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
|
12721
|
-
return new Uint8Array(sig, 0, sig.byteLength);
|
12722
|
-
}
|
12723
12156
|
async function hashAndVerify$1(key, sig, msg) {
|
12724
12157
|
const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12725
12158
|
name: 'RSASSA-PKCS1-v1_5',
|
@@ -12727,173 +12160,222 @@ async function hashAndVerify$1(key, sig, msg) {
|
|
12727
12160
|
}, false, ['verify']);
|
12728
12161
|
return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
|
12729
12162
|
}
|
12730
|
-
|
12731
|
-
if (pair.privateKey == null || pair.publicKey == null) {
|
12732
|
-
throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
|
12733
|
-
}
|
12734
|
-
return Promise.all([
|
12735
|
-
webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
|
12736
|
-
webcrypto.get().subtle.exportKey('jwk', pair.publicKey)
|
12737
|
-
]);
|
12738
|
-
}
|
12739
|
-
async function derivePublicFromPrivate(jwKey) {
|
12740
|
-
return webcrypto.get().subtle.importKey('jwk', {
|
12741
|
-
kty: jwKey.kty,
|
12742
|
-
n: jwKey.n,
|
12743
|
-
e: jwKey.e
|
12744
|
-
}, {
|
12745
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12746
|
-
hash: { name: 'SHA-256' }
|
12747
|
-
}, true, ['verify']);
|
12748
|
-
}
|
12749
|
-
function keySize(jwk) {
|
12163
|
+
function rsaKeySize(jwk) {
|
12750
12164
|
if (jwk.kty !== 'RSA') {
|
12751
|
-
throw new
|
12165
|
+
throw new InvalidParametersError('invalid key type');
|
12752
12166
|
}
|
12753
12167
|
else if (jwk.n == null) {
|
12754
|
-
throw new
|
12168
|
+
throw new InvalidParametersError('invalid key modulus');
|
12755
12169
|
}
|
12756
12170
|
const bytes = fromString(jwk.n, 'base64url');
|
12757
12171
|
return bytes.length * 8;
|
12758
12172
|
}
|
12759
12173
|
|
12760
|
-
|
12761
|
-
|
12174
|
+
class RSAPublicKey {
|
12175
|
+
type = 'RSA';
|
12762
12176
|
_key;
|
12763
|
-
|
12177
|
+
_raw;
|
12178
|
+
_multihash;
|
12179
|
+
constructor(key, digest) {
|
12764
12180
|
this._key = key;
|
12181
|
+
this._multihash = digest;
|
12765
12182
|
}
|
12766
|
-
|
12767
|
-
|
12768
|
-
|
12769
|
-
marshal() {
|
12770
|
-
return jwkToPkix(this._key);
|
12771
|
-
}
|
12772
|
-
get bytes() {
|
12773
|
-
return PublicKey.encode({
|
12774
|
-
Type: KeyType.RSA,
|
12775
|
-
Data: this.marshal()
|
12776
|
-
}).subarray();
|
12777
|
-
}
|
12778
|
-
equals(key) {
|
12779
|
-
return equals(this.bytes, key.bytes);
|
12780
|
-
}
|
12781
|
-
hash() {
|
12782
|
-
const p = sha256$1.digest(this.bytes);
|
12783
|
-
if (isPromise(p)) {
|
12784
|
-
return p.then(({ bytes }) => bytes);
|
12183
|
+
get raw() {
|
12184
|
+
if (this._raw == null) {
|
12185
|
+
this._raw = jwkToPkix(this._key);
|
12785
12186
|
}
|
12786
|
-
return
|
12187
|
+
return this._raw;
|
12787
12188
|
}
|
12788
|
-
|
12789
|
-
|
12790
|
-
_key;
|
12791
|
-
_publicKey;
|
12792
|
-
constructor(key, publicKey) {
|
12793
|
-
this._key = key;
|
12794
|
-
this._publicKey = publicKey;
|
12795
|
-
}
|
12796
|
-
genSecret() {
|
12797
|
-
return randomBytes(16);
|
12189
|
+
toMultihash() {
|
12190
|
+
return this._multihash;
|
12798
12191
|
}
|
12799
|
-
|
12800
|
-
return
|
12801
|
-
}
|
12802
|
-
get public() {
|
12803
|
-
if (this._publicKey == null) {
|
12804
|
-
throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
|
12805
|
-
}
|
12806
|
-
return new RsaPublicKey(this._publicKey);
|
12807
|
-
}
|
12808
|
-
marshal() {
|
12809
|
-
return jwkToPkcs1(this._key);
|
12192
|
+
toCID() {
|
12193
|
+
return CID.createV1(114, this._multihash);
|
12810
12194
|
}
|
12811
|
-
|
12812
|
-
return
|
12813
|
-
Type: KeyType.RSA,
|
12814
|
-
Data: this.marshal()
|
12815
|
-
}).subarray();
|
12195
|
+
toString() {
|
12196
|
+
return base58btc.encode(this.toMultihash().bytes).substring(1);
|
12816
12197
|
}
|
12817
12198
|
equals(key) {
|
12818
|
-
|
12819
|
-
|
12820
|
-
hash() {
|
12821
|
-
const p = sha256$1.digest(this.bytes);
|
12822
|
-
if (isPromise(p)) {
|
12823
|
-
return p.then(({ bytes }) => bytes);
|
12199
|
+
if (key == null || !(key.raw instanceof Uint8Array)) {
|
12200
|
+
return false;
|
12824
12201
|
}
|
12825
|
-
return
|
12202
|
+
return equals(this.raw, key.raw);
|
12826
12203
|
}
|
12827
|
-
|
12828
|
-
|
12829
|
-
*
|
12830
|
-
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
12831
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
12832
|
-
* of the PKCS SubjectPublicKeyInfo.
|
12833
|
-
*/
|
12834
|
-
async id() {
|
12835
|
-
const hash = await this.public.hash();
|
12836
|
-
return toString$1(hash, 'base58btc');
|
12204
|
+
verify(data, sig) {
|
12205
|
+
return hashAndVerify$1(this._key, sig, data);
|
12837
12206
|
}
|
12838
|
-
|
12839
|
-
|
12840
|
-
|
12841
|
-
|
12842
|
-
|
12843
|
-
|
12844
|
-
|
12845
|
-
|
12846
|
-
|
12847
|
-
|
12848
|
-
|
12849
|
-
|
12850
|
-
|
12851
|
-
|
12852
|
-
|
12853
|
-
|
12854
|
-
|
12207
|
+
}
|
12208
|
+
|
12209
|
+
const MAX_RSA_KEY_SIZE = 8192;
|
12210
|
+
const SHA2_256_CODE = 0x12;
|
12211
|
+
/**
|
12212
|
+
* Convert a PKIX in ASN1 DER format to a JWK key
|
12213
|
+
*/
|
12214
|
+
function pkixToJwk(bytes) {
|
12215
|
+
const { result } = fromBER(bytes);
|
12216
|
+
// @ts-expect-error this looks fragile but DER is a canonical format so we are
|
12217
|
+
// safe to have deeply property chains like this
|
12218
|
+
const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
|
12219
|
+
return {
|
12220
|
+
kty: 'RSA',
|
12221
|
+
n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
|
12222
|
+
e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
|
12223
|
+
};
|
12224
|
+
}
|
12225
|
+
/**
|
12226
|
+
* Convert a JWK key to PKIX in ASN1 DER format
|
12227
|
+
*/
|
12228
|
+
function jwkToPkix(jwk) {
|
12229
|
+
if (jwk.n == null || jwk.e == null) {
|
12230
|
+
throw new InvalidParametersError('JWK was missing components');
|
12855
12231
|
}
|
12232
|
+
const root = new Sequence({
|
12233
|
+
value: [
|
12234
|
+
new Sequence({
|
12235
|
+
value: [
|
12236
|
+
// rsaEncryption
|
12237
|
+
new ObjectIdentifier({
|
12238
|
+
value: '1.2.840.113549.1.1.1'
|
12239
|
+
}),
|
12240
|
+
new Null()
|
12241
|
+
]
|
12242
|
+
}),
|
12243
|
+
// this appears to be a bug in asn1js.js - this should really be a Sequence
|
12244
|
+
// and not a BitString but it generates the same bytes as node-forge so ๐คทโโ๏ธ
|
12245
|
+
new BitString({
|
12246
|
+
valueHex: new Sequence({
|
12247
|
+
value: [
|
12248
|
+
Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
|
12249
|
+
Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url')))
|
12250
|
+
]
|
12251
|
+
}).toBER()
|
12252
|
+
})
|
12253
|
+
]
|
12254
|
+
});
|
12255
|
+
const der = root.toBER();
|
12256
|
+
return new Uint8Array(der, 0, der.byteLength);
|
12856
12257
|
}
|
12857
|
-
|
12858
|
-
|
12859
|
-
if (
|
12860
|
-
|
12258
|
+
function bnToBuf(bn) {
|
12259
|
+
let hex = bn.toString(16);
|
12260
|
+
if (hex.length % 2 > 0) {
|
12261
|
+
hex = `0${hex}`;
|
12262
|
+
}
|
12263
|
+
const len = hex.length / 2;
|
12264
|
+
const u8 = new Uint8Array(len);
|
12265
|
+
let i = 0;
|
12266
|
+
let j = 0;
|
12267
|
+
while (i < len) {
|
12268
|
+
u8[i] = parseInt(hex.slice(j, j + 2), 16);
|
12269
|
+
i += 1;
|
12270
|
+
j += 2;
|
12861
12271
|
}
|
12862
|
-
|
12863
|
-
return new RsaPrivateKey(keys.privateKey, keys.publicKey);
|
12272
|
+
return u8;
|
12864
12273
|
}
|
12865
|
-
function
|
12274
|
+
function bufToBn(u8) {
|
12275
|
+
const hex = [];
|
12276
|
+
u8.forEach(function (i) {
|
12277
|
+
let h = i.toString(16);
|
12278
|
+
if (h.length % 2 > 0) {
|
12279
|
+
h = `0${h}`;
|
12280
|
+
}
|
12281
|
+
hex.push(h);
|
12282
|
+
});
|
12283
|
+
return BigInt('0x' + hex.join(''));
|
12284
|
+
}
|
12285
|
+
/**
|
12286
|
+
* Turn PKIX bytes to a PublicKey
|
12287
|
+
*/
|
12288
|
+
function pkixToRSAPublicKey(bytes) {
|
12866
12289
|
const jwk = pkixToJwk(bytes);
|
12867
|
-
if (
|
12868
|
-
throw new
|
12290
|
+
if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {
|
12291
|
+
throw new InvalidPublicKeyError('Key size is too large');
|
12869
12292
|
}
|
12870
|
-
|
12293
|
+
const hash = sha256(PublicKey.encode({
|
12294
|
+
Type: KeyType.RSA,
|
12295
|
+
Data: bytes
|
12296
|
+
}));
|
12297
|
+
const digest = create(SHA2_256_CODE, hash);
|
12298
|
+
return new RSAPublicKey(jwk, digest);
|
12871
12299
|
}
|
12872
|
-
|
12873
|
-
|
12874
|
-
|
12300
|
+
|
12301
|
+
// HMAC (RFC 2104)
|
12302
|
+
class HMAC extends Hash {
|
12303
|
+
constructor(hash$1, _key) {
|
12304
|
+
super();
|
12305
|
+
this.finished = false;
|
12306
|
+
this.destroyed = false;
|
12307
|
+
hash(hash$1);
|
12308
|
+
const key = toBytes$1(_key);
|
12309
|
+
this.iHash = hash$1.create();
|
12310
|
+
if (typeof this.iHash.update !== 'function')
|
12311
|
+
throw new Error('Expected instance of class which extends utils.Hash');
|
12312
|
+
this.blockLen = this.iHash.blockLen;
|
12313
|
+
this.outputLen = this.iHash.outputLen;
|
12314
|
+
const blockLen = this.blockLen;
|
12315
|
+
const pad = new Uint8Array(blockLen);
|
12316
|
+
// blockLen can be bigger than outputLen
|
12317
|
+
pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
|
12318
|
+
for (let i = 0; i < pad.length; i++)
|
12319
|
+
pad[i] ^= 0x36;
|
12320
|
+
this.iHash.update(pad);
|
12321
|
+
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
|
12322
|
+
this.oHash = hash$1.create();
|
12323
|
+
// Undo internal XOR && apply outer XOR
|
12324
|
+
for (let i = 0; i < pad.length; i++)
|
12325
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
12326
|
+
this.oHash.update(pad);
|
12327
|
+
pad.fill(0);
|
12875
12328
|
}
|
12876
|
-
|
12877
|
-
|
12878
|
-
|
12879
|
-
|
12880
|
-
|
12881
|
-
|
12329
|
+
update(buf) {
|
12330
|
+
exists(this);
|
12331
|
+
this.iHash.update(buf);
|
12332
|
+
return this;
|
12333
|
+
}
|
12334
|
+
digestInto(out) {
|
12335
|
+
exists(this);
|
12336
|
+
bytes(out, this.outputLen);
|
12337
|
+
this.finished = true;
|
12338
|
+
this.iHash.digestInto(out);
|
12339
|
+
this.oHash.update(out);
|
12340
|
+
this.oHash.digestInto(out);
|
12341
|
+
this.destroy();
|
12342
|
+
}
|
12343
|
+
digest() {
|
12344
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
12345
|
+
this.digestInto(out);
|
12346
|
+
return out;
|
12347
|
+
}
|
12348
|
+
_cloneInto(to) {
|
12349
|
+
// Create new instance without calling constructor since key already in state and we don't know it.
|
12350
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
12351
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
12352
|
+
to = to;
|
12353
|
+
to.finished = finished;
|
12354
|
+
to.destroyed = destroyed;
|
12355
|
+
to.blockLen = blockLen;
|
12356
|
+
to.outputLen = outputLen;
|
12357
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
12358
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
12359
|
+
return to;
|
12360
|
+
}
|
12361
|
+
destroy() {
|
12362
|
+
this.destroyed = true;
|
12363
|
+
this.oHash.destroy();
|
12364
|
+
this.iHash.destroy();
|
12882
12365
|
}
|
12883
|
-
const keys = await generateKey$1(bits);
|
12884
|
-
return new RsaPrivateKey(keys.privateKey, keys.publicKey);
|
12885
12366
|
}
|
12886
|
-
|
12887
|
-
|
12888
|
-
|
12889
|
-
|
12890
|
-
|
12891
|
-
|
12892
|
-
|
12893
|
-
|
12894
|
-
|
12895
|
-
|
12896
|
-
|
12367
|
+
/**
|
12368
|
+
* HMAC: RFC2104 message authentication code.
|
12369
|
+
* @param hash - function that would be used e.g. sha256
|
12370
|
+
* @param key - message key
|
12371
|
+
* @param message - message data
|
12372
|
+
* @example
|
12373
|
+
* import { hmac } from '@noble/hashes/hmac';
|
12374
|
+
* import { sha256 } from '@noble/hashes/sha2';
|
12375
|
+
* const mac1 = hmac(sha256, 'key', 'message');
|
12376
|
+
*/
|
12377
|
+
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
12378
|
+
hmac.create = (hash, key) => new HMAC(hash, key);
|
12897
12379
|
|
12898
12380
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
12899
12381
|
// Short Weierstrass curve. The formula is: yยฒ = xยณ + ax + b
|
@@ -12930,8 +12412,14 @@ function validatePointOpts(curve) {
|
|
12930
12412
|
}
|
12931
12413
|
return Object.freeze({ ...opts });
|
12932
12414
|
}
|
12933
|
-
// ASN.1 DER encoding utilities
|
12934
12415
|
const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
|
12416
|
+
/**
|
12417
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
12418
|
+
*
|
12419
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
12420
|
+
*
|
12421
|
+
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
|
12422
|
+
*/
|
12935
12423
|
const DER = {
|
12936
12424
|
// asn.1 DER encoding utils
|
12937
12425
|
Err: class DERErr extends Error {
|
@@ -12939,54 +12427,103 @@ const DER = {
|
|
12939
12427
|
super(m);
|
12940
12428
|
}
|
12941
12429
|
},
|
12942
|
-
|
12943
|
-
|
12944
|
-
|
12945
|
-
|
12946
|
-
|
12947
|
-
|
12948
|
-
|
12949
|
-
|
12950
|
-
|
12951
|
-
|
12952
|
-
|
12953
|
-
|
12954
|
-
|
12955
|
-
|
12956
|
-
|
12957
|
-
|
12958
|
-
|
12430
|
+
// Basic building block is TLV (Tag-Length-Value)
|
12431
|
+
_tlv: {
|
12432
|
+
encode: (tag, data) => {
|
12433
|
+
const { Err: E } = DER;
|
12434
|
+
if (tag < 0 || tag > 256)
|
12435
|
+
throw new E('tlv.encode: wrong tag');
|
12436
|
+
if (data.length & 1)
|
12437
|
+
throw new E('tlv.encode: unpadded data');
|
12438
|
+
const dataLen = data.length / 2;
|
12439
|
+
const len = numberToHexUnpadded(dataLen);
|
12440
|
+
if ((len.length / 2) & 128)
|
12441
|
+
throw new E('tlv.encode: long form length too big');
|
12442
|
+
// length of length with long form flag
|
12443
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
|
12444
|
+
return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
|
12445
|
+
},
|
12446
|
+
// v - value, l - left bytes (unparsed)
|
12447
|
+
decode(tag, data) {
|
12448
|
+
const { Err: E } = DER;
|
12449
|
+
let pos = 0;
|
12450
|
+
if (tag < 0 || tag > 256)
|
12451
|
+
throw new E('tlv.encode: wrong tag');
|
12452
|
+
if (data.length < 2 || data[pos++] !== tag)
|
12453
|
+
throw new E('tlv.decode: wrong tlv');
|
12454
|
+
const first = data[pos++];
|
12455
|
+
const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
|
12456
|
+
let length = 0;
|
12457
|
+
if (!isLong)
|
12458
|
+
length = first;
|
12459
|
+
else {
|
12460
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
12461
|
+
const lenLen = first & 127;
|
12462
|
+
if (!lenLen)
|
12463
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
12464
|
+
if (lenLen > 4)
|
12465
|
+
throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
|
12466
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
12467
|
+
if (lengthBytes.length !== lenLen)
|
12468
|
+
throw new E('tlv.decode: length bytes not complete');
|
12469
|
+
if (lengthBytes[0] === 0)
|
12470
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
12471
|
+
for (const b of lengthBytes)
|
12472
|
+
length = (length << 8) | b;
|
12473
|
+
pos += lenLen;
|
12474
|
+
if (length < 128)
|
12475
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
12476
|
+
}
|
12477
|
+
const v = data.subarray(pos, pos + length);
|
12478
|
+
if (v.length !== length)
|
12479
|
+
throw new E('tlv.decode: wrong value length');
|
12480
|
+
return { v, l: data.subarray(pos + length) };
|
12481
|
+
},
|
12482
|
+
},
|
12483
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
12484
|
+
// since we always use positive integers here. It must always be empty:
|
12485
|
+
// - add zero byte if exists
|
12486
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
12487
|
+
_int: {
|
12488
|
+
encode(num) {
|
12489
|
+
const { Err: E } = DER;
|
12490
|
+
if (num < _0n)
|
12491
|
+
throw new E('integer: negative integers are not allowed');
|
12492
|
+
let hex = numberToHexUnpadded(num);
|
12493
|
+
// Pad with zero byte if negative flag is present
|
12494
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
12495
|
+
hex = '00' + hex;
|
12496
|
+
if (hex.length & 1)
|
12497
|
+
throw new E('unexpected assertion');
|
12498
|
+
return hex;
|
12499
|
+
},
|
12500
|
+
decode(data) {
|
12501
|
+
const { Err: E } = DER;
|
12502
|
+
if (data[0] & 128)
|
12503
|
+
throw new E('Invalid signature integer: negative');
|
12504
|
+
if (data[0] === 0x00 && !(data[1] & 128))
|
12505
|
+
throw new E('Invalid signature integer: unnecessary leading zero');
|
12506
|
+
return b2n(data);
|
12507
|
+
},
|
12959
12508
|
},
|
12960
12509
|
toSig(hex) {
|
12961
12510
|
// parse DER signature
|
12962
|
-
const { Err: E } = DER;
|
12511
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
12963
12512
|
const data = typeof hex === 'string' ? h2b(hex) : hex;
|
12964
12513
|
abytes(data);
|
12965
|
-
|
12966
|
-
if (
|
12967
|
-
throw new E('Invalid signature
|
12968
|
-
|
12969
|
-
|
12970
|
-
|
12971
|
-
const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
|
12972
|
-
if (rBytesLeft.length)
|
12514
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
12515
|
+
if (seqLeftBytes.length)
|
12516
|
+
throw new E('Invalid signature: left bytes after parsing');
|
12517
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
12518
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
12519
|
+
if (sLeftBytes.length)
|
12973
12520
|
throw new E('Invalid signature: left bytes after parsing');
|
12974
|
-
return { r, s };
|
12521
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
12975
12522
|
},
|
12976
12523
|
hexFromSig(sig) {
|
12977
|
-
|
12978
|
-
const
|
12979
|
-
|
12980
|
-
const hex = num.toString(16);
|
12981
|
-
return hex.length & 1 ? `0${hex}` : hex;
|
12982
|
-
};
|
12983
|
-
const s = slice(h(sig.s));
|
12984
|
-
const r = slice(h(sig.r));
|
12985
|
-
const shl = s.length / 2;
|
12986
|
-
const rhl = r.length / 2;
|
12987
|
-
const sl = h(shl);
|
12988
|
-
const rl = h(rhl);
|
12989
|
-
return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
|
12524
|
+
const { _tlv: tlv, _int: int } = DER;
|
12525
|
+
const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
|
12526
|
+
return tlv.encode(0x30, seq);
|
12990
12527
|
},
|
12991
12528
|
};
|
12992
12529
|
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
@@ -12995,6 +12532,7 @@ const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigI
|
|
12995
12532
|
function weierstrassPoints(opts) {
|
12996
12533
|
const CURVE = validatePointOpts(opts);
|
12997
12534
|
const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
|
12535
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
12998
12536
|
const toBytes = CURVE.toBytes ||
|
12999
12537
|
((_c, point, _isCompressed) => {
|
13000
12538
|
const a = point.toAffine();
|
@@ -13168,6 +12706,10 @@ function weierstrassPoints(opts) {
|
|
13168
12706
|
static fromPrivateKey(privateKey) {
|
13169
12707
|
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
|
13170
12708
|
}
|
12709
|
+
// Multiscalar Multiplication
|
12710
|
+
static msm(points, scalars) {
|
12711
|
+
return pippenger(Point, Fn, points, scalars);
|
12712
|
+
}
|
13171
12713
|
// "Private method", don't use it directly
|
13172
12714
|
_setWindowSize(windowSize) {
|
13173
12715
|
wnaf.setWindowSize(this, windowSize);
|
@@ -13853,7 +13395,7 @@ function getHash(hash) {
|
|
13853
13395
|
return {
|
13854
13396
|
hash,
|
13855
13397
|
hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
|
13856
|
-
randomBytes
|
13398
|
+
randomBytes,
|
13857
13399
|
};
|
13858
13400
|
}
|
13859
13401
|
function createCurve(curveDef, defHash) {
|
@@ -13946,27 +13488,15 @@ const secp256k1 = createCurve({
|
|
13946
13488
|
BigInt(0);
|
13947
13489
|
secp256k1.ProjectivePoint;
|
13948
13490
|
|
13949
|
-
function
|
13950
|
-
|
13951
|
-
|
13952
|
-
/**
|
13953
|
-
* Hash and sign message with private key
|
13954
|
-
*/
|
13955
|
-
function hashAndSign(key, msg) {
|
13956
|
-
const p = sha256$1.digest(msg instanceof Uint8Array ? msg : msg.subarray());
|
13957
|
-
if (isPromise(p)) {
|
13958
|
-
return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
|
13959
|
-
.catch(err => {
|
13960
|
-
throw new CodeError(String(err), 'ERR_INVALID_INPUT');
|
13961
|
-
});
|
13962
|
-
}
|
13963
|
-
try {
|
13964
|
-
return secp256k1.sign(p.digest, key).toDERRawBytes();
|
13965
|
-
}
|
13966
|
-
catch (err) {
|
13967
|
-
throw new CodeError(String(err), 'ERR_INVALID_INPUT');
|
13491
|
+
function isPromise(thing) {
|
13492
|
+
if (thing == null) {
|
13493
|
+
return false;
|
13968
13494
|
}
|
13495
|
+
return typeof thing.then === 'function' &&
|
13496
|
+
typeof thing.catch === 'function' &&
|
13497
|
+
typeof thing.finally === 'function';
|
13969
13498
|
}
|
13499
|
+
|
13970
13500
|
/**
|
13971
13501
|
* Hash message and verify signature with public key
|
13972
13502
|
*/
|
@@ -13975,207 +13505,114 @@ function hashAndVerify(key, sig, msg) {
|
|
13975
13505
|
if (isPromise(p)) {
|
13976
13506
|
return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
|
13977
13507
|
.catch(err => {
|
13978
|
-
throw new
|
13508
|
+
throw new VerificationError(String(err));
|
13979
13509
|
});
|
13980
13510
|
}
|
13981
13511
|
try {
|
13982
13512
|
return secp256k1.verify(sig, p.digest, key);
|
13983
13513
|
}
|
13984
13514
|
catch (err) {
|
13985
|
-
throw new
|
13986
|
-
}
|
13987
|
-
}
|
13988
|
-
function compressPublicKey(key) {
|
13989
|
-
const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
|
13990
|
-
return point;
|
13991
|
-
}
|
13992
|
-
function validatePrivateKey(key) {
|
13993
|
-
try {
|
13994
|
-
secp256k1.getPublicKey(key, true);
|
13995
|
-
}
|
13996
|
-
catch (err) {
|
13997
|
-
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
|
13998
|
-
}
|
13999
|
-
}
|
14000
|
-
function validatePublicKey(key) {
|
14001
|
-
try {
|
14002
|
-
secp256k1.ProjectivePoint.fromHex(key);
|
14003
|
-
}
|
14004
|
-
catch (err) {
|
14005
|
-
throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
|
14006
|
-
}
|
14007
|
-
}
|
14008
|
-
function computePublicKey(privateKey) {
|
14009
|
-
try {
|
14010
|
-
return secp256k1.getPublicKey(privateKey, true);
|
14011
|
-
}
|
14012
|
-
catch (err) {
|
14013
|
-
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
|
13515
|
+
throw new VerificationError(String(err));
|
14014
13516
|
}
|
14015
13517
|
}
|
14016
13518
|
|
14017
13519
|
class Secp256k1PublicKey {
|
13520
|
+
type = 'secp256k1';
|
13521
|
+
raw;
|
14018
13522
|
_key;
|
14019
13523
|
constructor(key) {
|
14020
|
-
|
14021
|
-
this.
|
13524
|
+
this._key = validateSecp256k1PublicKey(key);
|
13525
|
+
this.raw = compressSecp256k1PublicKey(this._key);
|
14022
13526
|
}
|
14023
|
-
|
14024
|
-
return
|
14025
|
-
}
|
14026
|
-
marshal() {
|
14027
|
-
return compressPublicKey(this._key);
|
13527
|
+
toMultihash() {
|
13528
|
+
return identity.digest(publicKeyToProtobuf(this));
|
14028
13529
|
}
|
14029
|
-
|
14030
|
-
return
|
14031
|
-
Type: KeyType.Secp256k1,
|
14032
|
-
Data: this.marshal()
|
14033
|
-
}).subarray();
|
14034
|
-
}
|
14035
|
-
equals(key) {
|
14036
|
-
return equals(this.bytes, key.bytes);
|
14037
|
-
}
|
14038
|
-
async hash() {
|
14039
|
-
const p = sha256$1.digest(this.bytes);
|
14040
|
-
let bytes;
|
14041
|
-
if (isPromise(p)) {
|
14042
|
-
({ bytes } = await p);
|
14043
|
-
}
|
14044
|
-
else {
|
14045
|
-
bytes = p.bytes;
|
14046
|
-
}
|
14047
|
-
return bytes;
|
14048
|
-
}
|
14049
|
-
}
|
14050
|
-
class Secp256k1PrivateKey {
|
14051
|
-
_key;
|
14052
|
-
_publicKey;
|
14053
|
-
constructor(key, publicKey) {
|
14054
|
-
this._key = key;
|
14055
|
-
this._publicKey = publicKey ?? computePublicKey(key);
|
14056
|
-
validatePrivateKey(this._key);
|
14057
|
-
validatePublicKey(this._publicKey);
|
14058
|
-
}
|
14059
|
-
sign(message) {
|
14060
|
-
return hashAndSign(this._key, message);
|
14061
|
-
}
|
14062
|
-
get public() {
|
14063
|
-
return new Secp256k1PublicKey(this._publicKey);
|
14064
|
-
}
|
14065
|
-
marshal() {
|
14066
|
-
return this._key;
|
13530
|
+
toCID() {
|
13531
|
+
return CID.createV1(114, this.toMultihash());
|
14067
13532
|
}
|
14068
|
-
|
14069
|
-
return
|
14070
|
-
Type: KeyType.Secp256k1,
|
14071
|
-
Data: this.marshal()
|
14072
|
-
}).subarray();
|
13533
|
+
toString() {
|
13534
|
+
return base58btc.encode(this.toMultihash().bytes).substring(1);
|
14073
13535
|
}
|
14074
13536
|
equals(key) {
|
14075
|
-
|
14076
|
-
|
14077
|
-
hash() {
|
14078
|
-
const p = sha256$1.digest(this.bytes);
|
14079
|
-
if (isPromise(p)) {
|
14080
|
-
return p.then(({ bytes }) => bytes);
|
13537
|
+
if (key == null || !(key.raw instanceof Uint8Array)) {
|
13538
|
+
return false;
|
14081
13539
|
}
|
14082
|
-
return
|
13540
|
+
return equals(this.raw, key.raw);
|
14083
13541
|
}
|
14084
|
-
|
14085
|
-
|
14086
|
-
*
|
14087
|
-
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
14088
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
14089
|
-
* of the PKCS SubjectPublicKeyInfo.
|
14090
|
-
*/
|
14091
|
-
async id() {
|
14092
|
-
const hash = await this.public.hash();
|
14093
|
-
return toString$1(hash, 'base58btc');
|
14094
|
-
}
|
14095
|
-
/**
|
14096
|
-
* Exports the key into a password protected `format`
|
14097
|
-
*/
|
14098
|
-
async export(password, format = 'libp2p-key') {
|
14099
|
-
if (format === 'libp2p-key') {
|
14100
|
-
return exporter(this.bytes, password);
|
14101
|
-
}
|
14102
|
-
else {
|
14103
|
-
throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
|
14104
|
-
}
|
13542
|
+
verify(data, sig) {
|
13543
|
+
return hashAndVerify(this._key, sig, data);
|
14105
13544
|
}
|
14106
13545
|
}
|
14107
|
-
|
14108
|
-
return new Secp256k1PrivateKey(bytes);
|
14109
|
-
}
|
13546
|
+
|
14110
13547
|
function unmarshalSecp256k1PublicKey(bytes) {
|
14111
13548
|
return new Secp256k1PublicKey(bytes);
|
14112
13549
|
}
|
14113
|
-
|
14114
|
-
const
|
14115
|
-
return
|
13550
|
+
function compressSecp256k1PublicKey(key) {
|
13551
|
+
const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
|
13552
|
+
return point;
|
13553
|
+
}
|
13554
|
+
function validateSecp256k1PublicKey(key) {
|
13555
|
+
try {
|
13556
|
+
secp256k1.ProjectivePoint.fromHex(key);
|
13557
|
+
return key;
|
13558
|
+
}
|
13559
|
+
catch (err) {
|
13560
|
+
throw new InvalidPublicKeyError(String(err));
|
13561
|
+
}
|
14116
13562
|
}
|
14117
|
-
|
14118
|
-
var Secp256k1 = /*#__PURE__*/Object.freeze({
|
14119
|
-
__proto__: null,
|
14120
|
-
Secp256k1PrivateKey: Secp256k1PrivateKey,
|
14121
|
-
Secp256k1PublicKey: Secp256k1PublicKey,
|
14122
|
-
generateKeyPair: generateKeyPair,
|
14123
|
-
unmarshalSecp256k1PrivateKey: unmarshalSecp256k1PrivateKey,
|
14124
|
-
unmarshalSecp256k1PublicKey: unmarshalSecp256k1PublicKey
|
14125
|
-
});
|
14126
13563
|
|
14127
13564
|
/**
|
14128
13565
|
* @packageDocumentation
|
14129
13566
|
*
|
14130
|
-
*
|
14131
|
-
*
|
14132
|
-
* The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.
|
13567
|
+
* ## Supported Key Types
|
14133
13568
|
*
|
14134
13569
|
* Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
|
14135
13570
|
*
|
14136
13571
|
* For encryption / decryption support, RSA keys should be used.
|
14137
13572
|
*/
|
14138
|
-
const supportedKeys = {
|
14139
|
-
rsa: RSA,
|
14140
|
-
ed25519: Ed25519,
|
14141
|
-
secp256k1: Secp256k1
|
14142
|
-
};
|
14143
|
-
function unsupportedKey(type) {
|
14144
|
-
const supported = Object.keys(supportedKeys).join(' / ');
|
14145
|
-
return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
|
14146
|
-
}
|
14147
13573
|
/**
|
14148
|
-
*
|
13574
|
+
* Creates a public key from the raw key bytes
|
14149
13575
|
*/
|
14150
|
-
function
|
14151
|
-
|
14152
|
-
|
14153
|
-
|
14154
|
-
|
14155
|
-
|
14156
|
-
|
14157
|
-
|
14158
|
-
|
14159
|
-
return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);
|
14160
|
-
default:
|
14161
|
-
throw unsupportedKey(decoded.Type ?? 'unknown');
|
13576
|
+
function publicKeyFromRaw(buf) {
|
13577
|
+
if (buf.byteLength === 32) {
|
13578
|
+
return unmarshalEd25519PublicKey(buf);
|
13579
|
+
}
|
13580
|
+
else if (buf.byteLength === 33) {
|
13581
|
+
return unmarshalSecp256k1PublicKey(buf);
|
13582
|
+
}
|
13583
|
+
else {
|
13584
|
+
return pkixToRSAPublicKey(buf);
|
14162
13585
|
}
|
14163
13586
|
}
|
14164
13587
|
/**
|
14165
|
-
* Converts a
|
13588
|
+
* Converts a public key object into a protobuf serialized public key
|
14166
13589
|
*/
|
14167
|
-
|
14168
|
-
|
14169
|
-
|
14170
|
-
|
14171
|
-
|
14172
|
-
|
14173
|
-
|
14174
|
-
|
14175
|
-
|
14176
|
-
|
14177
|
-
|
14178
|
-
|
13590
|
+
function publicKeyToProtobuf(key) {
|
13591
|
+
return PublicKey.encode({
|
13592
|
+
Type: KeyType[key.type],
|
13593
|
+
Data: key.raw
|
13594
|
+
});
|
13595
|
+
}
|
13596
|
+
|
13597
|
+
/**
|
13598
|
+
* All PeerId implementations must use this symbol as the name of a property
|
13599
|
+
* with a boolean `true` value
|
13600
|
+
*/
|
13601
|
+
const peerIdSymbol = Symbol.for('@libp2p/peer-id');
|
13602
|
+
|
13603
|
+
/**
|
13604
|
+
* When this error is thrown it means an operation was aborted,
|
13605
|
+
* usually in response to the `abort` event being emitted by an
|
13606
|
+
* AbortSignal.
|
13607
|
+
*/
|
13608
|
+
/**
|
13609
|
+
* Thrown when and attempt to operate on an unsupported key was made
|
13610
|
+
*/
|
13611
|
+
class UnsupportedKeyTypeError extends Error {
|
13612
|
+
static name = 'UnsupportedKeyTypeError';
|
13613
|
+
constructor(message = 'Unsupported key type') {
|
13614
|
+
super(message);
|
13615
|
+
this.name = 'UnsupportedKeyTypeError';
|
14179
13616
|
}
|
14180
13617
|
}
|
14181
13618
|
|
@@ -14195,25 +13632,16 @@ async function unmarshalPrivateKey(buf) {
|
|
14195
13632
|
* ```
|
14196
13633
|
*/
|
14197
13634
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
14198
|
-
const baseDecoder = Object
|
14199
|
-
.values(bases)
|
14200
|
-
.map(codec => codec.decoder)
|
14201
|
-
// @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
|
14202
|
-
.reduce((acc, curr) => acc.or(curr), bases.identity.decoder);
|
14203
13635
|
// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
|
14204
13636
|
const LIBP2P_KEY_CODE = 0x72;
|
14205
|
-
const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;
|
14206
|
-
const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;
|
14207
13637
|
class PeerIdImpl {
|
14208
13638
|
type;
|
14209
13639
|
multihash;
|
14210
|
-
privateKey;
|
14211
13640
|
publicKey;
|
14212
13641
|
string;
|
14213
13642
|
constructor(init) {
|
14214
13643
|
this.type = init.type;
|
14215
13644
|
this.multihash = init.multihash;
|
14216
|
-
this.privateKey = init.privateKey;
|
14217
13645
|
// mark string cache as non-enumerable
|
14218
13646
|
Object.defineProperty(this, 'string', {
|
14219
13647
|
enumerable: false,
|
@@ -14230,17 +13658,14 @@ class PeerIdImpl {
|
|
14230
13658
|
}
|
14231
13659
|
return this.string;
|
14232
13660
|
}
|
13661
|
+
toMultihash() {
|
13662
|
+
return this.multihash;
|
13663
|
+
}
|
14233
13664
|
// return self-describing String representation
|
14234
13665
|
// in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
|
14235
13666
|
toCID() {
|
14236
13667
|
return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
|
14237
13668
|
}
|
14238
|
-
toBytes() {
|
14239
|
-
return this.multihash.bytes;
|
14240
|
-
}
|
14241
|
-
/**
|
14242
|
-
* Returns Multiaddr as a JSON string
|
14243
|
-
*/
|
14244
13669
|
toJSON() {
|
14245
13670
|
return this.toString();
|
14246
13671
|
}
|
@@ -14255,10 +13680,10 @@ class PeerIdImpl {
|
|
14255
13680
|
return equals(this.multihash.bytes, id);
|
14256
13681
|
}
|
14257
13682
|
else if (typeof id === 'string') {
|
14258
|
-
return
|
13683
|
+
return this.toString() === id;
|
14259
13684
|
}
|
14260
|
-
else if (id?.
|
14261
|
-
return equals(this.multihash.bytes, id.
|
13685
|
+
else if (id?.toMultihash()?.bytes != null) {
|
13686
|
+
return equals(this.multihash.bytes, id.toMultihash().bytes);
|
14262
13687
|
}
|
14263
13688
|
else {
|
14264
13689
|
throw new Error('not valid Id');
|
@@ -14280,7 +13705,7 @@ class PeerIdImpl {
|
|
14280
13705
|
return `PeerId(${this.toString()})`;
|
14281
13706
|
}
|
14282
13707
|
}
|
14283
|
-
class
|
13708
|
+
class RSAPeerId extends PeerIdImpl {
|
14284
13709
|
type = 'RSA';
|
14285
13710
|
publicKey;
|
14286
13711
|
constructor(init) {
|
@@ -14288,153 +13713,67 @@ class RSAPeerIdImpl extends PeerIdImpl {
|
|
14288
13713
|
this.publicKey = init.publicKey;
|
14289
13714
|
}
|
14290
13715
|
}
|
14291
|
-
class
|
13716
|
+
class Ed25519PeerId extends PeerIdImpl {
|
14292
13717
|
type = 'Ed25519';
|
14293
13718
|
publicKey;
|
14294
13719
|
constructor(init) {
|
14295
13720
|
super({ ...init, type: 'Ed25519' });
|
14296
|
-
this.publicKey = init.
|
13721
|
+
this.publicKey = init.publicKey;
|
14297
13722
|
}
|
14298
13723
|
}
|
14299
|
-
class
|
13724
|
+
class Secp256k1PeerId extends PeerIdImpl {
|
14300
13725
|
type = 'secp256k1';
|
14301
13726
|
publicKey;
|
14302
13727
|
constructor(init) {
|
14303
13728
|
super({ ...init, type: 'secp256k1' });
|
14304
|
-
this.publicKey = init.
|
14305
|
-
}
|
14306
|
-
}
|
14307
|
-
// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
|
14308
|
-
const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
|
14309
|
-
class URLPeerIdImpl {
|
14310
|
-
type = 'url';
|
14311
|
-
multihash;
|
14312
|
-
privateKey;
|
14313
|
-
publicKey;
|
14314
|
-
url;
|
14315
|
-
constructor(url) {
|
14316
|
-
this.url = url.toString();
|
14317
|
-
this.multihash = identity.digest(fromString(this.url));
|
14318
|
-
}
|
14319
|
-
[inspect]() {
|
14320
|
-
return `PeerId(${this.url})`;
|
14321
|
-
}
|
14322
|
-
[peerIdSymbol] = true;
|
14323
|
-
toString() {
|
14324
|
-
return this.toCID().toString();
|
14325
|
-
}
|
14326
|
-
toCID() {
|
14327
|
-
return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
|
14328
|
-
}
|
14329
|
-
toBytes() {
|
14330
|
-
return this.toCID().bytes;
|
14331
|
-
}
|
14332
|
-
equals(other) {
|
14333
|
-
if (other == null) {
|
14334
|
-
return false;
|
14335
|
-
}
|
14336
|
-
if (other instanceof Uint8Array) {
|
14337
|
-
other = toString$1(other);
|
14338
|
-
}
|
14339
|
-
return other.toString() === this.toString();
|
14340
|
-
}
|
14341
|
-
}
|
14342
|
-
function peerIdFromString(str, decoder) {
|
14343
|
-
if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
|
14344
|
-
// identity hash ed25519/secp256k1 key or sha2-256 hash of
|
14345
|
-
// rsa public key - base58btc encoded either way
|
14346
|
-
const multihash = decode$2(base58btc.decode(`z${str}`));
|
14347
|
-
if (str.startsWith('12D')) {
|
14348
|
-
return new Ed25519PeerIdImpl({ multihash });
|
14349
|
-
}
|
14350
|
-
else if (str.startsWith('16U')) {
|
14351
|
-
return new Secp256k1PeerIdImpl({ multihash });
|
14352
|
-
}
|
14353
|
-
else {
|
14354
|
-
return new RSAPeerIdImpl({ multihash });
|
14355
|
-
}
|
14356
|
-
}
|
14357
|
-
return peerIdFromBytes(baseDecoder.decode(str));
|
14358
|
-
}
|
14359
|
-
function peerIdFromBytes(buf) {
|
14360
|
-
try {
|
14361
|
-
const multihash = decode$2(buf);
|
14362
|
-
if (multihash.code === identity.code) {
|
14363
|
-
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
|
14364
|
-
return new Ed25519PeerIdImpl({ multihash });
|
14365
|
-
}
|
14366
|
-
else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
|
14367
|
-
return new Secp256k1PeerIdImpl({ multihash });
|
14368
|
-
}
|
14369
|
-
}
|
14370
|
-
if (multihash.code === sha256$1.code) {
|
14371
|
-
return new RSAPeerIdImpl({ multihash });
|
14372
|
-
}
|
14373
|
-
}
|
14374
|
-
catch {
|
14375
|
-
return peerIdFromCID(CID.decode(buf));
|
14376
|
-
}
|
14377
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14378
|
-
}
|
14379
|
-
function peerIdFromCID(cid) {
|
14380
|
-
if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
|
14381
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14382
|
-
}
|
14383
|
-
if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
|
14384
|
-
const url = toString$1(cid.multihash.digest);
|
14385
|
-
return new URLPeerIdImpl(new URL(url));
|
14386
|
-
}
|
14387
|
-
const multihash = cid.multihash;
|
14388
|
-
if (multihash.code === sha256$1.code) {
|
14389
|
-
return new RSAPeerIdImpl({ multihash: cid.multihash });
|
14390
|
-
}
|
14391
|
-
else if (multihash.code === identity.code) {
|
14392
|
-
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
|
14393
|
-
return new Ed25519PeerIdImpl({ multihash: cid.multihash });
|
14394
|
-
}
|
14395
|
-
else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
|
14396
|
-
return new Secp256k1PeerIdImpl({ multihash: cid.multihash });
|
14397
|
-
}
|
13729
|
+
this.publicKey = init.publicKey;
|
14398
13730
|
}
|
14399
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14400
13731
|
}
|
13732
|
+
|
14401
13733
|
/**
|
14402
|
-
* @
|
14403
|
-
*
|
13734
|
+
* @packageDocumentation
|
13735
|
+
*
|
13736
|
+
* An implementation of a peer id
|
13737
|
+
*
|
13738
|
+
* @example
|
13739
|
+
*
|
13740
|
+
* ```TypeScript
|
13741
|
+
* import { peerIdFromString } from '@libp2p/peer-id'
|
13742
|
+
* const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')
|
13743
|
+
*
|
13744
|
+
* console.log(peer.toCID()) // CID(bafzaa...)
|
13745
|
+
* console.log(peer.toString()) // "12D3K..."
|
13746
|
+
* ```
|
14404
13747
|
*/
|
14405
|
-
|
14406
|
-
if (publicKey.
|
14407
|
-
return new
|
13748
|
+
function peerIdFromPublicKey(publicKey) {
|
13749
|
+
if (publicKey.type === 'Ed25519') {
|
13750
|
+
return new Ed25519PeerId({
|
13751
|
+
multihash: publicKey.toCID().multihash,
|
13752
|
+
publicKey
|
13753
|
+
});
|
13754
|
+
}
|
13755
|
+
else if (publicKey.type === 'secp256k1') {
|
13756
|
+
return new Secp256k1PeerId({
|
13757
|
+
multihash: publicKey.toCID().multihash,
|
13758
|
+
publicKey
|
13759
|
+
});
|
14408
13760
|
}
|
14409
|
-
if (publicKey.
|
14410
|
-
return new
|
13761
|
+
else if (publicKey.type === 'RSA') {
|
13762
|
+
return new RSAPeerId({
|
13763
|
+
multihash: publicKey.toCID().multihash,
|
13764
|
+
publicKey
|
13765
|
+
});
|
14411
13766
|
}
|
14412
|
-
|
13767
|
+
throw new UnsupportedKeyTypeError();
|
14413
13768
|
}
|
14414
13769
|
|
13770
|
+
const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
|
14415
13771
|
function createPeerIdFromPublicKey(publicKey) {
|
14416
|
-
const
|
14417
|
-
|
14418
|
-
|
14419
|
-
function getPublicKeyFromPeerId(peerId) {
|
14420
|
-
if (peerId.type !== "secp256k1") {
|
14421
|
-
throw new Error("Unsupported peer id type");
|
14422
|
-
}
|
14423
|
-
if (!peerId.publicKey) {
|
14424
|
-
throw new Error("Public key not present on peer id");
|
14425
|
-
}
|
14426
|
-
return unmarshalPublicKey(peerId.publicKey).marshal();
|
14427
|
-
}
|
14428
|
-
// Only used in tests
|
14429
|
-
async function getPrivateKeyFromPeerId(peerId) {
|
14430
|
-
if (peerId.type !== "secp256k1") {
|
14431
|
-
throw new Error("Unsupported peer id type");
|
14432
|
-
}
|
14433
|
-
if (!peerId.privateKey) {
|
14434
|
-
throw new Error("Private key not present on peer id");
|
13772
|
+
const pubKey = publicKeyFromRaw(publicKey);
|
13773
|
+
if (pubKey.type !== "secp256k1") {
|
13774
|
+
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
|
14435
13775
|
}
|
14436
|
-
|
14437
|
-
return privateKey.marshal();
|
13776
|
+
return peerIdFromPublicKey(pubKey);
|
14438
13777
|
}
|
14439
13778
|
|
14440
13779
|
function decodeMultiaddrs(bytes) {
|
@@ -14681,12 +14020,12 @@ var TransportProtocolPerIpVersion;
|
|
14681
14020
|
class ENR extends RawEnr {
|
14682
14021
|
static RECORD_PREFIX = "enr:";
|
14683
14022
|
peerId;
|
14684
|
-
static
|
14023
|
+
static create(kvs = {}, seq = BigInt(1), signature) {
|
14685
14024
|
const enr = new ENR(kvs, seq, signature);
|
14686
14025
|
try {
|
14687
14026
|
const publicKey = enr.publicKey;
|
14688
14027
|
if (publicKey) {
|
14689
|
-
enr.peerId =
|
14028
|
+
enr.peerId = createPeerIdFromPublicKey(publicKey);
|
14690
14029
|
}
|
14691
14030
|
}
|
14692
14031
|
catch (e) {
|
@@ -14808,7 +14147,7 @@ class EnrCreator {
|
|
14808
14147
|
static fromPublicKey(publicKey, kvs = {}) {
|
14809
14148
|
// EIP-778 specifies that the key must be in compressed format, 33 bytes
|
14810
14149
|
if (publicKey.length !== 33) {
|
14811
|
-
publicKey = compressPublicKey
|
14150
|
+
publicKey = compressPublicKey(publicKey);
|
14812
14151
|
}
|
14813
14152
|
return ENR.create({
|
14814
14153
|
...kvs,
|
@@ -14819,7 +14158,7 @@ class EnrCreator {
|
|
14819
14158
|
static async fromPeerId(peerId, kvs = {}) {
|
14820
14159
|
switch (peerId.type) {
|
14821
14160
|
case "secp256k1":
|
14822
|
-
return EnrCreator.fromPublicKey(
|
14161
|
+
return EnrCreator.fromPublicKey(peerId.publicKey.raw, kvs);
|
14823
14162
|
default:
|
14824
14163
|
throw new Error();
|
14825
14164
|
}
|
@@ -15473,7 +14812,7 @@ async function fromValues(values) {
|
|
15473
14812
|
}
|
15474
14813
|
}
|
15475
14814
|
const _seq = decodeSeq(seq);
|
15476
|
-
const enr =
|
14815
|
+
const enr = ENR.create(obj, _seq, signature);
|
15477
14816
|
checkSignature(seq, kvs, enr, signature);
|
15478
14817
|
return enr;
|
15479
14818
|
}
|
@@ -15506,4 +14845,4 @@ function checkSignature(seq, kvs, enr, signature) {
|
|
15506
14845
|
}
|
15507
14846
|
}
|
15508
14847
|
|
15509
|
-
export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey
|
14848
|
+
export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, ERR_TYPE_NOT_IMPLEMENTED, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey, createPeerIdFromPublicKey, decodeWaku2, encodeWaku2, keccak256, sign$1 as sign, verifySignature };
|