@waku/enr 0.0.27-f599932.0 โ 0.0.28-5674b0e.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/CHANGELOG.md +8 -0
- package/bundle/index.js +719 -1393
- 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) {
|
@@ -4314,7 +4316,6 @@ var debug = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
|
|
4314
4316
|
|
4315
4317
|
const APP_NAME = "waku";
|
4316
4318
|
let Logger$1 = class Logger {
|
4317
|
-
_debug;
|
4318
4319
|
_info;
|
4319
4320
|
_warn;
|
4320
4321
|
_error;
|
@@ -4322,14 +4323,10 @@ let Logger$1 = class Logger {
|
|
4322
4323
|
return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;
|
4323
4324
|
}
|
4324
4325
|
constructor(prefix) {
|
4325
|
-
this._debug = debug(Logger.createDebugNamespace("debug", prefix));
|
4326
4326
|
this._info = debug(Logger.createDebugNamespace("info", prefix));
|
4327
4327
|
this._warn = debug(Logger.createDebugNamespace("warn", prefix));
|
4328
4328
|
this._error = debug(Logger.createDebugNamespace("error", prefix));
|
4329
4329
|
}
|
4330
|
-
get debug() {
|
4331
|
-
return this._debug;
|
4332
|
-
}
|
4333
4330
|
get info() {
|
4334
4331
|
return this._info;
|
4335
4332
|
}
|
@@ -4345,34 +4342,6 @@ let Logger$1 = class Logger {
|
|
4345
4342
|
}
|
4346
4343
|
};
|
4347
4344
|
|
4348
|
-
const peerIdSymbol = Symbol.for('@libp2p/peer-id');
|
4349
|
-
|
4350
|
-
/**
|
4351
|
-
* When this error is thrown it means an operation was aborted,
|
4352
|
-
* usually in response to the `abort` event being emitted by an
|
4353
|
-
* AbortSignal.
|
4354
|
-
*/
|
4355
|
-
class CodeError extends Error {
|
4356
|
-
code;
|
4357
|
-
props;
|
4358
|
-
constructor(message, code, props) {
|
4359
|
-
super(message);
|
4360
|
-
this.code = code;
|
4361
|
-
this.name = props?.name ?? 'CodeError';
|
4362
|
-
this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
|
4363
|
-
}
|
4364
|
-
}
|
4365
|
-
class AggregateCodeError extends AggregateError {
|
4366
|
-
code;
|
4367
|
-
props;
|
4368
|
-
constructor(errors, message, code, props) {
|
4369
|
-
super(errors, message);
|
4370
|
-
this.code = code;
|
4371
|
-
this.name = props?.name ?? 'AggregateCodeError';
|
4372
|
-
this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions
|
4373
|
-
}
|
4374
|
-
}
|
4375
|
-
|
4376
4345
|
/**
|
4377
4346
|
* Returns true if the two passed Uint8Arrays have the same content
|
4378
4347
|
*/
|
@@ -5430,6 +5399,12 @@ const DNS_CODES = [
|
|
5430
5399
|
getProtocol('dns6').code,
|
5431
5400
|
getProtocol('dnsaddr').code
|
5432
5401
|
];
|
5402
|
+
class NoAvailableResolverError extends Error {
|
5403
|
+
constructor(message = 'No available resolver') {
|
5404
|
+
super(message);
|
5405
|
+
this.name = 'NoAvailableResolverError';
|
5406
|
+
}
|
5407
|
+
}
|
5433
5408
|
/**
|
5434
5409
|
* Creates a {@link Multiaddr} from a {@link MultiaddrInput}
|
5435
5410
|
*/
|
@@ -5599,7 +5574,7 @@ class Multiaddr {
|
|
5599
5574
|
}
|
5600
5575
|
const resolver = resolvers.get(resolvableProto.name);
|
5601
5576
|
if (resolver == null) {
|
5602
|
-
throw new
|
5577
|
+
throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);
|
5603
5578
|
}
|
5604
5579
|
const result = await resolver(this, options);
|
5605
5580
|
return result.map(str => multiaddr(str));
|
@@ -5813,13 +5788,30 @@ function locationMultiaddrFromEnrFields(enr, protocol) {
|
|
5813
5788
|
return multiaddrFromFields(isIpv6 ? "ip6" : "ip4", protoName, ipVal, protoVal);
|
5814
5789
|
}
|
5815
5790
|
|
5816
|
-
|
5817
|
-
|
5818
|
-
|
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';
|
5819
5814
|
}
|
5820
|
-
return typeof thing.then === 'function' &&
|
5821
|
-
typeof thing.catch === 'function' &&
|
5822
|
-
typeof thing.finally === 'function';
|
5823
5815
|
}
|
5824
5816
|
|
5825
5817
|
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
@@ -6907,6 +6899,60 @@ function wNAF(c, bits) {
|
|
6907
6899
|
},
|
6908
6900
|
};
|
6909
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
|
+
}
|
6910
6956
|
function validateBasic(curve) {
|
6911
6957
|
validateField(curve.Fp);
|
6912
6958
|
validateObject(curve, {
|
@@ -6961,6 +7007,7 @@ function twistedEdwards(curveDef) {
|
|
6961
7007
|
const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;
|
6962
7008
|
const MASK = _2n$2 << (BigInt(nByteLength * 8) - _1n$3);
|
6963
7009
|
const modP = Fp.create; // Function overrides
|
7010
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
6964
7011
|
// sqrt(u/v)
|
6965
7012
|
const uvRatio = CURVE.uvRatio ||
|
6966
7013
|
((u, v) => {
|
@@ -7059,6 +7106,10 @@ function twistedEdwards(curveDef) {
|
|
7059
7106
|
const toInv = Fp.invertBatch(points.map((p) => p.ez));
|
7060
7107
|
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
|
7061
7108
|
}
|
7109
|
+
// Multiscalar Multiplication
|
7110
|
+
static msm(points, scalars) {
|
7111
|
+
return pippenger(Point, Fn, points, scalars);
|
7112
|
+
}
|
7062
7113
|
// "Private method", don't use it directly
|
7063
7114
|
_setWindowSize(windowSize) {
|
7064
7115
|
wnaf.setWindowSize(this, windowSize);
|
@@ -7434,7 +7485,7 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
|
|
7434
7485
|
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
|
7435
7486
|
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
|
7436
7487
|
hash: sha512,
|
7437
|
-
randomBytes
|
7488
|
+
randomBytes,
|
7438
7489
|
adjustScalarBytes,
|
7439
7490
|
// dom2
|
7440
7491
|
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
|
@@ -7447,176 +7498,46 @@ const ed25519Defaults = /* @__PURE__ */ (() => ({
|
|
7447
7498
|
const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();
|
7448
7499
|
|
7449
7500
|
const PUBLIC_KEY_BYTE_LENGTH = 32;
|
7450
|
-
const PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys
|
7451
|
-
const KEYS_BYTE_LENGTH = 32;
|
7452
|
-
function generateKey$2() {
|
7453
|
-
// the actual private key (32 bytes)
|
7454
|
-
const privateKeyRaw = ed25519.utils.randomPrivateKey();
|
7455
|
-
const publicKey = ed25519.getPublicKey(privateKeyRaw);
|
7456
|
-
// concatenated the public key to the private key
|
7457
|
-
const privateKey = concatKeys(privateKeyRaw, publicKey);
|
7458
|
-
return {
|
7459
|
-
privateKey,
|
7460
|
-
publicKey
|
7461
|
-
};
|
7462
|
-
}
|
7463
|
-
/**
|
7464
|
-
* Generate keypair from a 32 byte uint8array
|
7465
|
-
*/
|
7466
|
-
function generateKeyFromSeed(seed) {
|
7467
|
-
if (seed.length !== KEYS_BYTE_LENGTH) {
|
7468
|
-
throw new TypeError('"seed" must be 32 bytes in length.');
|
7469
|
-
}
|
7470
|
-
else if (!(seed instanceof Uint8Array)) {
|
7471
|
-
throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');
|
7472
|
-
}
|
7473
|
-
// based on node forges algorithm, the seed is used directly as private key
|
7474
|
-
const privateKeyRaw = seed;
|
7475
|
-
const publicKey = ed25519.getPublicKey(privateKeyRaw);
|
7476
|
-
const privateKey = concatKeys(privateKeyRaw, publicKey);
|
7477
|
-
return {
|
7478
|
-
privateKey,
|
7479
|
-
publicKey
|
7480
|
-
};
|
7481
|
-
}
|
7482
|
-
function hashAndSign$2(privateKey, msg) {
|
7483
|
-
const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);
|
7484
|
-
return ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);
|
7485
|
-
}
|
7486
7501
|
function hashAndVerify$2(publicKey, sig, msg) {
|
7487
7502
|
return ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);
|
7488
7503
|
}
|
7489
|
-
function concatKeys(privateKeyRaw, publicKey) {
|
7490
|
-
const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);
|
7491
|
-
for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {
|
7492
|
-
privateKey[i] = privateKeyRaw[i];
|
7493
|
-
privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];
|
7494
|
-
}
|
7495
|
-
return privateKey;
|
7496
|
-
}
|
7497
7504
|
|
7498
|
-
|
7499
|
-
|
7500
|
-
|
7501
|
-
|
7502
|
-
|
7503
|
-
const nativeCrypto = win.crypto;
|
7504
|
-
if (nativeCrypto?.subtle == null) {
|
7505
|
-
throw Object.assign(new Error('Missing Web Crypto API. ' +
|
7506
|
-
'The most likely cause of this error is that this page is being accessed ' +
|
7507
|
-
'from an insecure context (i.e. not HTTPS). For more information and ' +
|
7508
|
-
'possible resolutions see ' +
|
7509
|
-
'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });
|
7510
|
-
}
|
7511
|
-
return nativeCrypto;
|
7505
|
+
class Ed25519PublicKey {
|
7506
|
+
type = 'Ed25519';
|
7507
|
+
raw;
|
7508
|
+
constructor(key) {
|
7509
|
+
this.raw = ensureEd25519Key(key, PUBLIC_KEY_BYTE_LENGTH);
|
7512
7510
|
}
|
7513
|
-
|
7514
|
-
|
7515
|
-
|
7516
|
-
|
7517
|
-
|
7518
|
-
|
7519
|
-
|
7520
|
-
|
7521
|
-
|
7522
|
-
|
7523
|
-
|
7524
|
-
|
7525
|
-
const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };
|
7526
|
-
// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples
|
7527
|
-
function create(opts) {
|
7528
|
-
const algorithm = 'AES-GCM';
|
7529
|
-
let keyLength = 16;
|
7530
|
-
const nonceLength = 12;
|
7531
|
-
const digest = 'SHA-256';
|
7532
|
-
const saltLength = 16;
|
7533
|
-
const iterations = 32767;
|
7534
|
-
const crypto = webcrypto.get();
|
7535
|
-
keyLength *= 8; // Browser crypto uses bits instead of bytes
|
7536
|
-
/**
|
7537
|
-
* Uses the provided password to derive a pbkdf2 key. The key
|
7538
|
-
* will then be used to encrypt the data.
|
7539
|
-
*/
|
7540
|
-
async function encrypt(data, password) {
|
7541
|
-
const salt = crypto.getRandomValues(new Uint8Array(saltLength));
|
7542
|
-
const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));
|
7543
|
-
const aesGcm = { name: algorithm, iv: nonce };
|
7544
|
-
if (typeof password === 'string') {
|
7545
|
-
password = fromString(password);
|
7546
|
-
}
|
7547
|
-
let cryptoKey;
|
7548
|
-
if (password.length === 0) {
|
7549
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
|
7550
|
-
try {
|
7551
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7552
|
-
const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7553
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);
|
7554
|
-
}
|
7555
|
-
catch {
|
7556
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);
|
7557
|
-
}
|
7558
|
-
}
|
7559
|
-
else {
|
7560
|
-
// Derive a key using PBKDF2.
|
7561
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7562
|
-
const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7563
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);
|
7564
|
-
}
|
7565
|
-
// Encrypt the string.
|
7566
|
-
const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);
|
7567
|
-
return concat$1([salt, aesGcm.iv, new Uint8Array(ciphertext)]);
|
7568
|
-
}
|
7569
|
-
/**
|
7570
|
-
* Uses the provided password to derive a pbkdf2 key. The key
|
7571
|
-
* will then be used to decrypt the data. The options used to create
|
7572
|
-
* this decryption cipher must be the same as those used to create
|
7573
|
-
* the encryption cipher.
|
7574
|
-
*/
|
7575
|
-
async function decrypt(data, password) {
|
7576
|
-
const salt = data.subarray(0, saltLength);
|
7577
|
-
const nonce = data.subarray(saltLength, saltLength + nonceLength);
|
7578
|
-
const ciphertext = data.subarray(saltLength + nonceLength);
|
7579
|
-
const aesGcm = { name: algorithm, iv: nonce };
|
7580
|
-
if (typeof password === 'string') {
|
7581
|
-
password = fromString(password);
|
7582
|
-
}
|
7583
|
-
let cryptoKey;
|
7584
|
-
if (password.length === 0) {
|
7585
|
-
try {
|
7586
|
-
const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };
|
7587
|
-
const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);
|
7588
|
-
cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);
|
7589
|
-
}
|
7590
|
-
catch {
|
7591
|
-
cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);
|
7592
|
-
}
|
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;
|
7593
7523
|
}
|
7594
|
-
|
7595
|
-
|
7596
|
-
|
7597
|
-
|
7598
|
-
|
7599
|
-
}
|
7600
|
-
// Decrypt the string.
|
7601
|
-
const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);
|
7602
|
-
return new Uint8Array(plaintext);
|
7603
|
-
}
|
7604
|
-
const cipher = {
|
7605
|
-
encrypt,
|
7606
|
-
decrypt
|
7607
|
-
};
|
7608
|
-
return cipher;
|
7524
|
+
return equals(this.raw, key.raw);
|
7525
|
+
}
|
7526
|
+
verify(data, sig) {
|
7527
|
+
return hashAndVerify$2(this.raw, sig, data);
|
7528
|
+
}
|
7609
7529
|
}
|
7610
7530
|
|
7611
|
-
|
7612
|
-
|
7613
|
-
|
7614
|
-
|
7615
|
-
|
7616
|
-
|
7617
|
-
|
7618
|
-
|
7619
|
-
|
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;
|
7620
7541
|
}
|
7621
7542
|
|
7622
7543
|
const f32 = new Float32Array([-0]);
|
@@ -8825,13 +8746,13 @@ var KeyType;
|
|
8825
8746
|
(function (KeyType) {
|
8826
8747
|
KeyType["RSA"] = "RSA";
|
8827
8748
|
KeyType["Ed25519"] = "Ed25519";
|
8828
|
-
KeyType["
|
8749
|
+
KeyType["secp256k1"] = "secp256k1";
|
8829
8750
|
})(KeyType || (KeyType = {}));
|
8830
8751
|
var __KeyTypeValues;
|
8831
8752
|
(function (__KeyTypeValues) {
|
8832
8753
|
__KeyTypeValues[__KeyTypeValues["RSA"] = 0] = "RSA";
|
8833
8754
|
__KeyTypeValues[__KeyTypeValues["Ed25519"] = 1] = "Ed25519";
|
8834
|
-
__KeyTypeValues[__KeyTypeValues["
|
8755
|
+
__KeyTypeValues[__KeyTypeValues["secp256k1"] = 2] = "secp256k1";
|
8835
8756
|
})(__KeyTypeValues || (__KeyTypeValues = {}));
|
8836
8757
|
(function (KeyType) {
|
8837
8758
|
KeyType.codec = () => {
|
@@ -8858,21 +8779,24 @@ var PublicKey;
|
|
8858
8779
|
if (opts.lengthDelimited !== false) {
|
8859
8780
|
w.ldelim();
|
8860
8781
|
}
|
8861
|
-
}, (reader, length) => {
|
8782
|
+
}, (reader, length, opts = {}) => {
|
8862
8783
|
const obj = {};
|
8863
8784
|
const end = length == null ? reader.len : reader.pos + length;
|
8864
8785
|
while (reader.pos < end) {
|
8865
8786
|
const tag = reader.uint32();
|
8866
8787
|
switch (tag >>> 3) {
|
8867
|
-
case 1:
|
8788
|
+
case 1: {
|
8868
8789
|
obj.Type = KeyType.codec().decode(reader);
|
8869
8790
|
break;
|
8870
|
-
|
8791
|
+
}
|
8792
|
+
case 2: {
|
8871
8793
|
obj.Data = reader.bytes();
|
8872
8794
|
break;
|
8873
|
-
|
8795
|
+
}
|
8796
|
+
default: {
|
8874
8797
|
reader.skipType(tag & 7);
|
8875
8798
|
break;
|
8799
|
+
}
|
8876
8800
|
}
|
8877
8801
|
}
|
8878
8802
|
return obj;
|
@@ -8883,8 +8807,8 @@ var PublicKey;
|
|
8883
8807
|
PublicKey.encode = (obj) => {
|
8884
8808
|
return encodeMessage(obj, PublicKey.codec());
|
8885
8809
|
};
|
8886
|
-
PublicKey.decode = (buf) => {
|
8887
|
-
return decodeMessage(buf, PublicKey.codec());
|
8810
|
+
PublicKey.decode = (buf, opts) => {
|
8811
|
+
return decodeMessage(buf, PublicKey.codec(), opts);
|
8888
8812
|
};
|
8889
8813
|
})(PublicKey || (PublicKey = {}));
|
8890
8814
|
var PrivateKey;
|
@@ -8907,21 +8831,24 @@ var PrivateKey;
|
|
8907
8831
|
if (opts.lengthDelimited !== false) {
|
8908
8832
|
w.ldelim();
|
8909
8833
|
}
|
8910
|
-
}, (reader, length) => {
|
8834
|
+
}, (reader, length, opts = {}) => {
|
8911
8835
|
const obj = {};
|
8912
8836
|
const end = length == null ? reader.len : reader.pos + length;
|
8913
8837
|
while (reader.pos < end) {
|
8914
8838
|
const tag = reader.uint32();
|
8915
8839
|
switch (tag >>> 3) {
|
8916
|
-
case 1:
|
8840
|
+
case 1: {
|
8917
8841
|
obj.Type = KeyType.codec().decode(reader);
|
8918
8842
|
break;
|
8919
|
-
|
8843
|
+
}
|
8844
|
+
case 2: {
|
8920
8845
|
obj.Data = reader.bytes();
|
8921
8846
|
break;
|
8922
|
-
|
8847
|
+
}
|
8848
|
+
default: {
|
8923
8849
|
reader.skipType(tag & 7);
|
8924
8850
|
break;
|
8851
|
+
}
|
8925
8852
|
}
|
8926
8853
|
}
|
8927
8854
|
return obj;
|
@@ -8932,393 +8859,122 @@ var PrivateKey;
|
|
8932
8859
|
PrivateKey.encode = (obj) => {
|
8933
8860
|
return encodeMessage(obj, PrivateKey.codec());
|
8934
8861
|
};
|
8935
|
-
PrivateKey.decode = (buf) => {
|
8936
|
-
return decodeMessage(buf, PrivateKey.codec());
|
8862
|
+
PrivateKey.decode = (buf, opts) => {
|
8863
|
+
return decodeMessage(buf, PrivateKey.codec(), opts);
|
8937
8864
|
};
|
8938
8865
|
})(PrivateKey || (PrivateKey = {}));
|
8939
8866
|
|
8940
|
-
|
8941
|
-
|
8942
|
-
|
8943
|
-
|
8944
|
-
|
8945
|
-
|
8946
|
-
|
8947
|
-
|
8948
|
-
|
8949
|
-
|
8950
|
-
|
8951
|
-
|
8952
|
-
|
8953
|
-
|
8954
|
-
|
8955
|
-
|
8956
|
-
|
8957
|
-
|
8958
|
-
|
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;
|
8959
8896
|
}
|
8960
|
-
|
8961
|
-
|
8962
|
-
|
8963
|
-
return p.then(({ bytes }) => bytes);
|
8897
|
+
static toArrayBuffer(data) {
|
8898
|
+
if (this.isArrayBuffer(data)) {
|
8899
|
+
return data;
|
8964
8900
|
}
|
8965
|
-
|
8966
|
-
|
8967
|
-
}
|
8968
|
-
|
8969
|
-
|
8970
|
-
|
8971
|
-
|
8972
|
-
|
8973
|
-
|
8974
|
-
this._key = ensureKey(key, PRIVATE_KEY_BYTE_LENGTH);
|
8975
|
-
this._publicKey = ensureKey(publicKey, PUBLIC_KEY_BYTE_LENGTH);
|
8976
|
-
}
|
8977
|
-
sign(message) {
|
8978
|
-
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;
|
8979
8910
|
}
|
8980
|
-
|
8981
|
-
return
|
8911
|
+
static toUint8Array(data) {
|
8912
|
+
return this.toView(data, Uint8Array);
|
8982
8913
|
}
|
8983
|
-
|
8984
|
-
|
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)'");
|
8985
8925
|
}
|
8986
|
-
|
8987
|
-
return
|
8988
|
-
|
8989
|
-
Data: this.marshal()
|
8990
|
-
}).subarray();
|
8926
|
+
static isBufferSource(data) {
|
8927
|
+
return this.isArrayBufferView(data)
|
8928
|
+
|| this.isArrayBuffer(data);
|
8991
8929
|
}
|
8992
|
-
|
8993
|
-
return
|
8930
|
+
static isArrayBufferView(data) {
|
8931
|
+
return ArrayBuffer.isView(data)
|
8932
|
+
|| (data && this.isArrayBuffer(data.buffer));
|
8994
8933
|
}
|
8995
|
-
|
8996
|
-
const
|
8997
|
-
|
8998
|
-
if (
|
8999
|
-
|
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;
|
9000
8939
|
}
|
9001
|
-
|
9002
|
-
|
8940
|
+
for (let i = 0; i < aView.length; i++) {
|
8941
|
+
if (aView[i] !== bView[i]) {
|
8942
|
+
return false;
|
8943
|
+
}
|
9003
8944
|
}
|
9004
|
-
return
|
9005
|
-
}
|
9006
|
-
/**
|
9007
|
-
* Gets the ID of the key.
|
9008
|
-
*
|
9009
|
-
* The key id is the base58 encoding of the identity multihash containing its public key.
|
9010
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
9011
|
-
* of the PKCS SubjectPublicKeyInfo.
|
9012
|
-
*
|
9013
|
-
* @returns {Promise<string>}
|
9014
|
-
*/
|
9015
|
-
async id() {
|
9016
|
-
const encoding = identity.digest(this.public.bytes);
|
9017
|
-
return base58btc.encode(encoding.bytes).substring(1);
|
8945
|
+
return true;
|
9018
8946
|
}
|
9019
|
-
|
9020
|
-
|
9021
|
-
|
9022
|
-
|
9023
|
-
|
9024
|
-
|
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];
|
9025
8954
|
}
|
9026
8955
|
else {
|
9027
|
-
|
8956
|
+
if (args[args.length - 1] instanceof Function) {
|
8957
|
+
buffers = args.slice(0, args.length - 1);
|
8958
|
+
}
|
8959
|
+
else {
|
8960
|
+
buffers = args;
|
8961
|
+
}
|
9028
8962
|
}
|
9029
|
-
|
9030
|
-
|
9031
|
-
|
9032
|
-
|
9033
|
-
|
9034
|
-
|
9035
|
-
const
|
9036
|
-
|
9037
|
-
|
9038
|
-
|
9039
|
-
|
9040
|
-
|
9041
|
-
|
9042
|
-
|
9043
|
-
|
9044
|
-
function unmarshalEd25519PublicKey(bytes) {
|
9045
|
-
bytes = ensureKey(bytes, PUBLIC_KEY_BYTE_LENGTH);
|
9046
|
-
return new Ed25519PublicKey(bytes);
|
9047
|
-
}
|
9048
|
-
async function generateKeyPair$2() {
|
9049
|
-
const { privateKey, publicKey } = generateKey$2();
|
9050
|
-
return new Ed25519PrivateKey(privateKey, publicKey);
|
9051
|
-
}
|
9052
|
-
async function generateKeyPairFromSeed(seed) {
|
9053
|
-
const { privateKey, publicKey } = generateKeyFromSeed(seed);
|
9054
|
-
return new Ed25519PrivateKey(privateKey, publicKey);
|
9055
|
-
}
|
9056
|
-
function ensureKey(key, length) {
|
9057
|
-
key = Uint8Array.from(key ?? []);
|
9058
|
-
if (key.length !== length) {
|
9059
|
-
throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');
|
9060
|
-
}
|
9061
|
-
return key;
|
9062
|
-
}
|
9063
|
-
|
9064
|
-
var Ed25519 = /*#__PURE__*/Object.freeze({
|
9065
|
-
__proto__: null,
|
9066
|
-
Ed25519PrivateKey: Ed25519PrivateKey,
|
9067
|
-
Ed25519PublicKey: Ed25519PublicKey,
|
9068
|
-
generateKeyPair: generateKeyPair$2,
|
9069
|
-
generateKeyPairFromSeed: generateKeyPairFromSeed,
|
9070
|
-
unmarshalEd25519PrivateKey: unmarshalEd25519PrivateKey,
|
9071
|
-
unmarshalEd25519PublicKey: unmarshalEd25519PublicKey
|
9072
|
-
});
|
9073
|
-
|
9074
|
-
/**
|
9075
|
-
* Generates a Uint8Array with length `number` populated by random bytes
|
9076
|
-
*/
|
9077
|
-
function randomBytes(length) {
|
9078
|
-
if (isNaN(length) || length <= 0) {
|
9079
|
-
throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');
|
9080
|
-
}
|
9081
|
-
return randomBytes$1(length);
|
9082
|
-
}
|
9083
|
-
|
9084
|
-
// HMAC (RFC 2104)
|
9085
|
-
class HMAC extends Hash {
|
9086
|
-
constructor(hash$1, _key) {
|
9087
|
-
super();
|
9088
|
-
this.finished = false;
|
9089
|
-
this.destroyed = false;
|
9090
|
-
hash(hash$1);
|
9091
|
-
const key = toBytes$1(_key);
|
9092
|
-
this.iHash = hash$1.create();
|
9093
|
-
if (typeof this.iHash.update !== 'function')
|
9094
|
-
throw new Error('Expected instance of class which extends utils.Hash');
|
9095
|
-
this.blockLen = this.iHash.blockLen;
|
9096
|
-
this.outputLen = this.iHash.outputLen;
|
9097
|
-
const blockLen = this.blockLen;
|
9098
|
-
const pad = new Uint8Array(blockLen);
|
9099
|
-
// blockLen can be bigger than outputLen
|
9100
|
-
pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
|
9101
|
-
for (let i = 0; i < pad.length; i++)
|
9102
|
-
pad[i] ^= 0x36;
|
9103
|
-
this.iHash.update(pad);
|
9104
|
-
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
|
9105
|
-
this.oHash = hash$1.create();
|
9106
|
-
// Undo internal XOR && apply outer XOR
|
9107
|
-
for (let i = 0; i < pad.length; i++)
|
9108
|
-
pad[i] ^= 0x36 ^ 0x5c;
|
9109
|
-
this.oHash.update(pad);
|
9110
|
-
pad.fill(0);
|
9111
|
-
}
|
9112
|
-
update(buf) {
|
9113
|
-
exists(this);
|
9114
|
-
this.iHash.update(buf);
|
9115
|
-
return this;
|
9116
|
-
}
|
9117
|
-
digestInto(out) {
|
9118
|
-
exists(this);
|
9119
|
-
bytes(out, this.outputLen);
|
9120
|
-
this.finished = true;
|
9121
|
-
this.iHash.digestInto(out);
|
9122
|
-
this.oHash.update(out);
|
9123
|
-
this.oHash.digestInto(out);
|
9124
|
-
this.destroy();
|
9125
|
-
}
|
9126
|
-
digest() {
|
9127
|
-
const out = new Uint8Array(this.oHash.outputLen);
|
9128
|
-
this.digestInto(out);
|
9129
|
-
return out;
|
9130
|
-
}
|
9131
|
-
_cloneInto(to) {
|
9132
|
-
// Create new instance without calling constructor since key already in state and we don't know it.
|
9133
|
-
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
9134
|
-
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
9135
|
-
to = to;
|
9136
|
-
to.finished = finished;
|
9137
|
-
to.destroyed = destroyed;
|
9138
|
-
to.blockLen = blockLen;
|
9139
|
-
to.outputLen = outputLen;
|
9140
|
-
to.oHash = oHash._cloneInto(to.oHash);
|
9141
|
-
to.iHash = iHash._cloneInto(to.iHash);
|
9142
|
-
return to;
|
9143
|
-
}
|
9144
|
-
destroy() {
|
9145
|
-
this.destroyed = true;
|
9146
|
-
this.oHash.destroy();
|
9147
|
-
this.iHash.destroy();
|
9148
|
-
}
|
9149
|
-
}
|
9150
|
-
/**
|
9151
|
-
* HMAC: RFC2104 message authentication code.
|
9152
|
-
* @param hash - function that would be used e.g. sha256
|
9153
|
-
* @param key - message key
|
9154
|
-
* @param message - message data
|
9155
|
-
*/
|
9156
|
-
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
9157
|
-
hmac.create = (hash, key) => new HMAC(hash, key);
|
9158
|
-
|
9159
|
-
// Common prologue and epilogue for sync/async functions
|
9160
|
-
function pbkdf2Init(hash$1, _password, _salt, _opts) {
|
9161
|
-
hash(hash$1);
|
9162
|
-
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
|
9163
|
-
const { c, dkLen, asyncTick } = opts;
|
9164
|
-
number(c);
|
9165
|
-
number(dkLen);
|
9166
|
-
number(asyncTick);
|
9167
|
-
if (c < 1)
|
9168
|
-
throw new Error('PBKDF2: iterations (c) should be >= 1');
|
9169
|
-
const password = toBytes$1(_password);
|
9170
|
-
const salt = toBytes$1(_salt);
|
9171
|
-
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
|
9172
|
-
const DK = new Uint8Array(dkLen);
|
9173
|
-
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
9174
|
-
const PRF = hmac.create(hash$1, password);
|
9175
|
-
const PRFSalt = PRF._cloneInto().update(salt);
|
9176
|
-
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
|
9177
|
-
}
|
9178
|
-
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
|
9179
|
-
PRF.destroy();
|
9180
|
-
PRFSalt.destroy();
|
9181
|
-
if (prfW)
|
9182
|
-
prfW.destroy();
|
9183
|
-
u.fill(0);
|
9184
|
-
return DK;
|
9185
|
-
}
|
9186
|
-
async function pbkdf2Async(hash, password, salt, opts) {
|
9187
|
-
const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
|
9188
|
-
let prfW; // Working copy
|
9189
|
-
const arr = new Uint8Array(4);
|
9190
|
-
const view = createView(arr);
|
9191
|
-
const u = new Uint8Array(PRF.outputLen);
|
9192
|
-
// DK = T1 + T2 + โฏ + Tdklen/hlen
|
9193
|
-
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
|
9194
|
-
// Ti = F(Password, Salt, c, i)
|
9195
|
-
const Ti = DK.subarray(pos, pos + PRF.outputLen);
|
9196
|
-
view.setInt32(0, ti, false);
|
9197
|
-
// F(Password, Salt, c, i) = U1 ^ U2 ^ โฏ ^ Uc
|
9198
|
-
// U1 = PRF(Password, Salt + INT_32_BE(i))
|
9199
|
-
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
|
9200
|
-
Ti.set(u.subarray(0, Ti.length));
|
9201
|
-
await asyncLoop(c - 1, asyncTick, () => {
|
9202
|
-
// Uc = PRF(Password, Ucโ1)
|
9203
|
-
PRF._cloneInto(prfW).update(u).digestInto(u);
|
9204
|
-
for (let i = 0; i < Ti.length; i++)
|
9205
|
-
Ti[i] ^= u[i];
|
9206
|
-
});
|
9207
|
-
}
|
9208
|
-
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
|
9209
|
-
}
|
9210
|
-
|
9211
|
-
/*!
|
9212
|
-
* MIT License
|
9213
|
-
*
|
9214
|
-
* Copyright (c) 2017-2022 Peculiar Ventures, LLC
|
9215
|
-
*
|
9216
|
-
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
9217
|
-
* of this software and associated documentation files (the "Software"), to deal
|
9218
|
-
* in the Software without restriction, including without limitation the rights
|
9219
|
-
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9220
|
-
* copies of the Software, and to permit persons to whom the Software is
|
9221
|
-
* furnished to do so, subject to the following conditions:
|
9222
|
-
*
|
9223
|
-
* The above copyright notice and this permission notice shall be included in all
|
9224
|
-
* copies or substantial portions of the Software.
|
9225
|
-
*
|
9226
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
9227
|
-
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
9228
|
-
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
9229
|
-
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
9230
|
-
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
9231
|
-
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
9232
|
-
* SOFTWARE.
|
9233
|
-
*
|
9234
|
-
*/
|
9235
|
-
|
9236
|
-
const ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
|
9237
|
-
class BufferSourceConverter {
|
9238
|
-
static isArrayBuffer(data) {
|
9239
|
-
return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
|
9240
|
-
}
|
9241
|
-
static toArrayBuffer(data) {
|
9242
|
-
if (this.isArrayBuffer(data)) {
|
9243
|
-
return data;
|
9244
|
-
}
|
9245
|
-
if (data.byteLength === data.buffer.byteLength) {
|
9246
|
-
return data.buffer;
|
9247
|
-
}
|
9248
|
-
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
|
9249
|
-
return data.buffer;
|
9250
|
-
}
|
9251
|
-
return this.toUint8Array(data.buffer)
|
9252
|
-
.slice(data.byteOffset, data.byteOffset + data.byteLength)
|
9253
|
-
.buffer;
|
9254
|
-
}
|
9255
|
-
static toUint8Array(data) {
|
9256
|
-
return this.toView(data, Uint8Array);
|
9257
|
-
}
|
9258
|
-
static toView(data, type) {
|
9259
|
-
if (data.constructor === type) {
|
9260
|
-
return data;
|
9261
|
-
}
|
9262
|
-
if (this.isArrayBuffer(data)) {
|
9263
|
-
return new type(data);
|
9264
|
-
}
|
9265
|
-
if (this.isArrayBufferView(data)) {
|
9266
|
-
return new type(data.buffer, data.byteOffset, data.byteLength);
|
9267
|
-
}
|
9268
|
-
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
|
9269
|
-
}
|
9270
|
-
static isBufferSource(data) {
|
9271
|
-
return this.isArrayBufferView(data)
|
9272
|
-
|| this.isArrayBuffer(data);
|
9273
|
-
}
|
9274
|
-
static isArrayBufferView(data) {
|
9275
|
-
return ArrayBuffer.isView(data)
|
9276
|
-
|| (data && this.isArrayBuffer(data.buffer));
|
9277
|
-
}
|
9278
|
-
static isEqual(a, b) {
|
9279
|
-
const aView = BufferSourceConverter.toUint8Array(a);
|
9280
|
-
const bView = BufferSourceConverter.toUint8Array(b);
|
9281
|
-
if (aView.length !== bView.byteLength) {
|
9282
|
-
return false;
|
9283
|
-
}
|
9284
|
-
for (let i = 0; i < aView.length; i++) {
|
9285
|
-
if (aView[i] !== bView[i]) {
|
9286
|
-
return false;
|
9287
|
-
}
|
9288
|
-
}
|
9289
|
-
return true;
|
9290
|
-
}
|
9291
|
-
static concat(...args) {
|
9292
|
-
let buffers;
|
9293
|
-
if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
|
9294
|
-
buffers = args[0];
|
9295
|
-
}
|
9296
|
-
else if (Array.isArray(args[0]) && args[1] instanceof Function) {
|
9297
|
-
buffers = args[0];
|
9298
|
-
}
|
9299
|
-
else {
|
9300
|
-
if (args[args.length - 1] instanceof Function) {
|
9301
|
-
buffers = args.slice(0, args.length - 1);
|
9302
|
-
}
|
9303
|
-
else {
|
9304
|
-
buffers = args;
|
9305
|
-
}
|
9306
|
-
}
|
9307
|
-
let size = 0;
|
9308
|
-
for (const buffer of buffers) {
|
9309
|
-
size += buffer.byteLength;
|
9310
|
-
}
|
9311
|
-
const res = new Uint8Array(size);
|
9312
|
-
let offset = 0;
|
9313
|
-
for (const buffer of buffers) {
|
9314
|
-
const view = this.toUint8Array(buffer);
|
9315
|
-
res.set(view, offset);
|
9316
|
-
offset += view.length;
|
9317
|
-
}
|
9318
|
-
if (args[args.length - 1] instanceof Function) {
|
9319
|
-
return this.toView(res, args[args.length - 1]);
|
9320
|
-
}
|
9321
|
-
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;
|
9322
8978
|
}
|
9323
8979
|
}
|
9324
8980
|
|
@@ -12459,272 +12115,44 @@ _a = TIME;
|
|
12459
12115
|
TIME.NAME = "TIME";
|
12460
12116
|
|
12461
12117
|
/**
|
12462
|
-
*
|
12118
|
+
* Signing a message failed
|
12463
12119
|
*/
|
12464
|
-
function pkcs1ToJwk(bytes) {
|
12465
|
-
const { result } = fromBER(bytes);
|
12466
|
-
// @ts-expect-error this looks fragile but DER is a canonical format so we are
|
12467
|
-
// safe to have deeply property chains like this
|
12468
|
-
const values = result.valueBlock.value;
|
12469
|
-
const key = {
|
12470
|
-
n: toString$1(bnToBuf(values[1].toBigInt()), 'base64url'),
|
12471
|
-
e: toString$1(bnToBuf(values[2].toBigInt()), 'base64url'),
|
12472
|
-
d: toString$1(bnToBuf(values[3].toBigInt()), 'base64url'),
|
12473
|
-
p: toString$1(bnToBuf(values[4].toBigInt()), 'base64url'),
|
12474
|
-
q: toString$1(bnToBuf(values[5].toBigInt()), 'base64url'),
|
12475
|
-
dp: toString$1(bnToBuf(values[6].toBigInt()), 'base64url'),
|
12476
|
-
dq: toString$1(bnToBuf(values[7].toBigInt()), 'base64url'),
|
12477
|
-
qi: toString$1(bnToBuf(values[8].toBigInt()), 'base64url'),
|
12478
|
-
kty: 'RSA',
|
12479
|
-
alg: 'RS256'
|
12480
|
-
};
|
12481
|
-
return key;
|
12482
|
-
}
|
12483
12120
|
/**
|
12484
|
-
*
|
12121
|
+
* Verifying a message signature failed
|
12485
12122
|
*/
|
12486
|
-
|
12487
|
-
|
12488
|
-
|
12123
|
+
class VerificationError extends Error {
|
12124
|
+
constructor(message = 'An error occurred while verifying a message') {
|
12125
|
+
super(message);
|
12126
|
+
this.name = 'VerificationError';
|
12489
12127
|
}
|
12490
|
-
const root = new Sequence({
|
12491
|
-
value: [
|
12492
|
-
new Integer({ value: 0 }),
|
12493
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
|
12494
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url'))),
|
12495
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.d, 'base64url'))),
|
12496
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.p, 'base64url'))),
|
12497
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.q, 'base64url'))),
|
12498
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.dp, 'base64url'))),
|
12499
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.dq, 'base64url'))),
|
12500
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.qi, 'base64url')))
|
12501
|
-
]
|
12502
|
-
});
|
12503
|
-
const der = root.toBER();
|
12504
|
-
return new Uint8Array(der, 0, der.byteLength);
|
12505
|
-
}
|
12506
|
-
/**
|
12507
|
-
* Convert a PKCIX in ASN1 DER format to a JWK key
|
12508
|
-
*/
|
12509
|
-
function pkixToJwk(bytes) {
|
12510
|
-
const { result } = fromBER(bytes);
|
12511
|
-
// @ts-expect-error this looks fragile but DER is a canonical format so we are
|
12512
|
-
// safe to have deeply property chains like this
|
12513
|
-
const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;
|
12514
|
-
return {
|
12515
|
-
kty: 'RSA',
|
12516
|
-
n: toString$1(bnToBuf(values[0].toBigInt()), 'base64url'),
|
12517
|
-
e: toString$1(bnToBuf(values[1].toBigInt()), 'base64url')
|
12518
|
-
};
|
12519
12128
|
}
|
12520
12129
|
/**
|
12521
|
-
*
|
12130
|
+
* WebCrypto was not available in the current context
|
12522
12131
|
*/
|
12523
|
-
|
12524
|
-
|
12525
|
-
|
12526
|
-
|
12527
|
-
const root = new Sequence({
|
12528
|
-
value: [
|
12529
|
-
new Sequence({
|
12530
|
-
value: [
|
12531
|
-
// rsaEncryption
|
12532
|
-
new ObjectIdentifier({
|
12533
|
-
value: '1.2.840.113549.1.1.1'
|
12534
|
-
}),
|
12535
|
-
new Null()
|
12536
|
-
]
|
12537
|
-
}),
|
12538
|
-
// this appears to be a bug in asn1js.js - this should really be a Sequence
|
12539
|
-
// and not a BitString but it generates the same bytes as node-forge so ๐คทโโ๏ธ
|
12540
|
-
new BitString({
|
12541
|
-
valueHex: new Sequence({
|
12542
|
-
value: [
|
12543
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.n, 'base64url'))),
|
12544
|
-
Integer.fromBigInt(bufToBn(fromString(jwk.e, 'base64url')))
|
12545
|
-
]
|
12546
|
-
}).toBER()
|
12547
|
-
})
|
12548
|
-
]
|
12549
|
-
});
|
12550
|
-
const der = root.toBER();
|
12551
|
-
return new Uint8Array(der, 0, der.byteLength);
|
12552
|
-
}
|
12553
|
-
function bnToBuf(bn) {
|
12554
|
-
let hex = bn.toString(16);
|
12555
|
-
if (hex.length % 2 > 0) {
|
12556
|
-
hex = `0${hex}`;
|
12557
|
-
}
|
12558
|
-
const len = hex.length / 2;
|
12559
|
-
const u8 = new Uint8Array(len);
|
12560
|
-
let i = 0;
|
12561
|
-
let j = 0;
|
12562
|
-
while (i < len) {
|
12563
|
-
u8[i] = parseInt(hex.slice(j, j + 2), 16);
|
12564
|
-
i += 1;
|
12565
|
-
j += 2;
|
12132
|
+
class WebCryptoMissingError extends Error {
|
12133
|
+
constructor(message = 'Missing Web Crypto API') {
|
12134
|
+
super(message);
|
12135
|
+
this.name = 'WebCryptoMissingError';
|
12566
12136
|
}
|
12567
|
-
return u8;
|
12568
12137
|
}
|
12569
|
-
|
12570
|
-
|
12571
|
-
|
12572
|
-
|
12573
|
-
|
12574
|
-
|
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');
|
12575
12151
|
}
|
12576
|
-
|
12577
|
-
}
|
12578
|
-
|
12579
|
-
}
|
12580
|
-
const SALT_LENGTH = 16;
|
12581
|
-
const KEY_SIZE = 32;
|
12582
|
-
const ITERATIONS = 10000;
|
12583
|
-
async function exportToPem(privateKey, password) {
|
12584
|
-
const crypto = webcrypto.get();
|
12585
|
-
// PrivateKeyInfo
|
12586
|
-
const keyWrapper = new Sequence({
|
12587
|
-
value: [
|
12588
|
-
// version (0)
|
12589
|
-
new Integer({ value: 0 }),
|
12590
|
-
// privateKeyAlgorithm
|
12591
|
-
new Sequence({
|
12592
|
-
value: [
|
12593
|
-
// rsaEncryption OID
|
12594
|
-
new ObjectIdentifier({
|
12595
|
-
value: '1.2.840.113549.1.1.1'
|
12596
|
-
}),
|
12597
|
-
new Null()
|
12598
|
-
]
|
12599
|
-
}),
|
12600
|
-
// PrivateKey
|
12601
|
-
new OctetString({
|
12602
|
-
valueHex: privateKey.marshal()
|
12603
|
-
})
|
12604
|
-
]
|
12605
|
-
});
|
12606
|
-
const keyBuf = keyWrapper.toBER();
|
12607
|
-
const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);
|
12608
|
-
const salt = randomBytes(SALT_LENGTH);
|
12609
|
-
const encryptionKey = await pbkdf2Async(sha512, password, salt, {
|
12610
|
-
c: ITERATIONS,
|
12611
|
-
dkLen: KEY_SIZE
|
12612
|
-
});
|
12613
|
-
const iv = randomBytes(16);
|
12614
|
-
const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);
|
12615
|
-
const encrypted = await crypto.subtle.encrypt({
|
12616
|
-
name: 'AES-CBC',
|
12617
|
-
iv
|
12618
|
-
}, cryptoKey, keyArr);
|
12619
|
-
const pbkdf2Params = new Sequence({
|
12620
|
-
value: [
|
12621
|
-
// salt
|
12622
|
-
new OctetString({ valueHex: salt }),
|
12623
|
-
// iteration count
|
12624
|
-
new Integer({ value: ITERATIONS }),
|
12625
|
-
// key length
|
12626
|
-
new Integer({ value: KEY_SIZE }),
|
12627
|
-
// AlgorithmIdentifier
|
12628
|
-
new Sequence({
|
12629
|
-
value: [
|
12630
|
-
// hmacWithSHA512
|
12631
|
-
new ObjectIdentifier({ value: '1.2.840.113549.2.11' }),
|
12632
|
-
new Null()
|
12633
|
-
]
|
12634
|
-
})
|
12635
|
-
]
|
12636
|
-
});
|
12637
|
-
const encryptionAlgorithm = new Sequence({
|
12638
|
-
value: [
|
12639
|
-
// pkcs5PBES2
|
12640
|
-
new ObjectIdentifier({
|
12641
|
-
value: '1.2.840.113549.1.5.13'
|
12642
|
-
}),
|
12643
|
-
new Sequence({
|
12644
|
-
value: [
|
12645
|
-
// keyDerivationFunc
|
12646
|
-
new Sequence({
|
12647
|
-
value: [
|
12648
|
-
// pkcs5PBKDF2
|
12649
|
-
new ObjectIdentifier({
|
12650
|
-
value: '1.2.840.113549.1.5.12'
|
12651
|
-
}),
|
12652
|
-
// PBKDF2-params
|
12653
|
-
pbkdf2Params
|
12654
|
-
]
|
12655
|
-
}),
|
12656
|
-
// encryptionScheme
|
12657
|
-
new Sequence({
|
12658
|
-
value: [
|
12659
|
-
// aes256-CBC
|
12660
|
-
new ObjectIdentifier({
|
12661
|
-
value: '2.16.840.1.101.3.4.1.42'
|
12662
|
-
}),
|
12663
|
-
// iv
|
12664
|
-
new OctetString({
|
12665
|
-
valueHex: iv
|
12666
|
-
})
|
12667
|
-
]
|
12668
|
-
})
|
12669
|
-
]
|
12670
|
-
})
|
12671
|
-
]
|
12672
|
-
});
|
12673
|
-
const finalWrapper = new Sequence({
|
12674
|
-
value: [
|
12675
|
-
encryptionAlgorithm,
|
12676
|
-
new OctetString({ valueHex: encrypted })
|
12677
|
-
]
|
12678
|
-
});
|
12679
|
-
const finalWrapperBuf = finalWrapper.toBER();
|
12680
|
-
const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);
|
12681
|
-
return [
|
12682
|
-
'-----BEGIN ENCRYPTED PRIVATE KEY-----',
|
12683
|
-
...toString$1(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),
|
12684
|
-
'-----END ENCRYPTED PRIVATE KEY-----'
|
12685
|
-
].join('\n');
|
12686
|
-
}
|
12152
|
+
return nativeCrypto;
|
12153
|
+
}
|
12154
|
+
};
|
12687
12155
|
|
12688
|
-
async function generateKey$1(bits) {
|
12689
|
-
const pair = await webcrypto.get().subtle.generateKey({
|
12690
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12691
|
-
modulusLength: bits,
|
12692
|
-
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
12693
|
-
hash: { name: 'SHA-256' }
|
12694
|
-
}, true, ['sign', 'verify']);
|
12695
|
-
const keys = await exportKey(pair);
|
12696
|
-
return {
|
12697
|
-
privateKey: keys[0],
|
12698
|
-
publicKey: keys[1]
|
12699
|
-
};
|
12700
|
-
}
|
12701
|
-
// Takes a jwk key
|
12702
|
-
async function unmarshalPrivateKey$1(key) {
|
12703
|
-
const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12704
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12705
|
-
hash: { name: 'SHA-256' }
|
12706
|
-
}, true, ['sign']);
|
12707
|
-
const pair = [
|
12708
|
-
privateKey,
|
12709
|
-
await derivePublicFromPrivate(key)
|
12710
|
-
];
|
12711
|
-
const keys = await exportKey({
|
12712
|
-
privateKey: pair[0],
|
12713
|
-
publicKey: pair[1]
|
12714
|
-
});
|
12715
|
-
return {
|
12716
|
-
privateKey: keys[0],
|
12717
|
-
publicKey: keys[1]
|
12718
|
-
};
|
12719
|
-
}
|
12720
|
-
async function hashAndSign$1(key, msg) {
|
12721
|
-
const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12722
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12723
|
-
hash: { name: 'SHA-256' }
|
12724
|
-
}, false, ['sign']);
|
12725
|
-
const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());
|
12726
|
-
return new Uint8Array(sig, 0, sig.byteLength);
|
12727
|
-
}
|
12728
12156
|
async function hashAndVerify$1(key, sig, msg) {
|
12729
12157
|
const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {
|
12730
12158
|
name: 'RSASSA-PKCS1-v1_5',
|
@@ -12732,173 +12160,214 @@ async function hashAndVerify$1(key, sig, msg) {
|
|
12732
12160
|
}, false, ['verify']);
|
12733
12161
|
return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());
|
12734
12162
|
}
|
12735
|
-
|
12736
|
-
if (pair.privateKey == null || pair.publicKey == null) {
|
12737
|
-
throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');
|
12738
|
-
}
|
12739
|
-
return Promise.all([
|
12740
|
-
webcrypto.get().subtle.exportKey('jwk', pair.privateKey),
|
12741
|
-
webcrypto.get().subtle.exportKey('jwk', pair.publicKey)
|
12742
|
-
]);
|
12743
|
-
}
|
12744
|
-
async function derivePublicFromPrivate(jwKey) {
|
12745
|
-
return webcrypto.get().subtle.importKey('jwk', {
|
12746
|
-
kty: jwKey.kty,
|
12747
|
-
n: jwKey.n,
|
12748
|
-
e: jwKey.e
|
12749
|
-
}, {
|
12750
|
-
name: 'RSASSA-PKCS1-v1_5',
|
12751
|
-
hash: { name: 'SHA-256' }
|
12752
|
-
}, true, ['verify']);
|
12753
|
-
}
|
12754
|
-
function keySize(jwk) {
|
12163
|
+
function rsaKeySize(jwk) {
|
12755
12164
|
if (jwk.kty !== 'RSA') {
|
12756
|
-
throw new
|
12165
|
+
throw new InvalidParametersError('invalid key type');
|
12757
12166
|
}
|
12758
12167
|
else if (jwk.n == null) {
|
12759
|
-
throw new
|
12168
|
+
throw new InvalidParametersError('invalid key modulus');
|
12760
12169
|
}
|
12761
12170
|
const bytes = fromString(jwk.n, 'base64url');
|
12762
12171
|
return bytes.length * 8;
|
12763
12172
|
}
|
12764
12173
|
|
12765
|
-
|
12766
|
-
|
12174
|
+
class RSAPublicKey {
|
12175
|
+
type = 'RSA';
|
12767
12176
|
_key;
|
12768
|
-
|
12177
|
+
_raw;
|
12178
|
+
_multihash;
|
12179
|
+
constructor(key, digest) {
|
12769
12180
|
this._key = key;
|
12181
|
+
this._multihash = digest;
|
12770
12182
|
}
|
12771
|
-
|
12772
|
-
|
12773
|
-
|
12774
|
-
marshal() {
|
12775
|
-
return jwkToPkix(this._key);
|
12776
|
-
}
|
12777
|
-
get bytes() {
|
12778
|
-
return PublicKey.encode({
|
12779
|
-
Type: KeyType.RSA,
|
12780
|
-
Data: this.marshal()
|
12781
|
-
}).subarray();
|
12782
|
-
}
|
12783
|
-
equals(key) {
|
12784
|
-
return equals(this.bytes, key.bytes);
|
12785
|
-
}
|
12786
|
-
hash() {
|
12787
|
-
const p = sha256$1.digest(this.bytes);
|
12788
|
-
if (isPromise(p)) {
|
12789
|
-
return p.then(({ bytes }) => bytes);
|
12183
|
+
get raw() {
|
12184
|
+
if (this._raw == null) {
|
12185
|
+
this._raw = jwkToPkix(this._key);
|
12790
12186
|
}
|
12791
|
-
return
|
12792
|
-
}
|
12793
|
-
}
|
12794
|
-
class RsaPrivateKey {
|
12795
|
-
_key;
|
12796
|
-
_publicKey;
|
12797
|
-
constructor(key, publicKey) {
|
12798
|
-
this._key = key;
|
12799
|
-
this._publicKey = publicKey;
|
12187
|
+
return this._raw;
|
12800
12188
|
}
|
12801
|
-
|
12802
|
-
return
|
12189
|
+
toMultihash() {
|
12190
|
+
return this._multihash;
|
12803
12191
|
}
|
12804
|
-
|
12805
|
-
return
|
12806
|
-
}
|
12807
|
-
get public() {
|
12808
|
-
if (this._publicKey == null) {
|
12809
|
-
throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');
|
12810
|
-
}
|
12811
|
-
return new RsaPublicKey(this._publicKey);
|
12812
|
-
}
|
12813
|
-
marshal() {
|
12814
|
-
return jwkToPkcs1(this._key);
|
12192
|
+
toCID() {
|
12193
|
+
return CID.createV1(114, this._multihash);
|
12815
12194
|
}
|
12816
|
-
|
12817
|
-
return
|
12818
|
-
Type: KeyType.RSA,
|
12819
|
-
Data: this.marshal()
|
12820
|
-
}).subarray();
|
12195
|
+
toString() {
|
12196
|
+
return base58btc.encode(this.toMultihash().bytes).substring(1);
|
12821
12197
|
}
|
12822
12198
|
equals(key) {
|
12823
|
-
|
12824
|
-
|
12825
|
-
hash() {
|
12826
|
-
const p = sha256$1.digest(this.bytes);
|
12827
|
-
if (isPromise(p)) {
|
12828
|
-
return p.then(({ bytes }) => bytes);
|
12199
|
+
if (key == null || !(key.raw instanceof Uint8Array)) {
|
12200
|
+
return false;
|
12829
12201
|
}
|
12830
|
-
return
|
12202
|
+
return equals(this.raw, key.raw);
|
12831
12203
|
}
|
12832
|
-
|
12833
|
-
|
12834
|
-
*
|
12835
|
-
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
12836
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
12837
|
-
* of the PKCS SubjectPublicKeyInfo.
|
12838
|
-
*/
|
12839
|
-
async id() {
|
12840
|
-
const hash = await this.public.hash();
|
12841
|
-
return toString$1(hash, 'base58btc');
|
12204
|
+
verify(data, sig) {
|
12205
|
+
return hashAndVerify$1(this._key, sig, data);
|
12842
12206
|
}
|
12843
|
-
|
12844
|
-
|
12845
|
-
|
12846
|
-
|
12847
|
-
|
12848
|
-
|
12849
|
-
|
12850
|
-
|
12851
|
-
|
12852
|
-
|
12853
|
-
|
12854
|
-
|
12855
|
-
|
12856
|
-
|
12857
|
-
|
12858
|
-
|
12859
|
-
|
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: asn1jsIntegerToBase64(values[0]),
|
12222
|
+
e: asn1jsIntegerToBase64(values[1])
|
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');
|
12860
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);
|
12861
12257
|
}
|
12862
|
-
|
12863
|
-
|
12864
|
-
|
12865
|
-
|
12258
|
+
function asn1jsIntegerToBase64(int) {
|
12259
|
+
let buf = int.valueBlock.valueHexView;
|
12260
|
+
// chrome rejects values with leading 0s
|
12261
|
+
while (buf[0] === 0) {
|
12262
|
+
buf = buf.subarray(1);
|
12866
12263
|
}
|
12867
|
-
|
12868
|
-
|
12264
|
+
return toString$1(buf, 'base64url');
|
12265
|
+
}
|
12266
|
+
function bufToBn(u8) {
|
12267
|
+
const hex = [];
|
12268
|
+
u8.forEach(function (i) {
|
12269
|
+
let h = i.toString(16);
|
12270
|
+
if (h.length % 2 > 0) {
|
12271
|
+
h = `0${h}`;
|
12272
|
+
}
|
12273
|
+
hex.push(h);
|
12274
|
+
});
|
12275
|
+
return BigInt('0x' + hex.join(''));
|
12869
12276
|
}
|
12870
|
-
|
12277
|
+
/**
|
12278
|
+
* Turn PKIX bytes to a PublicKey
|
12279
|
+
*/
|
12280
|
+
function pkixToRSAPublicKey(bytes) {
|
12871
12281
|
const jwk = pkixToJwk(bytes);
|
12872
|
-
if (
|
12873
|
-
throw new
|
12282
|
+
if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {
|
12283
|
+
throw new InvalidPublicKeyError('Key size is too large');
|
12874
12284
|
}
|
12875
|
-
|
12285
|
+
const hash = sha256(PublicKey.encode({
|
12286
|
+
Type: KeyType.RSA,
|
12287
|
+
Data: bytes
|
12288
|
+
}));
|
12289
|
+
const digest = create(SHA2_256_CODE, hash);
|
12290
|
+
return new RSAPublicKey(jwk, digest);
|
12876
12291
|
}
|
12877
|
-
|
12878
|
-
|
12879
|
-
|
12292
|
+
|
12293
|
+
// HMAC (RFC 2104)
|
12294
|
+
class HMAC extends Hash {
|
12295
|
+
constructor(hash$1, _key) {
|
12296
|
+
super();
|
12297
|
+
this.finished = false;
|
12298
|
+
this.destroyed = false;
|
12299
|
+
hash(hash$1);
|
12300
|
+
const key = toBytes$1(_key);
|
12301
|
+
this.iHash = hash$1.create();
|
12302
|
+
if (typeof this.iHash.update !== 'function')
|
12303
|
+
throw new Error('Expected instance of class which extends utils.Hash');
|
12304
|
+
this.blockLen = this.iHash.blockLen;
|
12305
|
+
this.outputLen = this.iHash.outputLen;
|
12306
|
+
const blockLen = this.blockLen;
|
12307
|
+
const pad = new Uint8Array(blockLen);
|
12308
|
+
// blockLen can be bigger than outputLen
|
12309
|
+
pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
|
12310
|
+
for (let i = 0; i < pad.length; i++)
|
12311
|
+
pad[i] ^= 0x36;
|
12312
|
+
this.iHash.update(pad);
|
12313
|
+
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
|
12314
|
+
this.oHash = hash$1.create();
|
12315
|
+
// Undo internal XOR && apply outer XOR
|
12316
|
+
for (let i = 0; i < pad.length; i++)
|
12317
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
12318
|
+
this.oHash.update(pad);
|
12319
|
+
pad.fill(0);
|
12880
12320
|
}
|
12881
|
-
|
12882
|
-
|
12883
|
-
|
12884
|
-
|
12885
|
-
|
12886
|
-
|
12321
|
+
update(buf) {
|
12322
|
+
exists(this);
|
12323
|
+
this.iHash.update(buf);
|
12324
|
+
return this;
|
12325
|
+
}
|
12326
|
+
digestInto(out) {
|
12327
|
+
exists(this);
|
12328
|
+
bytes(out, this.outputLen);
|
12329
|
+
this.finished = true;
|
12330
|
+
this.iHash.digestInto(out);
|
12331
|
+
this.oHash.update(out);
|
12332
|
+
this.oHash.digestInto(out);
|
12333
|
+
this.destroy();
|
12334
|
+
}
|
12335
|
+
digest() {
|
12336
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
12337
|
+
this.digestInto(out);
|
12338
|
+
return out;
|
12339
|
+
}
|
12340
|
+
_cloneInto(to) {
|
12341
|
+
// Create new instance without calling constructor since key already in state and we don't know it.
|
12342
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
12343
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
12344
|
+
to = to;
|
12345
|
+
to.finished = finished;
|
12346
|
+
to.destroyed = destroyed;
|
12347
|
+
to.blockLen = blockLen;
|
12348
|
+
to.outputLen = outputLen;
|
12349
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
12350
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
12351
|
+
return to;
|
12352
|
+
}
|
12353
|
+
destroy() {
|
12354
|
+
this.destroyed = true;
|
12355
|
+
this.oHash.destroy();
|
12356
|
+
this.iHash.destroy();
|
12887
12357
|
}
|
12888
|
-
const keys = await generateKey$1(bits);
|
12889
|
-
return new RsaPrivateKey(keys.privateKey, keys.publicKey);
|
12890
12358
|
}
|
12891
|
-
|
12892
|
-
|
12893
|
-
|
12894
|
-
|
12895
|
-
|
12896
|
-
|
12897
|
-
|
12898
|
-
|
12899
|
-
|
12900
|
-
|
12901
|
-
|
12359
|
+
/**
|
12360
|
+
* HMAC: RFC2104 message authentication code.
|
12361
|
+
* @param hash - function that would be used e.g. sha256
|
12362
|
+
* @param key - message key
|
12363
|
+
* @param message - message data
|
12364
|
+
* @example
|
12365
|
+
* import { hmac } from '@noble/hashes/hmac';
|
12366
|
+
* import { sha256 } from '@noble/hashes/sha2';
|
12367
|
+
* const mac1 = hmac(sha256, 'key', 'message');
|
12368
|
+
*/
|
12369
|
+
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
12370
|
+
hmac.create = (hash, key) => new HMAC(hash, key);
|
12902
12371
|
|
12903
12372
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
12904
12373
|
// Short Weierstrass curve. The formula is: yยฒ = xยณ + ax + b
|
@@ -12935,8 +12404,14 @@ function validatePointOpts(curve) {
|
|
12935
12404
|
}
|
12936
12405
|
return Object.freeze({ ...opts });
|
12937
12406
|
}
|
12938
|
-
// ASN.1 DER encoding utilities
|
12939
12407
|
const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
|
12408
|
+
/**
|
12409
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
12410
|
+
*
|
12411
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
12412
|
+
*
|
12413
|
+
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
|
12414
|
+
*/
|
12940
12415
|
const DER = {
|
12941
12416
|
// asn.1 DER encoding utils
|
12942
12417
|
Err: class DERErr extends Error {
|
@@ -12944,54 +12419,103 @@ const DER = {
|
|
12944
12419
|
super(m);
|
12945
12420
|
}
|
12946
12421
|
},
|
12947
|
-
|
12948
|
-
|
12949
|
-
|
12950
|
-
|
12951
|
-
|
12952
|
-
|
12953
|
-
|
12954
|
-
|
12955
|
-
|
12956
|
-
|
12957
|
-
|
12958
|
-
|
12959
|
-
|
12960
|
-
|
12961
|
-
|
12962
|
-
|
12963
|
-
|
12422
|
+
// Basic building block is TLV (Tag-Length-Value)
|
12423
|
+
_tlv: {
|
12424
|
+
encode: (tag, data) => {
|
12425
|
+
const { Err: E } = DER;
|
12426
|
+
if (tag < 0 || tag > 256)
|
12427
|
+
throw new E('tlv.encode: wrong tag');
|
12428
|
+
if (data.length & 1)
|
12429
|
+
throw new E('tlv.encode: unpadded data');
|
12430
|
+
const dataLen = data.length / 2;
|
12431
|
+
const len = numberToHexUnpadded(dataLen);
|
12432
|
+
if ((len.length / 2) & 128)
|
12433
|
+
throw new E('tlv.encode: long form length too big');
|
12434
|
+
// length of length with long form flag
|
12435
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
|
12436
|
+
return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
|
12437
|
+
},
|
12438
|
+
// v - value, l - left bytes (unparsed)
|
12439
|
+
decode(tag, data) {
|
12440
|
+
const { Err: E } = DER;
|
12441
|
+
let pos = 0;
|
12442
|
+
if (tag < 0 || tag > 256)
|
12443
|
+
throw new E('tlv.encode: wrong tag');
|
12444
|
+
if (data.length < 2 || data[pos++] !== tag)
|
12445
|
+
throw new E('tlv.decode: wrong tlv');
|
12446
|
+
const first = data[pos++];
|
12447
|
+
const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
|
12448
|
+
let length = 0;
|
12449
|
+
if (!isLong)
|
12450
|
+
length = first;
|
12451
|
+
else {
|
12452
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
12453
|
+
const lenLen = first & 127;
|
12454
|
+
if (!lenLen)
|
12455
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
12456
|
+
if (lenLen > 4)
|
12457
|
+
throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
|
12458
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
12459
|
+
if (lengthBytes.length !== lenLen)
|
12460
|
+
throw new E('tlv.decode: length bytes not complete');
|
12461
|
+
if (lengthBytes[0] === 0)
|
12462
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
12463
|
+
for (const b of lengthBytes)
|
12464
|
+
length = (length << 8) | b;
|
12465
|
+
pos += lenLen;
|
12466
|
+
if (length < 128)
|
12467
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
12468
|
+
}
|
12469
|
+
const v = data.subarray(pos, pos + length);
|
12470
|
+
if (v.length !== length)
|
12471
|
+
throw new E('tlv.decode: wrong value length');
|
12472
|
+
return { v, l: data.subarray(pos + length) };
|
12473
|
+
},
|
12474
|
+
},
|
12475
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
12476
|
+
// since we always use positive integers here. It must always be empty:
|
12477
|
+
// - add zero byte if exists
|
12478
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
12479
|
+
_int: {
|
12480
|
+
encode(num) {
|
12481
|
+
const { Err: E } = DER;
|
12482
|
+
if (num < _0n)
|
12483
|
+
throw new E('integer: negative integers are not allowed');
|
12484
|
+
let hex = numberToHexUnpadded(num);
|
12485
|
+
// Pad with zero byte if negative flag is present
|
12486
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
12487
|
+
hex = '00' + hex;
|
12488
|
+
if (hex.length & 1)
|
12489
|
+
throw new E('unexpected assertion');
|
12490
|
+
return hex;
|
12491
|
+
},
|
12492
|
+
decode(data) {
|
12493
|
+
const { Err: E } = DER;
|
12494
|
+
if (data[0] & 128)
|
12495
|
+
throw new E('Invalid signature integer: negative');
|
12496
|
+
if (data[0] === 0x00 && !(data[1] & 128))
|
12497
|
+
throw new E('Invalid signature integer: unnecessary leading zero');
|
12498
|
+
return b2n(data);
|
12499
|
+
},
|
12964
12500
|
},
|
12965
12501
|
toSig(hex) {
|
12966
12502
|
// parse DER signature
|
12967
|
-
const { Err: E } = DER;
|
12503
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
12968
12504
|
const data = typeof hex === 'string' ? h2b(hex) : hex;
|
12969
12505
|
abytes(data);
|
12970
|
-
|
12971
|
-
if (
|
12972
|
-
throw new E('Invalid signature tag');
|
12973
|
-
if (data[1] !== l - 2)
|
12974
|
-
throw new E('Invalid signature: incorrect length');
|
12975
|
-
const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
|
12976
|
-
const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
|
12977
|
-
if (rBytesLeft.length)
|
12506
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
12507
|
+
if (seqLeftBytes.length)
|
12978
12508
|
throw new E('Invalid signature: left bytes after parsing');
|
12979
|
-
|
12509
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
12510
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
12511
|
+
if (sLeftBytes.length)
|
12512
|
+
throw new E('Invalid signature: left bytes after parsing');
|
12513
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
12980
12514
|
},
|
12981
12515
|
hexFromSig(sig) {
|
12982
|
-
|
12983
|
-
const
|
12984
|
-
|
12985
|
-
const hex = num.toString(16);
|
12986
|
-
return hex.length & 1 ? `0${hex}` : hex;
|
12987
|
-
};
|
12988
|
-
const s = slice(h(sig.s));
|
12989
|
-
const r = slice(h(sig.r));
|
12990
|
-
const shl = s.length / 2;
|
12991
|
-
const rhl = r.length / 2;
|
12992
|
-
const sl = h(shl);
|
12993
|
-
const rl = h(rhl);
|
12994
|
-
return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
|
12516
|
+
const { _tlv: tlv, _int: int } = DER;
|
12517
|
+
const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;
|
12518
|
+
return tlv.encode(0x30, seq);
|
12995
12519
|
},
|
12996
12520
|
};
|
12997
12521
|
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
@@ -13000,6 +12524,7 @@ const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigI
|
|
13000
12524
|
function weierstrassPoints(opts) {
|
13001
12525
|
const CURVE = validatePointOpts(opts);
|
13002
12526
|
const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
|
12527
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
13003
12528
|
const toBytes = CURVE.toBytes ||
|
13004
12529
|
((_c, point, _isCompressed) => {
|
13005
12530
|
const a = point.toAffine();
|
@@ -13173,6 +12698,10 @@ function weierstrassPoints(opts) {
|
|
13173
12698
|
static fromPrivateKey(privateKey) {
|
13174
12699
|
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
|
13175
12700
|
}
|
12701
|
+
// Multiscalar Multiplication
|
12702
|
+
static msm(points, scalars) {
|
12703
|
+
return pippenger(Point, Fn, points, scalars);
|
12704
|
+
}
|
13176
12705
|
// "Private method", don't use it directly
|
13177
12706
|
_setWindowSize(windowSize) {
|
13178
12707
|
wnaf.setWindowSize(this, windowSize);
|
@@ -13858,7 +13387,7 @@ function getHash(hash) {
|
|
13858
13387
|
return {
|
13859
13388
|
hash,
|
13860
13389
|
hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
|
13861
|
-
randomBytes
|
13390
|
+
randomBytes,
|
13862
13391
|
};
|
13863
13392
|
}
|
13864
13393
|
function createCurve(curveDef, defHash) {
|
@@ -13951,27 +13480,15 @@ const secp256k1 = createCurve({
|
|
13951
13480
|
BigInt(0);
|
13952
13481
|
secp256k1.ProjectivePoint;
|
13953
13482
|
|
13954
|
-
function
|
13955
|
-
|
13956
|
-
|
13957
|
-
/**
|
13958
|
-
* Hash and sign message with private key
|
13959
|
-
*/
|
13960
|
-
function hashAndSign(key, msg) {
|
13961
|
-
const p = sha256$1.digest(msg instanceof Uint8Array ? msg : msg.subarray());
|
13962
|
-
if (isPromise(p)) {
|
13963
|
-
return p.then(({ digest }) => secp256k1.sign(digest, key).toDERRawBytes())
|
13964
|
-
.catch(err => {
|
13965
|
-
throw new CodeError(String(err), 'ERR_INVALID_INPUT');
|
13966
|
-
});
|
13967
|
-
}
|
13968
|
-
try {
|
13969
|
-
return secp256k1.sign(p.digest, key).toDERRawBytes();
|
13970
|
-
}
|
13971
|
-
catch (err) {
|
13972
|
-
throw new CodeError(String(err), 'ERR_INVALID_INPUT');
|
13483
|
+
function isPromise(thing) {
|
13484
|
+
if (thing == null) {
|
13485
|
+
return false;
|
13973
13486
|
}
|
13487
|
+
return typeof thing.then === 'function' &&
|
13488
|
+
typeof thing.catch === 'function' &&
|
13489
|
+
typeof thing.finally === 'function';
|
13974
13490
|
}
|
13491
|
+
|
13975
13492
|
/**
|
13976
13493
|
* Hash message and verify signature with public key
|
13977
13494
|
*/
|
@@ -13980,207 +13497,114 @@ function hashAndVerify(key, sig, msg) {
|
|
13980
13497
|
if (isPromise(p)) {
|
13981
13498
|
return p.then(({ digest }) => secp256k1.verify(sig, digest, key))
|
13982
13499
|
.catch(err => {
|
13983
|
-
throw new
|
13500
|
+
throw new VerificationError(String(err));
|
13984
13501
|
});
|
13985
13502
|
}
|
13986
13503
|
try {
|
13987
13504
|
return secp256k1.verify(sig, p.digest, key);
|
13988
13505
|
}
|
13989
13506
|
catch (err) {
|
13990
|
-
throw new
|
13991
|
-
}
|
13992
|
-
}
|
13993
|
-
function compressPublicKey(key) {
|
13994
|
-
const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
|
13995
|
-
return point;
|
13996
|
-
}
|
13997
|
-
function validatePrivateKey(key) {
|
13998
|
-
try {
|
13999
|
-
secp256k1.getPublicKey(key, true);
|
14000
|
-
}
|
14001
|
-
catch (err) {
|
14002
|
-
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
|
14003
|
-
}
|
14004
|
-
}
|
14005
|
-
function validatePublicKey(key) {
|
14006
|
-
try {
|
14007
|
-
secp256k1.ProjectivePoint.fromHex(key);
|
14008
|
-
}
|
14009
|
-
catch (err) {
|
14010
|
-
throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');
|
14011
|
-
}
|
14012
|
-
}
|
14013
|
-
function computePublicKey(privateKey) {
|
14014
|
-
try {
|
14015
|
-
return secp256k1.getPublicKey(privateKey, true);
|
14016
|
-
}
|
14017
|
-
catch (err) {
|
14018
|
-
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');
|
13507
|
+
throw new VerificationError(String(err));
|
14019
13508
|
}
|
14020
13509
|
}
|
14021
13510
|
|
14022
13511
|
class Secp256k1PublicKey {
|
13512
|
+
type = 'secp256k1';
|
13513
|
+
raw;
|
14023
13514
|
_key;
|
14024
13515
|
constructor(key) {
|
14025
|
-
|
14026
|
-
this.
|
14027
|
-
}
|
14028
|
-
verify(data, sig) {
|
14029
|
-
return hashAndVerify(this._key, sig, data);
|
14030
|
-
}
|
14031
|
-
marshal() {
|
14032
|
-
return compressPublicKey(this._key);
|
14033
|
-
}
|
14034
|
-
get bytes() {
|
14035
|
-
return PublicKey.encode({
|
14036
|
-
Type: KeyType.Secp256k1,
|
14037
|
-
Data: this.marshal()
|
14038
|
-
}).subarray();
|
14039
|
-
}
|
14040
|
-
equals(key) {
|
14041
|
-
return equals(this.bytes, key.bytes);
|
14042
|
-
}
|
14043
|
-
async hash() {
|
14044
|
-
const p = sha256$1.digest(this.bytes);
|
14045
|
-
let bytes;
|
14046
|
-
if (isPromise(p)) {
|
14047
|
-
({ bytes } = await p);
|
14048
|
-
}
|
14049
|
-
else {
|
14050
|
-
bytes = p.bytes;
|
14051
|
-
}
|
14052
|
-
return bytes;
|
13516
|
+
this._key = validateSecp256k1PublicKey(key);
|
13517
|
+
this.raw = compressSecp256k1PublicKey(this._key);
|
14053
13518
|
}
|
14054
|
-
|
14055
|
-
|
14056
|
-
_key;
|
14057
|
-
_publicKey;
|
14058
|
-
constructor(key, publicKey) {
|
14059
|
-
this._key = key;
|
14060
|
-
this._publicKey = publicKey ?? computePublicKey(key);
|
14061
|
-
validatePrivateKey(this._key);
|
14062
|
-
validatePublicKey(this._publicKey);
|
13519
|
+
toMultihash() {
|
13520
|
+
return identity.digest(publicKeyToProtobuf(this));
|
14063
13521
|
}
|
14064
|
-
|
14065
|
-
return
|
14066
|
-
}
|
14067
|
-
get public() {
|
14068
|
-
return new Secp256k1PublicKey(this._publicKey);
|
14069
|
-
}
|
14070
|
-
marshal() {
|
14071
|
-
return this._key;
|
13522
|
+
toCID() {
|
13523
|
+
return CID.createV1(114, this.toMultihash());
|
14072
13524
|
}
|
14073
|
-
|
14074
|
-
return
|
14075
|
-
Type: KeyType.Secp256k1,
|
14076
|
-
Data: this.marshal()
|
14077
|
-
}).subarray();
|
13525
|
+
toString() {
|
13526
|
+
return base58btc.encode(this.toMultihash().bytes).substring(1);
|
14078
13527
|
}
|
14079
13528
|
equals(key) {
|
14080
|
-
|
14081
|
-
|
14082
|
-
hash() {
|
14083
|
-
const p = sha256$1.digest(this.bytes);
|
14084
|
-
if (isPromise(p)) {
|
14085
|
-
return p.then(({ bytes }) => bytes);
|
13529
|
+
if (key == null || !(key.raw instanceof Uint8Array)) {
|
13530
|
+
return false;
|
14086
13531
|
}
|
14087
|
-
return
|
13532
|
+
return equals(this.raw, key.raw);
|
14088
13533
|
}
|
14089
|
-
|
14090
|
-
|
14091
|
-
*
|
14092
|
-
* The key id is the base58 encoding of the SHA-256 multihash of its public key.
|
14093
|
-
* The public key is a protobuf encoding containing a type and the DER encoding
|
14094
|
-
* of the PKCS SubjectPublicKeyInfo.
|
14095
|
-
*/
|
14096
|
-
async id() {
|
14097
|
-
const hash = await this.public.hash();
|
14098
|
-
return toString$1(hash, 'base58btc');
|
14099
|
-
}
|
14100
|
-
/**
|
14101
|
-
* Exports the key into a password protected `format`
|
14102
|
-
*/
|
14103
|
-
async export(password, format = 'libp2p-key') {
|
14104
|
-
if (format === 'libp2p-key') {
|
14105
|
-
return exporter(this.bytes, password);
|
14106
|
-
}
|
14107
|
-
else {
|
14108
|
-
throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');
|
14109
|
-
}
|
13534
|
+
verify(data, sig) {
|
13535
|
+
return hashAndVerify(this._key, sig, data);
|
14110
13536
|
}
|
14111
13537
|
}
|
14112
|
-
|
14113
|
-
return new Secp256k1PrivateKey(bytes);
|
14114
|
-
}
|
13538
|
+
|
14115
13539
|
function unmarshalSecp256k1PublicKey(bytes) {
|
14116
13540
|
return new Secp256k1PublicKey(bytes);
|
14117
13541
|
}
|
14118
|
-
|
14119
|
-
const
|
14120
|
-
return
|
13542
|
+
function compressSecp256k1PublicKey(key) {
|
13543
|
+
const point = secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);
|
13544
|
+
return point;
|
13545
|
+
}
|
13546
|
+
function validateSecp256k1PublicKey(key) {
|
13547
|
+
try {
|
13548
|
+
secp256k1.ProjectivePoint.fromHex(key);
|
13549
|
+
return key;
|
13550
|
+
}
|
13551
|
+
catch (err) {
|
13552
|
+
throw new InvalidPublicKeyError(String(err));
|
13553
|
+
}
|
14121
13554
|
}
|
14122
|
-
|
14123
|
-
var Secp256k1 = /*#__PURE__*/Object.freeze({
|
14124
|
-
__proto__: null,
|
14125
|
-
Secp256k1PrivateKey: Secp256k1PrivateKey,
|
14126
|
-
Secp256k1PublicKey: Secp256k1PublicKey,
|
14127
|
-
generateKeyPair: generateKeyPair,
|
14128
|
-
unmarshalSecp256k1PrivateKey: unmarshalSecp256k1PrivateKey,
|
14129
|
-
unmarshalSecp256k1PublicKey: unmarshalSecp256k1PublicKey
|
14130
|
-
});
|
14131
13555
|
|
14132
13556
|
/**
|
14133
13557
|
* @packageDocumentation
|
14134
13558
|
*
|
14135
|
-
*
|
14136
|
-
*
|
14137
|
-
* The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.
|
13559
|
+
* ## Supported Key Types
|
14138
13560
|
*
|
14139
13561
|
* Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.
|
14140
13562
|
*
|
14141
13563
|
* For encryption / decryption support, RSA keys should be used.
|
14142
13564
|
*/
|
14143
|
-
const supportedKeys = {
|
14144
|
-
rsa: RSA,
|
14145
|
-
ed25519: Ed25519,
|
14146
|
-
secp256k1: Secp256k1
|
14147
|
-
};
|
14148
|
-
function unsupportedKey(type) {
|
14149
|
-
const supported = Object.keys(supportedKeys).join(' / ');
|
14150
|
-
return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');
|
14151
|
-
}
|
14152
13565
|
/**
|
14153
|
-
*
|
13566
|
+
* Creates a public key from the raw key bytes
|
14154
13567
|
*/
|
14155
|
-
function
|
14156
|
-
|
14157
|
-
|
14158
|
-
|
14159
|
-
|
14160
|
-
|
14161
|
-
|
14162
|
-
|
14163
|
-
|
14164
|
-
return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);
|
14165
|
-
default:
|
14166
|
-
throw unsupportedKey(decoded.Type ?? 'unknown');
|
13568
|
+
function publicKeyFromRaw(buf) {
|
13569
|
+
if (buf.byteLength === 32) {
|
13570
|
+
return unmarshalEd25519PublicKey(buf);
|
13571
|
+
}
|
13572
|
+
else if (buf.byteLength === 33) {
|
13573
|
+
return unmarshalSecp256k1PublicKey(buf);
|
13574
|
+
}
|
13575
|
+
else {
|
13576
|
+
return pkixToRSAPublicKey(buf);
|
14167
13577
|
}
|
14168
13578
|
}
|
14169
13579
|
/**
|
14170
|
-
* Converts a
|
13580
|
+
* Converts a public key object into a protobuf serialized public key
|
14171
13581
|
*/
|
14172
|
-
|
14173
|
-
|
14174
|
-
|
14175
|
-
|
14176
|
-
|
14177
|
-
|
14178
|
-
|
14179
|
-
|
14180
|
-
|
14181
|
-
|
14182
|
-
|
14183
|
-
|
13582
|
+
function publicKeyToProtobuf(key) {
|
13583
|
+
return PublicKey.encode({
|
13584
|
+
Type: KeyType[key.type],
|
13585
|
+
Data: key.raw
|
13586
|
+
});
|
13587
|
+
}
|
13588
|
+
|
13589
|
+
/**
|
13590
|
+
* All PeerId implementations must use this symbol as the name of a property
|
13591
|
+
* with a boolean `true` value
|
13592
|
+
*/
|
13593
|
+
const peerIdSymbol = Symbol.for('@libp2p/peer-id');
|
13594
|
+
|
13595
|
+
/**
|
13596
|
+
* When this error is thrown it means an operation was aborted,
|
13597
|
+
* usually in response to the `abort` event being emitted by an
|
13598
|
+
* AbortSignal.
|
13599
|
+
*/
|
13600
|
+
/**
|
13601
|
+
* Thrown when and attempt to operate on an unsupported key was made
|
13602
|
+
*/
|
13603
|
+
class UnsupportedKeyTypeError extends Error {
|
13604
|
+
static name = 'UnsupportedKeyTypeError';
|
13605
|
+
constructor(message = 'Unsupported key type') {
|
13606
|
+
super(message);
|
13607
|
+
this.name = 'UnsupportedKeyTypeError';
|
14184
13608
|
}
|
14185
13609
|
}
|
14186
13610
|
|
@@ -14200,25 +13624,16 @@ async function unmarshalPrivateKey(buf) {
|
|
14200
13624
|
* ```
|
14201
13625
|
*/
|
14202
13626
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
14203
|
-
const baseDecoder = Object
|
14204
|
-
.values(bases)
|
14205
|
-
.map(codec => codec.decoder)
|
14206
|
-
// @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
|
14207
|
-
.reduce((acc, curr) => acc.or(curr), bases.identity.decoder);
|
14208
13627
|
// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
|
14209
13628
|
const LIBP2P_KEY_CODE = 0x72;
|
14210
|
-
const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;
|
14211
|
-
const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;
|
14212
13629
|
class PeerIdImpl {
|
14213
13630
|
type;
|
14214
13631
|
multihash;
|
14215
|
-
privateKey;
|
14216
13632
|
publicKey;
|
14217
13633
|
string;
|
14218
13634
|
constructor(init) {
|
14219
13635
|
this.type = init.type;
|
14220
13636
|
this.multihash = init.multihash;
|
14221
|
-
this.privateKey = init.privateKey;
|
14222
13637
|
// mark string cache as non-enumerable
|
14223
13638
|
Object.defineProperty(this, 'string', {
|
14224
13639
|
enumerable: false,
|
@@ -14235,17 +13650,14 @@ class PeerIdImpl {
|
|
14235
13650
|
}
|
14236
13651
|
return this.string;
|
14237
13652
|
}
|
13653
|
+
toMultihash() {
|
13654
|
+
return this.multihash;
|
13655
|
+
}
|
14238
13656
|
// return self-describing String representation
|
14239
13657
|
// in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
|
14240
13658
|
toCID() {
|
14241
13659
|
return CID.createV1(LIBP2P_KEY_CODE, this.multihash);
|
14242
13660
|
}
|
14243
|
-
toBytes() {
|
14244
|
-
return this.multihash.bytes;
|
14245
|
-
}
|
14246
|
-
/**
|
14247
|
-
* Returns Multiaddr as a JSON string
|
14248
|
-
*/
|
14249
13661
|
toJSON() {
|
14250
13662
|
return this.toString();
|
14251
13663
|
}
|
@@ -14260,10 +13672,10 @@ class PeerIdImpl {
|
|
14260
13672
|
return equals(this.multihash.bytes, id);
|
14261
13673
|
}
|
14262
13674
|
else if (typeof id === 'string') {
|
14263
|
-
return
|
13675
|
+
return this.toString() === id;
|
14264
13676
|
}
|
14265
|
-
else if (id?.
|
14266
|
-
return equals(this.multihash.bytes, id.
|
13677
|
+
else if (id?.toMultihash()?.bytes != null) {
|
13678
|
+
return equals(this.multihash.bytes, id.toMultihash().bytes);
|
14267
13679
|
}
|
14268
13680
|
else {
|
14269
13681
|
throw new Error('not valid Id');
|
@@ -14285,7 +13697,7 @@ class PeerIdImpl {
|
|
14285
13697
|
return `PeerId(${this.toString()})`;
|
14286
13698
|
}
|
14287
13699
|
}
|
14288
|
-
class
|
13700
|
+
class RSAPeerId extends PeerIdImpl {
|
14289
13701
|
type = 'RSA';
|
14290
13702
|
publicKey;
|
14291
13703
|
constructor(init) {
|
@@ -14293,153 +13705,67 @@ class RSAPeerIdImpl extends PeerIdImpl {
|
|
14293
13705
|
this.publicKey = init.publicKey;
|
14294
13706
|
}
|
14295
13707
|
}
|
14296
|
-
class
|
13708
|
+
class Ed25519PeerId extends PeerIdImpl {
|
14297
13709
|
type = 'Ed25519';
|
14298
13710
|
publicKey;
|
14299
13711
|
constructor(init) {
|
14300
13712
|
super({ ...init, type: 'Ed25519' });
|
14301
|
-
this.publicKey = init.
|
13713
|
+
this.publicKey = init.publicKey;
|
14302
13714
|
}
|
14303
13715
|
}
|
14304
|
-
class
|
13716
|
+
class Secp256k1PeerId extends PeerIdImpl {
|
14305
13717
|
type = 'secp256k1';
|
14306
13718
|
publicKey;
|
14307
13719
|
constructor(init) {
|
14308
13720
|
super({ ...init, type: 'secp256k1' });
|
14309
|
-
this.publicKey = init.
|
14310
|
-
}
|
14311
|
-
}
|
14312
|
-
// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
|
14313
|
-
const TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;
|
14314
|
-
class URLPeerIdImpl {
|
14315
|
-
type = 'url';
|
14316
|
-
multihash;
|
14317
|
-
privateKey;
|
14318
|
-
publicKey;
|
14319
|
-
url;
|
14320
|
-
constructor(url) {
|
14321
|
-
this.url = url.toString();
|
14322
|
-
this.multihash = identity.digest(fromString(this.url));
|
14323
|
-
}
|
14324
|
-
[inspect]() {
|
14325
|
-
return `PeerId(${this.url})`;
|
14326
|
-
}
|
14327
|
-
[peerIdSymbol] = true;
|
14328
|
-
toString() {
|
14329
|
-
return this.toCID().toString();
|
14330
|
-
}
|
14331
|
-
toCID() {
|
14332
|
-
return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);
|
14333
|
-
}
|
14334
|
-
toBytes() {
|
14335
|
-
return this.toCID().bytes;
|
14336
|
-
}
|
14337
|
-
equals(other) {
|
14338
|
-
if (other == null) {
|
14339
|
-
return false;
|
14340
|
-
}
|
14341
|
-
if (other instanceof Uint8Array) {
|
14342
|
-
other = toString$1(other);
|
14343
|
-
}
|
14344
|
-
return other.toString() === this.toString();
|
14345
|
-
}
|
14346
|
-
}
|
14347
|
-
function peerIdFromString(str, decoder) {
|
14348
|
-
if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
|
14349
|
-
// identity hash ed25519/secp256k1 key or sha2-256 hash of
|
14350
|
-
// rsa public key - base58btc encoded either way
|
14351
|
-
const multihash = decode$2(base58btc.decode(`z${str}`));
|
14352
|
-
if (str.startsWith('12D')) {
|
14353
|
-
return new Ed25519PeerIdImpl({ multihash });
|
14354
|
-
}
|
14355
|
-
else if (str.startsWith('16U')) {
|
14356
|
-
return new Secp256k1PeerIdImpl({ multihash });
|
14357
|
-
}
|
14358
|
-
else {
|
14359
|
-
return new RSAPeerIdImpl({ multihash });
|
14360
|
-
}
|
14361
|
-
}
|
14362
|
-
return peerIdFromBytes(baseDecoder.decode(str));
|
14363
|
-
}
|
14364
|
-
function peerIdFromBytes(buf) {
|
14365
|
-
try {
|
14366
|
-
const multihash = decode$2(buf);
|
14367
|
-
if (multihash.code === identity.code) {
|
14368
|
-
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
|
14369
|
-
return new Ed25519PeerIdImpl({ multihash });
|
14370
|
-
}
|
14371
|
-
else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
|
14372
|
-
return new Secp256k1PeerIdImpl({ multihash });
|
14373
|
-
}
|
14374
|
-
}
|
14375
|
-
if (multihash.code === sha256$1.code) {
|
14376
|
-
return new RSAPeerIdImpl({ multihash });
|
14377
|
-
}
|
14378
|
-
}
|
14379
|
-
catch {
|
14380
|
-
return peerIdFromCID(CID.decode(buf));
|
14381
|
-
}
|
14382
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14383
|
-
}
|
14384
|
-
function peerIdFromCID(cid) {
|
14385
|
-
if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {
|
14386
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14387
|
-
}
|
14388
|
-
if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {
|
14389
|
-
const url = toString$1(cid.multihash.digest);
|
14390
|
-
return new URLPeerIdImpl(new URL(url));
|
14391
|
-
}
|
14392
|
-
const multihash = cid.multihash;
|
14393
|
-
if (multihash.code === sha256$1.code) {
|
14394
|
-
return new RSAPeerIdImpl({ multihash: cid.multihash });
|
14395
|
-
}
|
14396
|
-
else if (multihash.code === identity.code) {
|
14397
|
-
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
|
14398
|
-
return new Ed25519PeerIdImpl({ multihash: cid.multihash });
|
14399
|
-
}
|
14400
|
-
else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
|
14401
|
-
return new Secp256k1PeerIdImpl({ multihash: cid.multihash });
|
14402
|
-
}
|
13721
|
+
this.publicKey = init.publicKey;
|
14403
13722
|
}
|
14404
|
-
throw new Error('Supplied PeerID CID is invalid');
|
14405
13723
|
}
|
13724
|
+
|
14406
13725
|
/**
|
14407
|
-
* @
|
14408
|
-
*
|
13726
|
+
* @packageDocumentation
|
13727
|
+
*
|
13728
|
+
* An implementation of a peer id
|
13729
|
+
*
|
13730
|
+
* @example
|
13731
|
+
*
|
13732
|
+
* ```TypeScript
|
13733
|
+
* import { peerIdFromString } from '@libp2p/peer-id'
|
13734
|
+
* const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')
|
13735
|
+
*
|
13736
|
+
* console.log(peer.toCID()) // CID(bafzaa...)
|
13737
|
+
* console.log(peer.toString()) // "12D3K..."
|
13738
|
+
* ```
|
14409
13739
|
*/
|
14410
|
-
|
14411
|
-
if (publicKey.
|
14412
|
-
return new
|
13740
|
+
function peerIdFromPublicKey(publicKey) {
|
13741
|
+
if (publicKey.type === 'Ed25519') {
|
13742
|
+
return new Ed25519PeerId({
|
13743
|
+
multihash: publicKey.toCID().multihash,
|
13744
|
+
publicKey
|
13745
|
+
});
|
14413
13746
|
}
|
14414
|
-
if (publicKey.
|
14415
|
-
return new
|
13747
|
+
else if (publicKey.type === 'secp256k1') {
|
13748
|
+
return new Secp256k1PeerId({
|
13749
|
+
multihash: publicKey.toCID().multihash,
|
13750
|
+
publicKey
|
13751
|
+
});
|
14416
13752
|
}
|
14417
|
-
|
13753
|
+
else if (publicKey.type === 'RSA') {
|
13754
|
+
return new RSAPeerId({
|
13755
|
+
multihash: publicKey.toCID().multihash,
|
13756
|
+
publicKey
|
13757
|
+
});
|
13758
|
+
}
|
13759
|
+
throw new UnsupportedKeyTypeError();
|
14418
13760
|
}
|
14419
13761
|
|
13762
|
+
const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
|
14420
13763
|
function createPeerIdFromPublicKey(publicKey) {
|
14421
|
-
const
|
14422
|
-
|
14423
|
-
|
14424
|
-
function getPublicKeyFromPeerId(peerId) {
|
14425
|
-
if (peerId.type !== "secp256k1") {
|
14426
|
-
throw new Error("Unsupported peer id type");
|
14427
|
-
}
|
14428
|
-
if (!peerId.publicKey) {
|
14429
|
-
throw new Error("Public key not present on peer id");
|
14430
|
-
}
|
14431
|
-
return unmarshalPublicKey(peerId.publicKey).marshal();
|
14432
|
-
}
|
14433
|
-
// Only used in tests
|
14434
|
-
async function getPrivateKeyFromPeerId(peerId) {
|
14435
|
-
if (peerId.type !== "secp256k1") {
|
14436
|
-
throw new Error("Unsupported peer id type");
|
14437
|
-
}
|
14438
|
-
if (!peerId.privateKey) {
|
14439
|
-
throw new Error("Private key not present on peer id");
|
13764
|
+
const pubKey = publicKeyFromRaw(publicKey);
|
13765
|
+
if (pubKey.type !== "secp256k1") {
|
13766
|
+
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
|
14440
13767
|
}
|
14441
|
-
|
14442
|
-
return privateKey.marshal();
|
13768
|
+
return peerIdFromPublicKey(pubKey);
|
14443
13769
|
}
|
14444
13770
|
|
14445
13771
|
function decodeMultiaddrs(bytes) {
|
@@ -14686,12 +14012,12 @@ var TransportProtocolPerIpVersion;
|
|
14686
14012
|
class ENR extends RawEnr {
|
14687
14013
|
static RECORD_PREFIX = "enr:";
|
14688
14014
|
peerId;
|
14689
|
-
static
|
14015
|
+
static create(kvs = {}, seq = BigInt(1), signature) {
|
14690
14016
|
const enr = new ENR(kvs, seq, signature);
|
14691
14017
|
try {
|
14692
14018
|
const publicKey = enr.publicKey;
|
14693
14019
|
if (publicKey) {
|
14694
|
-
enr.peerId =
|
14020
|
+
enr.peerId = createPeerIdFromPublicKey(publicKey);
|
14695
14021
|
}
|
14696
14022
|
}
|
14697
14023
|
catch (e) {
|
@@ -14813,7 +14139,7 @@ class EnrCreator {
|
|
14813
14139
|
static fromPublicKey(publicKey, kvs = {}) {
|
14814
14140
|
// EIP-778 specifies that the key must be in compressed format, 33 bytes
|
14815
14141
|
if (publicKey.length !== 33) {
|
14816
|
-
publicKey = compressPublicKey
|
14142
|
+
publicKey = compressPublicKey(publicKey);
|
14817
14143
|
}
|
14818
14144
|
return ENR.create({
|
14819
14145
|
...kvs,
|
@@ -14824,7 +14150,7 @@ class EnrCreator {
|
|
14824
14150
|
static async fromPeerId(peerId, kvs = {}) {
|
14825
14151
|
switch (peerId.type) {
|
14826
14152
|
case "secp256k1":
|
14827
|
-
return EnrCreator.fromPublicKey(
|
14153
|
+
return EnrCreator.fromPublicKey(peerId.publicKey.raw, kvs);
|
14828
14154
|
default:
|
14829
14155
|
throw new Error();
|
14830
14156
|
}
|
@@ -15478,7 +14804,7 @@ async function fromValues(values) {
|
|
15478
14804
|
}
|
15479
14805
|
}
|
15480
14806
|
const _seq = decodeSeq(seq);
|
15481
|
-
const enr =
|
14807
|
+
const enr = ENR.create(obj, _seq, signature);
|
15482
14808
|
checkSignature(seq, kvs, enr, signature);
|
15483
14809
|
return enr;
|
15484
14810
|
}
|
@@ -15511,4 +14837,4 @@ function checkSignature(seq, kvs, enr, signature) {
|
|
15511
14837
|
}
|
15512
14838
|
}
|
15513
14839
|
|
15514
|
-
export { ENR, ERR_INVALID_ID, ERR_NO_SIGNATURE, EnrCreator, EnrDecoder, MAX_RECORD_SIZE, MULTIADDR_LENGTH_SIZE, TransportProtocol, TransportProtocolPerIpVersion, compressPublicKey
|
14840
|
+
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 };
|