@helia/ipns 8.2.1 → 8.2.2-e3522f5
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/dist/index.min.js.map +2 -2
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/routing/helia.d.ts +1 -1
- package/dist/src/routing/helia.d.ts.map +1 -1
- package/dist/src/routing/helia.js.map +1 -1
- package/dist/src/routing/local-store.d.ts +2 -2
- package/dist/src/routing/local-store.d.ts.map +1 -1
- package/dist/src/routing/local-store.js.map +1 -1
- package/dist/src/routing/pubsub.d.ts +1 -1
- package/dist/src/routing/pubsub.d.ts.map +1 -1
- package/dist/src/routing/pubsub.js.map +1 -1
- package/package.json +5 -5
- package/src/index.ts +4 -2
- package/src/routing/helia.ts +2 -1
- package/src/routing/local-store.ts +4 -2
- package/src/routing/pubsub.ts +4 -2
- package/dist/typedoc-urls.json +0 -48
package/dist/index.min.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../node_modules/timestamp-nano/dist/timestamp.min.js", "../../../node_modules/hashlru/index.js", "../src/index.ts", "../../../node_modules/@libp2p/interface/src/keys.ts", "../../../node_modules/@libp2p/interface/src/peer-id.ts", "../../../node_modules/@libp2p/interface/src/errors.ts", "../../../node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/multiformats/src/bytes.ts", "../../../node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/multiformats/src/bases/base.ts", "../../../node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/multiformats/src/bases/base64.ts", "../../../node_modules/weald/node_modules/ms/dist/index.mjs", "../../../node_modules/weald/src/common.ts", "../../../node_modules/weald/src/browser.ts", "../../../node_modules/weald/src/index.ts", "../../../node_modules/@libp2p/logger/src/index.ts", "../../../node_modules/multiformats/src/bases/base36.ts", "../../../node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/multiformats/src/varint.ts", "../../../node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/multiformats/src/cid.ts", "../../../node_modules/multiformats/src/hashes/identity.ts", "../../../node_modules/uint8arrays/src/equals.ts", "../../../node_modules/uint8arrays/src/alloc.ts", "../../../node_modules/uint8arrays/src/concat.ts", "../../../node_modules/uint8arraylist/src/index.ts", "../../../node_modules/multiformats/src/bases/base10.ts", "../../../node_modules/multiformats/src/bases/base16.ts", "../../../node_modules/multiformats/src/bases/base2.ts", "../../../node_modules/multiformats/src/bases/base256emoji.ts", "../../../node_modules/multiformats/src/bases/base8.ts", "../../../node_modules/multiformats/src/bases/identity.ts", "../../../node_modules/multiformats/src/codecs/json.ts", "../../../node_modules/multiformats/src/hashes/sha2-browser.ts", "../../../node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/multiformats/src/basics.ts", "../../../node_modules/uint8arrays/src/util/bases.ts", "../../../node_modules/uint8arrays/src/from-string.ts", "../../../node_modules/uint8arrays/src/to-string.ts", "../../../node_modules/@libp2p/crypto/src/keys/rsa/der.ts", "../../../node_modules/@libp2p/crypto/src/keys/ecdsa/index.ts", "../../../node_modules/@libp2p/crypto/src/keys/ecdsa/utils.ts", "../../../node_modules/@libp2p/crypto/src/keys/ecdsa/ecdsa.ts", "../../../node_modules/@noble/hashes/src/crypto.ts", "../../../node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/@noble/hashes/src/sha2.ts", "../../../node_modules/@noble/curves/src/abstract/utils.ts", "../../../node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/@noble/curves/src/ed25519.ts", "../../../node_modules/@libp2p/crypto/src/keys/ed25519/index.browser.ts", "../../../node_modules/@libp2p/crypto/src/keys/ed25519/ed25519.ts", "../../../node_modules/@libp2p/crypto/src/keys/ed25519/utils.ts", "../../../node_modules/uint8-varint/src/index.ts", "../../../node_modules/protons-runtime/src/utils/float.ts", "../../../node_modules/protons-runtime/src/utils/longbits.ts", "../../../node_modules/protons-runtime/src/utils/utf8.ts", "../../../node_modules/protons-runtime/src/utils/reader.ts", "../../../node_modules/protons-runtime/src/decode.ts", "../../../node_modules/protons-runtime/src/utils/pool.ts", "../../../node_modules/protons-runtime/src/utils/writer.ts", "../../../node_modules/protons-runtime/src/encode.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../../node_modules/@libp2p/crypto/src/keys/keys.ts", "../../../node_modules/@libp2p/crypto/src/errors.ts", "../../../node_modules/@libp2p/crypto/src/webcrypto/webcrypto.browser.ts", "../../../node_modules/@libp2p/crypto/src/webcrypto/index.ts", "../../../node_modules/@libp2p/crypto/src/keys/rsa/utils.ts", "../../../node_modules/@noble/hashes/src/sha256.ts", "../../../node_modules/@libp2p/crypto/src/keys/rsa/rsa.ts", "../../../node_modules/@libp2p/crypto/src/keys/rsa/index.browser.ts", "../../../node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/@noble/curves/src/_shortw_utils.ts", "../../../node_modules/@noble/curves/src/secp256k1.ts", "../../../node_modules/@libp2p/crypto/src/util.ts", "../../../node_modules/@libp2p/crypto/src/keys/secp256k1/index.browser.ts", "../../../node_modules/@libp2p/crypto/src/keys/secp256k1/secp256k1.ts", "../../../node_modules/@libp2p/crypto/src/keys/secp256k1/utils.ts", "../../../node_modules/@libp2p/crypto/src/keys/index.ts", "../../../node_modules/@libp2p/peer-id/src/peer-id.ts", "../../../node_modules/@libp2p/peer-id/src/index.ts", "../../../node_modules/interface-datastore/src/key.ts", "../../../node_modules/ipns/src/index.ts", "../../../node_modules/ipns/src/errors.ts", "../../../node_modules/ipns/src/pb/ipns.ts", "../../../node_modules/cborg/lib/is.js", "../../../node_modules/cborg/lib/token.js", "../../../node_modules/cborg/lib/byte-utils.js", "../../../node_modules/cborg/lib/bl.js", "../../../node_modules/cborg/lib/common.js", "../../../node_modules/cborg/lib/0uint.js", "../../../node_modules/cborg/lib/1negint.js", "../../../node_modules/cborg/lib/2bytes.js", "../../../node_modules/cborg/lib/3string.js", "../../../node_modules/cborg/lib/4array.js", "../../../node_modules/cborg/lib/5map.js", "../../../node_modules/cborg/lib/6tag.js", "../../../node_modules/cborg/lib/7float.js", "../../../node_modules/cborg/lib/jump.js", "../../../node_modules/cborg/lib/encode.js", "../../../node_modules/cborg/lib/decode.js", "../../../node_modules/ipns/src/utils.ts", "../../../node_modules/ipns/src/selector.ts", "../../../node_modules/ipns/src/validator.ts", "../../../node_modules/progress-events/src/index.ts", "../../../node_modules/@multiformats/dns/src/utils/cache.ts", "../../../node_modules/@multiformats/dns/src/index.ts", "../src/errors.ts", "../src/dnslink.ts", "../src/routing/helia.ts", "../../../node_modules/@libp2p/record/src/record.ts", "../../../node_modules/@libp2p/record/src/utils.ts", "../../../node_modules/@libp2p/record/src/index.ts", "../../../node_modules/@libp2p/kad-dht/src/index.ts", "../src/routing/local-store.ts", "../src/utils.ts"],
|
|
4
|
-
"sourcesContent": ["var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1<n.length?n[1]--:n[1]=0;if(r.time=e=Date.UTC.apply(Date,n)-(e||0),isNaN(e))throw new TypeError(\"Invalid Date\");return p(r)},d.fromTimeT=function(n){return y(n,0)},n.year=0,n.time=0,n.nano=0,n.addNano=function(n){return this.nano+=+n||0,this},n.getNano=function(){var n=p(this);return(n.time%1e3*h+ +n.nano+1e9)%1e9},n.getTimeT=function(){var n=p(this),t=Math.floor(n.time/1e3),n=n.year;n&&(t+=n*T*l/s);return t},n.getYear=function(){return this.toDate().getUTCFullYear()+this.year},n.toDate=function(){return M(p(this).time)},n.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,\"Z\")},n.toString=function(n){var t=this,r=t.toDate(),u={H:function(){return C(r.getUTCHours())},L:function(){return D(r.getUTCMilliseconds(),3)},M:function(){return C(r.getUTCMinutes())},N:function(){return D(t.getNano(),9)},S:function(){return C(r.getUTCSeconds())},Y:function(){var n=t.getYear();return 999999<n?\"+\"+n:9999<n?\"+\"+D(n,6):0<=n?D(n,4):-999999<=n?\"-\"+D(-n,6):n},a:function(){return a[r.getUTCDay()]},b:function(){return i[r.getUTCMonth()]},d:function(){return C(r.getUTCDate())},e:function(){return function(n){return(9<n?\"\":\" \")+(0|n)}(r.getUTCDate())},m:function(){return C(r.getUTCMonth()+1)}};return function e(n){return n.replace(/%./g,function(n){var t=n[1],r=v[t],t=u[t];return r?e(r):t?t():n})}(n||o)},n.writeInt64BE=t(0,1,2,3,0,4),n.writeInt64LE=t(3,2,1,0,4,0),\"%Y-%m-%dT%H:%M:%S.%NZ\"),i=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],a=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],v={\"%\":\"%\",F:\"%Y-%m-%d\",n:\"\\n\",R:\"%H:%M\",T:\"%H:%M:%S\",t:\"\\t\",X:\"%T\",Z:\"GMT\",z:\"+0000\"};return d;function d(n,t,r){var e=this;if(!(e instanceof d))return new d(n,t,r);e.time=+n||0,e.nano=+t||0,e.year=+r||0,p(e)}function p(n){var t,r,e,u=n.year,o=n.time,i=n.nano,a=((i<0||h<=i)&&(i-=(r=Math.floor(i/h))*h,o+=r,r=1),u%s);return(o<-c||c<o||a)&&((t=m(o/f))&&(u+=t*s,o-=t*f),(e=M(o)).setUTCFullYear(a+e.getUTCFullYear()),e=(o=+e)+(t=m((u-=a)/s))*f,t&&-c<=e&&e<=c&&(u-=t*s,o=e),r=1),r&&(n.year=u,n.time=o,n.nano=i),n}function M(n){var t=new Date(0);return t.setTime(n),t}function y(n,t){n=+n||0;var r=m((t=(t|0)*g)/e)+m(n/e),t=t%e+n%e,n=m(t/e);return n&&(r+=n,t-=n*e),new d(1e3*t,0,r*s)}function t(e,u,o,i,a,f){return function(n,t){var r=p(this);n=n||new Array(8);w(n,t|=0);var e=Math.floor(r.time/1e3),r=r.year*(T*l/s),u=m(r/g)+m(e/g),r=r%g+e%g,e=Math.floor(r/g);e&&(u+=e,r-=e*g);return c(n,t+a,u),c(n,t+f,r),n};function c(n,t,r){n[t+e]=r>>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n<t+8)throw new RangeError(\"Out of range\")}function C(n){return(9<n?\"\":\"0\")+(0|n)}function D(n,t){return(u+(0|n)).substr(-t)}}();", "module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n", "/**\n * @packageDocumentation\n *\n * IPNS operations using a Helia node\n *\n * @example Getting started\n *\n * With {@link IPNSRouting} routers:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n *\n * console.info(result.cid, result.path)\n * ```\n *\n * @example Publishing a recursive record\n *\n * A recursive record is a one that points to another record rather than to a\n * value.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // create another keypair to re-publish the original record\n * const recursivePrivateKey = await generateKeyPair('Ed25519')\n *\n * // publish the recursive name\n * await name.publish(recursivePrivateKey, privateKey.publicKey)\n *\n * // resolve the name recursively - it resolves until a CID is found\n * const result = await name.resolve(recursivePrivateKey.publicKey)\n * console.info(result.cid.toString() === cid.toString()) // true\n * ```\n *\n * @example Publishing a record with a path\n *\n * It is possible to publish CIDs with an associated path.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const fileCid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // store the file in a directory\n * const dirCid = await fs.addDirectory()\n * const finalDirCid = await fs.cp(fileCid, dirCid, '/foo.txt')\n *\n * // publish the name\n * await name.publish(privateKey, `/ipfs/${finalDirCid}/foo.txt`)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n *\n * console.info(result.cid, result.path) // QmFoo.. 'foo.txt'\n * ```\n *\n * @example Using custom PubSub router\n *\n * Additional IPNS routers can be configured - these enable alternative means to\n * publish and resolve IPNS names.\n *\n * One example is the PubSub router - this requires an instance of Helia with\n * libp2p PubSub configured.\n *\n * It works by subscribing to a pubsub topic for each IPNS name that we try to\n * resolve. Updated IPNS records are shared on these topics so an update must\n * occur before the name is resolvable.\n *\n * This router is only suitable for networks where IPNS updates are frequent\n * and multiple peers are listening on the topic(s), otherwise update messages\n * may fail to be published with \"Insufficient peers\" errors.\n *\n * ```TypeScript\n * import { createHelia, libp2pDefaults } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { pubsub } from '@helia/ipns/routing'\n * import { unixfs } from '@helia/unixfs'\n * import { gossipsub } from '@chainsafe/libp2p-gossipsub'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n * import type { Libp2p, PubSub } from '@libp2p/interface'\n * import type { DefaultLibp2pServices } from 'helia'\n *\n * const libp2pOptions = libp2pDefaults()\n * libp2pOptions.services.pubsub = gossipsub()\n *\n * const helia = await createHelia<Libp2p<DefaultLibp2pServices & { pubsub: PubSub }>>({\n * libp2p: libp2pOptions\n * })\n * const name = ipns(helia, {\n * routers: [\n * pubsub(helia)\n * ]\n * })\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n * ```\n *\n * @example Using custom DNS over HTTPS resolvers\n *\n * To use custom resolvers, configure Helia's `dns` option:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns/resolvers'\n * import { helia } from '@helia/ipns/routing'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsOverHttps('https://private-dns-server.me/dns-query')\n * }\n * })\n * })\n * const name = ipns(node, {\n * routers: [\n * helia(node.routing)\n * ]\n * })\n *\n * const result = name.resolveDNSLink('some-domain-with-dnslink-entry.com')\n * ```\n *\n * @example Resolving a domain with a dnslink entry\n *\n * Calling `resolveDNSLink` with the `@helia/ipns` instance:\n *\n * ```TypeScript\n * // resolve a CID from a TXT record in a DNS zone file, using the default\n * // resolver for the current platform eg:\n * // > dig _dnslink.ipfs.io TXT\n * // ;; ANSWER SECTION:\n * // _dnslink.ipfs.io. 60 IN TXT \"dnslink=/ipns/website.ipfs.io\"\n * // > dig _dnslink.website.ipfs.io TXT\n * // ;; ANSWER SECTION:\n * // _dnslink.website.ipfs.io. 60 IN TXT \"dnslink=/ipfs/QmWebsite\"\n *\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n *\n * const node = await createHelia()\n * const name = ipns(node)\n *\n * const { answer } = await name.resolveDNSLink('ipfs.io')\n *\n * console.info(answer)\n * // { data: '/ipfs/QmWebsite' }\n * ```\n *\n * @example Using DNS-Over-HTTPS\n *\n * This example uses the Mozilla provided RFC 1035 DNS over HTTPS service. This\n * uses binary DNS records so requires extra dependencies to process the\n * response which can increase browser bundle sizes.\n *\n * If this is a concern, use the DNS-JSON-Over-HTTPS resolver instead.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns/resolvers'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsOverHttps('https://mozilla.cloudflare-dns.com/dns-query')\n * }\n * })\n * })\n * const name = ipns(node)\n *\n * const result = await name.resolveDNSLink('ipfs.io')\n * ```\n *\n * @example Using DNS-JSON-Over-HTTPS\n *\n * DNS-JSON-Over-HTTPS resolvers use the RFC 8427 `application/dns-json` and can\n * result in a smaller browser bundle due to the response being plain JSON.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsJsonOverHttps('https://mozilla.cloudflare-dns.com/dns-query')\n * }\n * })\n * })\n * const name = ipns(node)\n *\n * const result = await name.resolveDNSLink('ipfs.io')\n * ```\n *\n * @example Republishing an existing IPNS record\n *\n * The `republishRecord` method allows you to republish an existing IPNS record without\n * needing the private key. This is useful for relay nodes or when you want to extend\n * the availability of a record that was created elsewhere.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { createDelegatedRoutingV1HttpApiClient } from '@helia/delegated-routing-v1-http-api-client'\n * import { CID } from 'multiformats/cid'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * const ipnsName = 'k51qzi5uqu5dktsyfv7xz8h631pri4ct7osmb43nibxiojpttxzoft6hdyyzg4'\n * const parsedCid: CID<unknown, 114, 0 | 18, 1> = CID.parse(ipnsName)\n * const delegatedClient = createDelegatedRoutingV1HttpApiClient('https://delegated-ipfs.dev')\n * const record = await delegatedClient.getIPNS(parsedCid)\n *\n * await name.republishRecord(ipnsName, record)\n * ```\n */\n\nimport { NotFoundError, isPublicKey } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { createIPNSRecord, extractPublicKeyFromIPNSRecord, marshalIPNSRecord, multihashToIPNSRoutingKey, unmarshalIPNSRecord, type IPNSRecord } from 'ipns'\nimport { ipnsSelector } from 'ipns/selector'\nimport { ipnsValidator } from 'ipns/validator'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CustomProgressEvent } from 'progress-events'\nimport { resolveDNSLink } from './dnslink.js'\nimport { InvalidValueError, RecordsFailedValidationError, UnsupportedMultibasePrefixError, UnsupportedMultihashCodecError } from './errors.js'\nimport { helia } from './routing/helia.js'\nimport { localStore, type LocalStore } from './routing/local-store.js'\nimport { isCodec, IDENTITY_CODEC, SHA2_256_CODEC, IPNS_STRING_PREFIX } from './utils.js'\nimport type { IPNSRouting, IPNSRoutingEvents } from './routing/index.js'\nimport type { Routing } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger, PrivateKey, PublicKey } from '@libp2p/interface'\nimport type { Answer, DNS, ResolveDnsProgressEvents } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nconst log = logger('helia:ipns')\n\nconst MINUTE = 60 * 1000\nconst HOUR = 60 * MINUTE\n\nconst DEFAULT_LIFETIME_MS = 48 * HOUR\nconst DEFAULT_REPUBLISH_INTERVAL_MS = 23 * HOUR\n\nconst DEFAULT_TTL_NS = BigInt(MINUTE) * 5_000_000n // 5 minutes\n\nexport type PublishProgressEvents =\n ProgressEvent<'ipns:publish:start'> |\n ProgressEvent<'ipns:publish:success', IPNSRecord> |\n ProgressEvent<'ipns:publish:error', Error>\n\nexport type ResolveProgressEvents =\n ProgressEvent<'ipns:resolve:start', unknown> |\n ProgressEvent<'ipns:resolve:success', IPNSRecord> |\n ProgressEvent<'ipns:resolve:error', Error>\n\nexport type RepublishProgressEvents =\n ProgressEvent<'ipns:republish:start', unknown> |\n ProgressEvent<'ipns:republish:success', IPNSRecord> |\n ProgressEvent<'ipns:republish:error', { key?: MultihashDigest<0x00 | 0x12>, record: IPNSRecord, err: Error }>\n\nexport type ResolveDNSLinkProgressEvents =\n ResolveProgressEvents |\n IPNSRoutingEvents |\n ResolveDnsProgressEvents\n\nexport interface PublishOptions extends AbortOptions, ProgressOptions<PublishProgressEvents | IPNSRoutingEvents> {\n /**\n * Time duration of the signature validity in ms (default: 48hrs)\n */\n lifetime?: number\n\n /**\n * Only publish to a local datastore (default: false)\n */\n offline?: boolean\n\n /**\n * By default a IPNS V1 and a V2 signature is added to every record. Pass\n * false here to only add a V2 signature. (default: true)\n */\n v1Compatible?: boolean\n\n /**\n * The TTL of the record in ms (default: 5 minutes)\n */\n ttl?: number\n}\n\nexport interface ResolveOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached IPNS Record entries\n *\n * @default false\n */\n nocache?: boolean\n}\n\nexport interface ResolveDNSLinkOptions extends AbortOptions, ProgressOptions<ResolveDNSLinkProgressEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n nocache?: boolean\n\n /**\n * When resolving DNSLink records that resolve to other DNSLink records, limit\n * how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface RepublishOptions extends AbortOptions, ProgressOptions<RepublishProgressEvents | IPNSRoutingEvents> {\n /**\n * The republish interval in ms (default: 23hrs)\n */\n interval?: number\n}\n\nexport interface RepublishRecordOptions extends AbortOptions, ProgressOptions<RepublishProgressEvents | IPNSRoutingEvents> {\n /**\n * Only publish to a local datastore\n *\n * @default false\n */\n offline?: boolean\n}\n\nexport interface ResolveResult {\n /**\n * The CID that was resolved\n */\n cid: CID\n\n /**\n * Any path component that was part of the resolved record\n *\n * @default \"\"\n */\n path: string\n}\n\nexport interface IPNSResolveResult extends ResolveResult {\n /**\n * The resolved record\n */\n record: IPNSRecord\n}\n\nexport interface DNSLinkResolveResult extends ResolveResult {\n /**\n * The resolved record\n */\n answer: Answer\n}\n\nexport interface IPNS {\n /**\n * Creates an IPNS record signed by the passed PeerId that will resolve to the passed value\n *\n * If the value is a PeerId, a recursive IPNS record will be created.\n */\n publish(key: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, options?: PublishOptions): Promise<IPNSRecord>\n\n /**\n * Accepts a public key formatted as a libp2p PeerID and resolves the IPNS record\n * corresponding to that public key until a value is found\n */\n resolve(key: PublicKey | MultihashDigest<0x00 | 0x12>, options?: ResolveOptions): Promise<IPNSResolveResult>\n\n /**\n * Resolve a CID from a dns-link style IPNS record\n */\n resolveDNSLink(domain: string, options?: ResolveDNSLinkOptions): Promise<DNSLinkResolveResult>\n\n /**\n * Periodically republish all IPNS records found in the datastore\n */\n republish(options?: RepublishOptions): void\n\n /**\n * Republish an existing IPNS record without the private key.\n *\n * Before republishing the record will be validated to ensure it has a valid signature and lifetime(validity) in the future.\n * The key is a multihash of the public key or a string representation of the PeerID (either base58btc encoded multihash or base36 encoded CID)\n */\n republishRecord(key: MultihashDigest<0x00 | 0x12> | string, record: IPNSRecord, options?: RepublishRecordOptions): Promise<void>\n}\n\nexport type { IPNSRouting } from './routing/index.js'\n\nexport type { IPNSRecord } from 'ipns'\n\nexport interface IPNSComponents {\n datastore: Datastore\n routing: Routing\n dns: DNS\n logger: ComponentLogger\n}\n\nconst bases: Record<string, MultibaseDecoder<string>> = {\n [base36.prefix]: base36,\n [base58btc.prefix]: base58btc\n}\n\nclass DefaultIPNS implements IPNS {\n private readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private timeout?: ReturnType<typeof setTimeout>\n private readonly dns: DNS\n private readonly log: Logger\n\n constructor (components: IPNSComponents, routers: IPNSRouting[] = []) {\n this.routers = [\n helia(components.routing),\n ...routers\n ]\n this.localStore = localStore(components.datastore)\n this.dns = components.dns\n this.log = components.logger.forComponent('helia:ipns')\n }\n\n async publish (key: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, options: PublishOptions = {}): Promise<IPNSRecord> {\n try {\n let sequenceNumber = 1n\n const routingKey = multihashToIPNSRoutingKey(key.publicKey.toMultihash())\n\n if (await this.localStore.has(routingKey, options)) {\n // if we have published under this key before, increment the sequence number\n const { record } = await this.localStore.get(routingKey, options)\n const existingRecord = unmarshalIPNSRecord(record)\n sequenceNumber = existingRecord.sequence + 1n\n }\n\n // convert ttl from milliseconds to nanoseconds as createIPNSRecord expects\n const ttlNs = options.ttl != null ? BigInt(options.ttl) * 1_000_000n : DEFAULT_TTL_NS\n const record = await createIPNSRecord(key, value, sequenceNumber, options.lifetime ?? DEFAULT_LIFETIME_MS, { ...options, ttlNs })\n const marshaledRecord = marshalIPNSRecord(record)\n\n await this.localStore.put(routingKey, marshaledRecord, options)\n\n if (options.offline !== true) {\n // publish record to routing\n await Promise.all(this.routers.map(async r => { await r.put(routingKey, marshaledRecord, options) }))\n }\n\n return record\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:publish:error', err))\n throw err\n }\n }\n\n async resolve (key: PublicKey | MultihashDigest<0x00 | 0x12>, options: ResolveOptions = {}): Promise<IPNSResolveResult> {\n const digest = isPublicKey(key) ? key.toMultihash() : key\n const routingKey = multihashToIPNSRoutingKey(digest)\n const record = await this.#findIpnsRecord(routingKey, options)\n\n return {\n ...(await this.#resolve(record.value, options)),\n record\n }\n }\n\n async resolveDNSLink (domain: string, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResolveResult> {\n const dnslink = await resolveDNSLink(domain, this.dns, this.log, options)\n\n return {\n ...(await this.#resolve(dnslink.value, options)),\n answer: dnslink.answer\n }\n }\n\n republish (options: RepublishOptions = {}): void {\n if (this.timeout != null) {\n throw new Error('Republish is already running')\n }\n\n options.signal?.addEventListener('abort', () => {\n clearTimeout(this.timeout)\n })\n\n async function republish (): Promise<void> {\n const startTime = Date.now()\n\n options.onProgress?.(new CustomProgressEvent('ipns:republish:start'))\n\n const finishType = Date.now()\n const timeTaken = finishType - startTime\n let nextInterval = DEFAULT_REPUBLISH_INTERVAL_MS - timeTaken\n\n if (nextInterval < 0) {\n nextInterval = options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS\n }\n\n setTimeout(() => {\n republish().catch(err => {\n log.error('error republishing', err)\n })\n }, nextInterval)\n }\n\n this.timeout = setTimeout(() => {\n republish().catch(err => {\n log.error('error republishing', err)\n })\n }, options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS)\n }\n\n async #resolve (ipfsPath: string, options: ResolveOptions = {}): Promise<{ cid: CID, path: string }> {\n const parts = ipfsPath.split('/')\n try {\n const scheme = parts[1]\n\n if (scheme === 'ipns') {\n const str = parts[2]\n const prefix = str.substring(0, 1)\n let buf: Uint8Array | undefined\n\n if (prefix === '1' || prefix === 'Q') {\n buf = base58btc.decode(`z${str}`)\n } else if (bases[prefix] != null) {\n buf = bases[prefix].decode(str)\n } else {\n throw new UnsupportedMultibasePrefixError(`Unsupported multibase prefix \"${prefix}\"`)\n }\n\n let digest: MultihashDigest<number>\n\n try {\n digest = Digest.decode(buf)\n } catch {\n digest = CID.decode(buf).multihash\n }\n\n if (!isCodec(digest, IDENTITY_CODEC) && !isCodec(digest, SHA2_256_CODEC)) {\n throw new UnsupportedMultihashCodecError(`Unsupported multihash codec \"${digest.code}\"`)\n }\n\n const { cid } = await this.resolve(digest, options)\n const path = parts.slice(3).join('/')\n return {\n cid,\n path\n }\n } else if (scheme === 'ipfs') {\n const cid = CID.parse(parts[2])\n const path = parts.slice(3).join('/')\n return {\n cid,\n path\n }\n }\n } catch (err) {\n log.error('error parsing ipfs path', err)\n }\n\n log.error('invalid ipfs path %s', ipfsPath)\n throw new InvalidValueError('Invalid value')\n }\n\n async #findIpnsRecord (routingKey: Uint8Array, options: ResolveOptions = {}): Promise<IPNSRecord> {\n const records: Uint8Array[] = []\n const cached = await this.localStore.has(routingKey, options)\n\n if (cached) {\n log('record is present in the cache')\n\n if (options.nocache !== true) {\n try {\n // check the local cache first\n const { record, created } = await this.localStore.get(routingKey, options)\n\n this.log('record retrieved from cache')\n\n // validate the record\n await ipnsValidator(routingKey, record)\n\n this.log('record was valid')\n\n // check the TTL\n const ipnsRecord = unmarshalIPNSRecord(record)\n\n // IPNS TTL is in nanoseconds, convert to milliseconds, default to one\n // hour\n const ttlMs = Number((ipnsRecord.ttl ?? DEFAULT_TTL_NS) / 1_000_000n)\n const ttlExpires = created.getTime() + ttlMs\n\n if (ttlExpires > Date.now()) {\n // the TTL has not yet expired, return the cached record\n this.log('record TTL was valid')\n return ipnsRecord\n }\n\n if (options.offline === true) {\n // the TTL has expired but we are skipping the routing search\n this.log('record TTL has been reached but we are resolving offline-only, returning record')\n return ipnsRecord\n }\n\n this.log('record TTL has been reached, searching routing for updates')\n\n // add the local record to our list of resolved record, and also\n // search the routing for updates - the most up to date record will be\n // returned\n records.push(record)\n } catch (err) {\n this.log('cached record was invalid', err)\n await this.localStore.delete(routingKey, options)\n }\n } else {\n log('ignoring local cache due to nocache=true option')\n }\n }\n\n if (options.offline === true) {\n throw new NotFoundError('Record was not present in the cache or has expired')\n }\n\n log('did not have record locally')\n\n let foundInvalid = 0\n\n await Promise.all(\n this.routers.map(async (router) => {\n let record: Uint8Array\n\n try {\n record = await router.get(routingKey, {\n ...options,\n validate: false\n })\n } catch (err: any) {\n log.error('error finding IPNS record', err)\n\n return\n }\n\n try {\n await ipnsValidator(routingKey, record)\n\n records.push(record)\n } catch (err) {\n // we found a record, but the validator rejected it\n foundInvalid++\n log.error('error finding IPNS record', err)\n }\n })\n )\n\n if (records.length === 0) {\n if (foundInvalid > 0) {\n throw new RecordsFailedValidationError(`${foundInvalid > 1 ? `${foundInvalid} records` : 'Record'} found for routing key ${foundInvalid > 1 ? 'were' : 'was'} invalid`)\n }\n\n throw new NotFoundError('Could not find record for routing key')\n }\n\n const record = records[ipnsSelector(routingKey, records)]\n\n await this.localStore.put(routingKey, record, options)\n\n return unmarshalIPNSRecord(record)\n }\n\n async republishRecord (key: MultihashDigest<0x00 | 0x12> | string, record: IPNSRecord, options: RepublishRecordOptions = {}): Promise<void> {\n let mh: MultihashDigest<0x00 | 0x12> | undefined\n try {\n mh = extractPublicKeyFromIPNSRecord(record)?.toMultihash() // embedded public key take precedence, if present\n if (mh == null) {\n // if no public key is embedded in the record, use the key that was passed in\n if (typeof key === 'string') {\n if (key.startsWith(IPNS_STRING_PREFIX)) {\n // remove the /ipns/ prefix from the key\n key = key.slice(IPNS_STRING_PREFIX.length)\n }\n // Convert string key to MultihashDigest\n try {\n mh = peerIdFromString(key).toMultihash()\n } catch (err: any) {\n throw new Error(`Invalid string key: ${err.message}`)\n }\n } else {\n mh = key\n }\n }\n\n if (mh == null) {\n throw new Error('No public key multihash found to determine the routing key')\n }\n\n const routingKey = multihashToIPNSRoutingKey(mh)\n const marshaledRecord = marshalIPNSRecord(record)\n\n await ipnsValidator(routingKey, marshaledRecord) // validate that they key corresponds to the record\n\n await this.localStore.put(routingKey, marshaledRecord, options) // add to local store\n\n if (options.offline !== true) {\n // publish record to routing\n await Promise.all(this.routers.map(async r => { await r.put(routingKey, marshaledRecord, options) }))\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent('ipns:republish:error', { key: mh, record, err }))\n throw err\n }\n }\n}\n\nexport interface IPNSOptions {\n routers?: IPNSRouting[]\n}\n\nexport function ipns (components: IPNSComponents, { routers = [] }: IPNSOptions = {}): IPNS {\n return new DefaultIPNS(components, routers)\n}\n\nexport { ipnsValidator, type IPNSRoutingEvents }\nexport { ipnsSelector } from 'ipns/selector'\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport type KeyType = 'RSA' | 'Ed25519' | 'secp256k1' | 'ECDSA'\n\nexport interface RSAPublicKey {\n /**\n * The type of this key\n */\n readonly type: 'RSA'\n\n /**\n * PKIX in ASN1 DER format\n */\n readonly raw: Uint8Array\n\n /**\n * The public key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as a Multihash digest.\n *\n * It contains a sha256 hash of the protobuf version of the public key.\n */\n toMultihash(): MultihashDigest<0x12>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains a sha256 hash of the protobuf version of the public\n * key.\n */\n toCID(): CID<unknown, 0x72, 0x12, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface Ed25519PublicKey {\n /**\n * The type of this key\n */\n readonly type: 'Ed25519'\n\n /**\n * The raw public key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface Secp256k1PublicKey {\n /**\n * The type of this key\n */\n readonly type: 'secp256k1'\n\n /**\n * The raw public key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface ECDSAPublicKey {\n /**\n * The type of this key\n */\n readonly type: 'ECDSA'\n\n /**\n * The public key as a DER-encoded PKIMessage\n */\n readonly raw: Uint8Array\n\n /**\n * The public key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport type PublicKey = RSAPublicKey | Ed25519PublicKey | Secp256k1PublicKey | ECDSAPublicKey\n\n/**\n * Returns true if the passed argument has type overlap with the `PublicKey`\n * interface. Can be used to disambiguate object types.\n */\nexport function isPublicKey (key?: any): key is PublicKey {\n if (key == null) {\n return false\n }\n\n return (key.type === 'RSA' || key.type === 'Ed25519' || key.type === 'secp256k1' || key.type === 'ECDSA') &&\n key.raw instanceof Uint8Array &&\n typeof key.equals === 'function' &&\n typeof key.toMultihash === 'function' &&\n typeof key.toCID === 'function' &&\n typeof key.verify === 'function'\n}\n\n/**\n * Generic private key interface\n */\nexport interface RSAPrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'RSA'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: RSAPublicKey\n\n /**\n * PKIX in ASN1 DER format\n */\n readonly raw: Uint8Array\n\n /**\n * The private key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface Ed25519PrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'Ed25519'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: Ed25519PublicKey\n\n /**\n * The raw private key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface Secp256k1PrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'secp256k1'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: Secp256k1PublicKey\n\n /**\n * The raw private key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface ECDSAPrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'ECDSA'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: ECDSAPublicKey\n\n /**\n * The private key as a DER-encoded PKIMessage\n */\n readonly raw: Uint8Array\n\n /**\n * The private key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport type PrivateKey = RSAPrivateKey | Ed25519PrivateKey | Secp256k1PrivateKey | ECDSAPrivateKey\n\n/**\n * Returns true if the passed argument has type overlap with the `PrivateKey`\n * interface. Can be used to disambiguate object types.\n */\nexport function isPrivateKey (key?: any): key is PrivateKey {\n if (key == null) {\n return false\n }\n\n return (key.type === 'RSA' || key.type === 'Ed25519' || key.type === 'secp256k1' || key.type === 'ECDSA') &&\n isPublicKey(key.publicKey) &&\n key.raw instanceof Uint8Array &&\n typeof key.equals === 'function' &&\n typeof key.sign === 'function'\n}\n", "import type { Ed25519PublicKey, KeyType, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = KeyType | string\n\n/**\n * A PeerId generated from an RSA public key - it is a base58btc encoded sha-256\n * hash of the public key.\n *\n * RSA public keys are too large to pass around freely, instead Ed25519 or\n * secp256k1 should be preferred as they can embed their public key in the\n * PeerId itself.\n *\n * @deprecated Ed25519 or secp256k1 keys are preferred to RSA\n */\nexport interface RSAPeerId {\n readonly type: 'RSA'\n\n /**\n * RSA public keys are too large to embed in the multihash commonly used to\n * refer to peers, so this will only be defined if the public key has\n * previously been found through a routing query or during normal protocol\n * operations\n */\n readonly publicKey?: RSAPublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the SHA2-256 hash of the public\n * key\n */\n toMultihash(): MultihashDigest<0x12>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x12, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Ed25519PeerId {\n readonly type: 'Ed25519'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Ed25519PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Secp256k1PeerId {\n readonly type: 'secp256k1'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Secp256k1PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface URLPeerId {\n readonly type: 'url'\n\n /**\n * This will always be undefined as URL Peers do not have public keys\n */\n readonly publicKey: undefined\n\n /**\n * Returns CID from `toCID()` encoded as a base36 string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the URL encoded as an identity\n * hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the Transport IPFS Gateway HTTP code and the same\n * multihash as `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x0920, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\n/**\n * This is a union of all known PeerId types - use the `.type` field to\n * disambiguate them\n */\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId | URLPeerId\n\n/**\n * All PeerId implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id')\n\n/**\n * Returns true if the passed argument is a PeerId implementation\n */\nexport function isPeerId (other?: any): other is PeerId {\n return Boolean(other?.[peerIdSymbol])\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when and attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\nexport default ms;\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Debug {\n (namespace: string): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial<PeerLoggerOptions> = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n", "import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Context {\n offset: number\n}\n\nconst TAG_MASK = parseInt('11111', 2)\nconst LONG_LENGTH_MASK = parseInt('10000000', 2)\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2)\n\ninterface Decoder {\n (buf: Uint8Array, context: Context): any\n}\n\nconst decoders: Record<number, Decoder> = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n}\n\nexport function decodeDer (buf: Uint8Array, context: Context = { offset: 0 }): any {\n const tag = buf[context.offset] & TAG_MASK\n context.offset++\n\n if (decoders[tag] != null) {\n return decoders[tag](buf, context)\n }\n\n throw new Error('No decoder for tag ' + tag)\n}\n\nfunction readLength (buf: Uint8Array, context: Context): number {\n let length = 0\n\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK\n let str = '0x'\n context.offset++\n\n for (let i = 0; i < count; i++, context.offset++) {\n str += buf[context.offset].toString(16).padStart(2, '0')\n }\n\n length = parseInt(str, 16)\n } else {\n length = buf[context.offset]\n context.offset++\n }\n\n return length\n}\n\nfunction readSequence (buf: Uint8Array, context: Context): any[] {\n readLength(buf, context)\n const entries: any[] = []\n\n while (true) {\n if (context.offset >= buf.byteLength) {\n break\n }\n\n const result = decodeDer(buf, context)\n\n if (result === null) {\n break\n }\n\n entries.push(result)\n }\n\n return entries\n}\n\nfunction readInteger (buf: Uint8Array, context: Context): Uint8Array {\n const length = readLength(buf, context)\n const start = context.offset\n const end = context.offset + length\n\n const vals: number[] = []\n\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue\n }\n\n vals.push(buf[i])\n }\n\n context.offset += length\n\n return Uint8Array.from(vals)\n}\n\nfunction readObjectIdentifier (buf: Uint8Array, context: Context): string {\n const count = readLength(buf, context)\n const finalOffset = context.offset + count\n\n const byte = buf[context.offset]\n context.offset++\n\n let val1 = 0\n let val2 = 0\n\n if (byte < 40) {\n val1 = 0\n val2 = byte\n } else if (byte < 80) {\n val1 = 1\n val2 = byte - 40\n } else {\n val1 = 2\n val2 = byte - 80\n }\n\n let oid = `${val1}.${val2}`\n let num: number[] = []\n\n while (context.offset < finalOffset) {\n const byte = buf[context.offset]\n context.offset++\n\n // remove msb\n num.push(byte & 0b01111111)\n\n if (byte < 128) {\n num.reverse()\n\n // reached the end of the encoding\n let val = 0\n\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7)\n }\n\n oid += `.${val}`\n num = []\n }\n }\n\n return oid\n}\n\nfunction readNull (buf: Uint8Array, context: Context): null {\n context.offset++\n\n return null\n}\n\nfunction readBitString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const unusedBits = buf[context.offset]\n context.offset++\n const bytes = buf.subarray(context.offset, context.offset + length - 1)\n context.offset += length\n\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented')\n }\n\n return bytes\n}\n\nfunction readOctetString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const bytes = buf.subarray(context.offset, context.offset + length)\n context.offset += length\n\n return bytes\n}\n\nfunction encodeNumber (value: number): Uint8ArrayList {\n let number = value.toString(16)\n\n if (number.length % 2 === 1) {\n number = '0' + number\n }\n\n const array = new Uint8ArrayList()\n\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]))\n }\n\n return array\n}\n\nfunction encodeLength (bytes: { byteLength: number }): Uint8Array | Uint8ArrayList {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength])\n }\n\n // long length\n const length = encodeNumber(bytes.byteLength)\n\n return new Uint8ArrayList(\n Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]),\n length\n )\n}\n\nexport function encodeInteger (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const contents = new Uint8ArrayList()\n\n const mask = 0b10000000\n const positive = (value.subarray()[0] & mask) === mask\n\n if (positive) {\n contents.append(Uint8Array.from([0]))\n }\n\n contents.append(value)\n\n return new Uint8ArrayList(\n Uint8Array.from([0x02]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeBitString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0])\n\n const contents = new Uint8ArrayList(\n unusedBits,\n value\n )\n\n return new Uint8ArrayList(\n Uint8Array.from([0x03]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeOctetString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n return new Uint8ArrayList(\n Uint8Array.from([0x04]),\n encodeLength(value),\n value\n )\n}\n\nexport function encodeSequence (values: Array<Uint8Array | Uint8ArrayList>, tag = 0x30): Uint8ArrayList {\n const output = new Uint8ArrayList()\n\n for (const buf of values) {\n output.append(\n buf\n )\n }\n\n return new Uint8ArrayList(\n Uint8Array.from([tag]),\n encodeLength(output),\n output\n )\n}\n", "import type { JWKKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport type Curve = 'P-256' | 'P-384' | 'P-521'\n\nexport const ECDSA_P_256_OID = '1.2.840.10045.3.1.7'\nexport const ECDSA_P_384_OID = '1.3.132.0.34'\nexport const ECDSA_P_521_OID = '1.3.132.0.35'\n\nexport async function generateECDSAKey (curve: Curve = 'P-256'): Promise<JWKKeyPair> {\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify'])\n\n return {\n publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),\n privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n }\n}\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n\n return crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from '../rsa/der.js'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass, ECDSAPublicKey as ECDSAPublicKeyClass } from './ecdsa.js'\nimport { generateECDSAKey } from './index.js'\nimport type { Curve } from '../ecdh/index.js'\nimport type { ECDSAPublicKey, ECDSAPrivateKey } from '@libp2p/interface'\n\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07])\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22])\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23])\n\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n}\n\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n}\n\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n}\n\nconst P_256_KEY_LENGTH = 32\nconst P_384_KEY_LENGTH = 48\nconst P_521_KEY_LENGTH = 66\n\nexport function unmarshalECDSAPrivateKey (bytes: Uint8Array): ECDSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPrivateKey(message)\n}\n\nexport function pkiMessageToECDSAPrivateKey (message: any): ECDSAPrivateKey {\n const privateKey = message[1]\n const d = uint8ArrayToString(privateKey, 'base64url')\n const coordinates: Uint8Array = message[2][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`)\n}\n\nexport function unmarshalECDSAPublicKey (bytes: Uint8Array): ECDSAPublicKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPublicKey(message)\n}\n\nexport function pkiMessageToECDSAPublicKey (message: any): ECDSAPublicKey {\n const coordinates = message[1][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`)\n}\n\nexport function privateKeyToPKIMessage (privateKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(uint8ArrayFromString(privateKey.d ?? '', 'base64url')), // body\n encodeSequence([ // PKIProtection\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(privateKey.x ?? '', 'base64url'),\n uint8ArrayFromString(privateKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nexport function publicKeyToPKIMessage (publicKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([ // PKIProtection\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(publicKey.x ?? '', 'base64url'),\n uint8ArrayFromString(publicKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction getOID (curve?: string): Uint8Array {\n if (curve === 'P-256') {\n return OID_256\n }\n\n if (curve === 'P-384') {\n return OID_384\n }\n\n if (curve === 'P-521') {\n return OID_521\n }\n\n throw new InvalidParametersError(`Invalid curve ${curve}`)\n}\n\nexport async function generateECDSAKeyPair (curve: Curve = 'P-256'): Promise<ECDSAPrivateKey> {\n const key = await generateECDSAKey(curve)\n\n return new ECDSAPrivateKeyClass(key.privateKey)\n}\n\nexport function ensureECDSAKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { privateKeyToPKIMessage, publicKeyToPKIMessage } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { ECDSAPublicKey as ECDSAPublicKeyInterface, ECDSAPrivateKey as ECDSAPrivateKeyInterface } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class ECDSAPublicKey implements ECDSAPublicKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = publicKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\n }\n}\n\nexport class ECDSAPrivateKey implements ECDSAPrivateKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n public readonly publicKey: ECDSAPublicKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n this.publicKey = new ECDSAPublicKey({\n crv: jwk.crv,\n ext: jwk.ext,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n })\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = privateKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async sign (message: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\n }\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike<number>) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n =/* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Do expensive precomputation step\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p-1 == q*(2^s) with q odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n let Z = _2n;\n const _Fp = Field(P);\n while (Z < P && FpIsSquare(_Fp, Z)) {\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (!FpIsSquare(Fp, n)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: test on Fp2 and others\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n // (4. If t = 0, return r = 0)\n // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO;\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,\n // otherwise there will be overflow.\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (P + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const c1 = (P - _5n) / _8n;\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n // @ts-ignore\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p)..\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): number {\n const legc = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, legc);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('Cannot find square root: probably non-prime P');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 0 || l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\nimport { Field, FpInvertBatch, mod } from './modular.ts';\n// prettier-ignore\nimport {\n abool, aInRange, bytesToHex, bytesToNumberLE, concatBytes,\n ensureBytes, memoized, numberToBytesLE, validateObject,\n type FHash, type Hex\n} from './utils.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n/** Edwards curves must declare params a & d. */\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\nexport type CurveTypeWithLength = Readonly<CurveType & { nByteLength: number; nBitLength: number }>;\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType): CurveTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n _setWindowSize(windowSize: number): void;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool('phflag', phflag);\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n\n constructor(ex: bigint, ey: bigint, ez: bigint, et: bigint) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez, true);\n aCoordinate('t', et);\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.ez)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n const n = scalar;\n aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.is0() || n === _1n) return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('pointHex.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex): Point {\n const { scalar } = getPrivateScalar(privKey);\n return G.multiply(scalar); // reduced one call of `toRawBytes`\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(bytesToNumberLE(hash));\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n // Convenience method that creates public key from scalar. RFC8032 5.1.5\n function getExtendedPublicKey(key: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(key);\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = bytesToNumberLE(sig.slice(len, 2 * len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point: ExtPointType = Point.BASE): ExtPointType {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { type AffinePoint, type Group, pippenger } from './abstract/curve.ts';\nimport { type CurveFn, type ExtPointType, twistedEdwards } from './abstract/edwards.ts';\nimport {\n createHasher,\n expand_message_xmd,\n type Hasher,\n type htfBasicOpts,\n type HTFMethod,\n} from './abstract/hash-to-curve.ts';\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.ts';\nimport { montgomery, type CurveFn as XCurveFn } from './abstract/montgomery.ts';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n type Hex,\n numberToBytesLE,\n} from './abstract/utils.ts';\n\n// 2n**255n - 19n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n/** Weird / bogus points, useful for debugging. */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Removing Fp.create() will still work, and is 10% faster on sign\n a: Fp.create(BigInt(-1)),\n // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 2n**255n - 19n\n Fp,\n // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n h: _8n,\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\nexport const ed25519_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\n\nfunction aristp(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n private readonly ep: ExtendedPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep: ExtendedPoint) {\n this.ep = ep;\n }\n\n static fromAffine(ap: AffinePoint<bigint>): RistPoint {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n static msm(points: RistPoint[], scalars: bigint[]): RistPoint {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n aristp(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint: typeof RistPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts): RistPoint => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\n/** @deprecated */\nexport const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint =\n hashToRistretto255; // legacy\n", "import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { type Digest } from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey implements Ed25519PublicKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n\n constructor (key: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.publicKeyLength)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this.raw, sig, data)\n }\n}\n\nexport class Ed25519PrivateKey implements Ed25519PrivateKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n public readonly publicKey: Ed25519PublicKey\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.privateKeyLength)\n this.publicKey = new Ed25519PublicKey(publicKey)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this.raw, message)\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Ed25519PublicKey as Ed25519PublicKeyClass, Ed25519PrivateKey as Ed25519PrivateKeyClass } from './ed25519.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey, Ed25519PrivateKey } from '@libp2p/interface'\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureEd25519Key(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKeyClass(bytes)\n}\n\nexport async function generateEd25519KeyPair (): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport async function generateEd25519KeyPairFromSeed (seed: Uint8Array): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport function ensureEd25519Key (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\n\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 1: {\n buf[offset++] = (value & 0xFF)\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 1: {\n buf.set(offset++, (value & 0xFF))\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n secp256k1 = 'secp256k1',\n ECDSA = 'ECDSA'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n secp256k1 = 2,\n ECDSA = 3\n}\n\nexport namespace KeyType {\n export const codec = (): Codec<KeyType> => {\n return enumeration<KeyType>(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec<PublicKey>\n\n export const codec = (): Codec<PublicKey> => {\n if (_codec == null) {\n _codec = message<PublicKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PublicKey>): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey => {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec<PrivateKey>\n\n export const codec = (): Codec<PrivateKey> => {\n if (_codec == null) {\n _codec = message<PrivateKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PrivateKey>): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n}\n", "/**\n * Signing a message failed\n */\nexport class SigningError extends Error {\n constructor (message = 'An error occurred while signing a message') {\n super(message)\n this.name = 'SigningError'\n }\n}\n\n/**\n * Verifying a message signature failed\n */\nexport class VerificationError extends Error {\n constructor (message = 'An error occurred while verifying a message') {\n super(message)\n this.name = 'VerificationError'\n }\n}\n\n/**\n * WebCrypto was not available in the current context\n */\nexport class WebCryptoMissingError extends Error {\n constructor (message = 'Missing Web Crypto API') {\n super(message)\n this.name = 'WebCryptoMissingError'\n }\n}\n", "/* eslint-env browser */\n\nimport { WebCryptoMissingError } from '../errors.js'\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto?.subtle == null) {\n throw new WebCryptoMissingError(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n )\n }\n\n return nativeCrypto\n }\n}\n", "import webcrypto from './webcrypto.js'\n\nexport default webcrypto\n", "import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { create } from 'multiformats/hashes/digest'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as pb from '../keys.js'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.js'\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from './rsa.js'\nimport { generateRSAKey, rsaKeySize } from './index.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { RSAPrivateKey, RSAPublicKey } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport const MAX_RSA_KEY_SIZE = 8192\nconst SHA2_256_CODE = 0x12\nconst MAX_RSA_JWK_SIZE = 1062\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToJwk(message)\n}\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1MessageToJwk (message: any): JsonWebKey {\n return {\n n: uint8ArrayToString(message[1], 'base64url'),\n e: uint8ArrayToString(message[2], 'base64url'),\n d: uint8ArrayToString(message[3], 'base64url'),\n p: uint8ArrayToString(message[4], 'base64url'),\n q: uint8ArrayToString(message[5], 'base64url'),\n dp: uint8ArrayToString(message[6], 'base64url'),\n dq: uint8ArrayToString(message[7], 'base64url'),\n qi: uint8ArrayToString(message[8], 'base64url'),\n kty: 'RSA'\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.d, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.p, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.q, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dp, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dq, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.qi, 'base64url'))\n ]).subarray()\n}\n\n/**\n * Convert a PKIX in ASN1 DER format to a JWK public key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToJwk(message)\n}\n\nexport function pkixMessageToJwk (message: any): JsonWebKey {\n const keys = decodeDer(message[1], {\n offset: 0\n })\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deeply property chains like this\n return {\n kty: 'RSA',\n n: uint8ArrayToString(\n keys[0],\n 'base64url'\n ),\n e: uint8ArrayToString(\n keys[1],\n 'base64url'\n )\n }\n}\n\n/**\n * Convert a JWK public key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url'))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey (bytes: Uint8Array): RSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToRSAPrivateKey(message)\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1MessageToRSAPrivateKey (message: any): RSAPrivateKey {\n const jwk = pkcs1MessageToJwk(message)\n\n return jwkToRSAPrivateKey(jwk)\n}\n\n/**\n * Turn a PKIX message into a PublicKey\n */\nexport function pkixToRSAPublicKey (bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n if (bytes.byteLength >= MAX_RSA_JWK_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large')\n }\n\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToRSAPublicKey(message, bytes, digest)\n}\n\nexport function pkixMessageToRSAPublicKey (message: any, bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n const jwk = pkixMessageToJwk(message)\n\n if (digest == null) {\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }))\n digest = create(SHA2_256_CODE, hash)\n }\n\n return new RSAPublicKeyClass(jwk, digest)\n}\n\nexport function jwkToRSAPrivateKey (jwk: JsonWebKey): RSAPrivateKey {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = jwkToJWKKeyPair(jwk)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\nexport async function generateRSAKeyPair (bits: number): Promise<RSAPrivateKey> {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = await generateRSAKey(bits)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair (key: JsonWebKey): JWKKeyPair {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter')\n }\n\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n }\n}\n", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { type Digest } from 'multiformats/hashes/digest'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { hashAndSign, utils, hashAndVerify } from './index.js'\nimport type { RSAPublicKey as RSAPublicKeyInterface, RSAPrivateKey as RSAPrivateKeyInterface } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class RSAPublicKey implements RSAPublicKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n private readonly _multihash: Digest<18, number>\n\n constructor (jwk: JsonWebKey, digest: Digest<18, number>) {\n this.jwk = jwk\n this._multihash = digest\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<18, number> {\n return this._multihash\n }\n\n toCID (): CID<unknown, 114, 18, 1> {\n return CID.createV1(114, this._multihash)\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\n }\n}\n\nexport class RSAPrivateKey implements RSAPrivateKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n public readonly publicKey: RSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: RSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../../random-bytes.js'\nimport webcrypto from '../../webcrypto/index.js'\nimport * as utils from './utils.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const RSAES_PKCS1_V1_5_OID = '1.2.840.113549.1.1.1'\nexport { utils }\n\nexport async function generateRSAKey (bits: number): Promise<JWKKeyPair> {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nexport function rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)\n * * n: Curve prime subgroup order, total count of valid points in the field\n * * Gx: Base point (x, y) aka generator point x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor,\n pippenger, validateBasic, wNAF\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n type IField, getMinHashLength, invert, mapHashToField, mod, validateField\n} from './modular.ts';\n// prettier-ignore\nimport {\n type CHash, type Hex, type PrivKey,\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\nexport type Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n toAffine(iz?: T): AffinePoint<T>;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n msm(points: ProjPointType<T>[], scalars: bigint[]): ProjPointType<T>;\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula. Takes x, returns y\u00B2.\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (isBytes(key)) key = bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) \u220B (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType<T> {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint<T> {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = bytesToNumberBE(tail);\n if (!inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n const numToNByteHex = (num: bigint): string =>\n bytesToHex(numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteHex(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteHex(this.r) + numToNByteHex(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // Our custom check \"just in case\"\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1\u22C5G - U2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n", "/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: BigInt(0),\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n aInRange('x', x, _1n, secp256k1P); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n } as const\n ))();\n\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise <T = unknown> (thing: any): thing is Promise<T> {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 33\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new SigningError(String(err))\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new VerificationError(String(err))\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new VerificationError(String(err))\n }\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { validateSecp256k1PublicKey, compressSecp256k1PublicKey, computeSecp256k1PublicKey, validateSecp256k1PrivateKey } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { Secp256k1PublicKey as Secp256k1PublicKeyInterface, Secp256k1PrivateKey as Secp256k1PrivateKeyInterface } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey implements Secp256k1PublicKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = validateSecp256k1PublicKey(key)\n this.raw = compressSecp256k1PublicKey(this._key)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return hashAndVerify(this._key, sig, data)\n }\n}\n\nexport class Secp256k1PrivateKey implements Secp256k1PrivateKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this.raw = validateSecp256k1PrivateKey(key)\n this.publicKey = new Secp256k1PublicKey(publicKey ?? computeSecp256k1PublicKey(key))\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { Secp256k1PublicKey as Secp256k1PublicKeyClass, Secp256k1PrivateKey as Secp256k1PrivateKeyClass } from './secp256k1.js'\nimport type { Secp256k1PublicKey, Secp256k1PrivateKey } from '@libp2p/interface'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKeyClass(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKeyClass(bytes)\n}\n\nexport async function generateSecp256k1KeyPair (): Promise<Secp256k1PrivateKey> {\n const privateKeyBytes = generateSecp256k1PrivateKey()\n return new Secp256k1PrivateKeyClass(privateKeyBytes)\n}\n\nexport function compressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validateSecp256k1PrivateKey (key: Uint8Array): Uint8Array {\n try {\n secp.getPublicKey(key, true)\n\n return key\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function validateSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n try {\n secp.ProjectivePoint.fromHex(key)\n\n return key\n } catch (err) {\n throw new InvalidPublicKeyError(String(err))\n }\n}\n\nexport function computeSecp256k1PublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function generateSecp256k1PrivateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n", "/**\n * @packageDocumentation\n *\n * ## Supported Key Types\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass } from './ecdsa/ecdsa.js'\nimport { ECDSA_P_256_OID, ECDSA_P_384_OID, ECDSA_P_521_OID } from './ecdsa/index.js'\nimport { generateECDSAKeyPair, pkiMessageToECDSAPrivateKey, pkiMessageToECDSAPublicKey, unmarshalECDSAPrivateKey, unmarshalECDSAPublicKey } from './ecdsa/utils.js'\nimport { privateKeyLength as ed25519PrivateKeyLength, publicKeyLength as ed25519PublicKeyLength } from './ed25519/index.js'\nimport { generateEd25519KeyPair, generateEd25519KeyPairFromSeed, unmarshalEd25519PrivateKey, unmarshalEd25519PublicKey } from './ed25519/utils.js'\nimport * as pb from './keys.js'\nimport { decodeDer } from './rsa/der.js'\nimport { RSAES_PKCS1_V1_5_OID } from './rsa/index.js'\nimport { pkcs1ToRSAPrivateKey, pkixToRSAPublicKey, generateRSAKeyPair, pkcs1MessageToRSAPrivateKey, pkixMessageToRSAPublicKey, jwkToRSAPrivateKey } from './rsa/utils.js'\nimport { privateKeyLength as secp256k1PrivateKeyLength, publicKeyLength as secp256k1PublicKeyLength } from './secp256k1/index.js'\nimport { generateSecp256k1KeyPair, unmarshalSecp256k1PrivateKey, unmarshalSecp256k1PublicKey } from './secp256k1/utils.js'\nimport type { Curve } from './ecdsa/index.js'\nimport type { PrivateKey, PublicKey, KeyType, RSAPrivateKey, Secp256k1PrivateKey, Ed25519PrivateKey, Secp256k1PublicKey, Ed25519PublicKey, ECDSAPrivateKey, ECDSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport { generateEphemeralKeyPair } from './ecdh/index.js'\nexport type { Curve } from './ecdh/index.js'\nexport type { ECDHKey, EnhancedKey, EnhancedKeyPair, ECDHKeyPair } from './interface.js'\nexport { keyStretcher } from './key-stretcher.js'\n\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair (type: 'Ed25519'): Promise<Ed25519PrivateKey>\nexport async function generateKeyPair (type: 'secp256k1'): Promise<Secp256k1PrivateKey>\nexport async function generateKeyPair (type: 'ECDSA', curve?: Curve): Promise<ECDSAPrivateKey>\nexport async function generateKeyPair (type: 'RSA', bits?: number): Promise<RSAPrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number): Promise<PrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number | string): Promise<unknown> {\n if (type === 'Ed25519') {\n return generateEd25519KeyPair()\n }\n\n if (type === 'secp256k1') {\n return generateSecp256k1KeyPair()\n }\n\n if (type === 'RSA') {\n return generateRSAKeyPair(toBits(bits))\n }\n\n if (type === 'ECDSA') {\n return generateECDSAKeyPair(toCurve(bits))\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\n/**\n * Generates a keypair of the given type from the passed seed. Currently only\n * supports Ed25519 keys.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: 'Ed25519', seed: Uint8Array): Promise<Ed25519PrivateKey>\nexport async function generateKeyPairFromSeed <T extends KeyType> (type: T, seed: Uint8Array, bits?: number): Promise<never>\nexport async function generateKeyPairFromSeed (type: string, seed: Uint8Array): Promise<unknown> {\n if (type !== 'Ed25519') {\n throw new UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys')\n }\n\n return generateEd25519KeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object.\n *\n * For RSA public keys optionally pass the multihash digest of the public key if\n * it is known. If the digest is omitted it will be calculated which can be\n * expensive.\n *\n * For other key types the digest option is ignored.\n */\nexport function publicKeyFromProtobuf (buf: Uint8Array, digest?: Digest<18, number>): PublicKey {\n const { Type, Data } = pb.PublicKey.decode(buf)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.RSA:\n return pkixToRSAPublicKey(data, digest)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a public key from the raw key bytes\n */\nexport function publicKeyFromRaw (buf: Uint8Array): PublicKey {\n if (buf.byteLength === ed25519PublicKeyLength) {\n return unmarshalEd25519PublicKey(buf)\n } else if (buf.byteLength === secp256k1PublicKeyLength) {\n return unmarshalSecp256k1PublicKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[1]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPublicKey(message)\n }\n\n if (message[0]?.[0] === RSAES_PKCS1_V1_5_OID) {\n return pkixMessageToRSAPublicKey(message, buf)\n }\n\n throw new InvalidParametersError('Could not extract public key from raw bytes')\n}\n\n/**\n * Creates a public key from an identity multihash which contains a protobuf\n * encoded Ed25519 or secp256k1 public key.\n *\n * RSA keys are not supported as in practice we they are not stored in identity\n * multihash since the hash would be very large.\n */\nexport function publicKeyFromMultihash (digest: MultihashDigest<0x0>): Ed25519PublicKey | Secp256k1PublicKey | ECDSAPublicKey {\n const { Type, Data } = pb.PublicKey.decode(digest.digest)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function publicKeyToProtobuf (key: PublicKey): Uint8Array {\n return pb.PublicKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport function privateKeyFromProtobuf (buf: Uint8Array): Ed25519PrivateKey | Secp256k1PrivateKey | RSAPrivateKey | ECDSAPrivateKey {\n const decoded = pb.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case pb.KeyType.RSA:\n return pkcs1ToRSAPrivateKey(data)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PrivateKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PrivateKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPrivateKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a private key from the raw key bytes. For Ed25519 keys this requires\n * the public key to be appended to the private key otherwise we can't\n * differentiate between Ed25519 and secp256k1 keys as they are the same length.\n */\nexport function privateKeyFromRaw (buf: Uint8Array): PrivateKey {\n if (buf.byteLength === ed25519PrivateKeyLength) {\n return unmarshalEd25519PrivateKey(buf)\n } else if (buf.byteLength === secp256k1PrivateKeyLength) {\n return unmarshalSecp256k1PrivateKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[2]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPrivateKey(message)\n }\n\n if (message.length > 8) {\n return pkcs1MessageToRSAPrivateKey(message)\n }\n\n throw new InvalidParametersError('Could not extract private key from raw bytes')\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function privateKeyToProtobuf (key: PrivateKey): Uint8Array {\n return pb.PrivateKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\nfunction toBits (bits: any): number {\n if (bits == null) {\n return 2048\n }\n\n return parseInt(bits, 10)\n}\n\nfunction toCurve (curve: any): Curve {\n if (curve === 'P-256' || curve == null) {\n return 'P-256'\n }\n\n if (curve === 'P-384') {\n return 'P-384'\n }\n\n if (curve === 'P-521') {\n return 'P-521'\n }\n\n throw new InvalidParametersError('Unsupported curve, should be P-256, P-384 or P-521')\n}\n\n/**\n * Convert a libp2p RSA or ECDSA private key to a WebCrypto CryptoKeyPair\n */\nexport async function privateKeyToCryptoKeyPair (privateKey: PrivateKey): Promise<CryptoKeyPair> {\n if (privateKey.type === 'RSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify'])\n }\n }\n\n if (privateKey.type === 'ECDSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.jwk.crv ?? 'P-256'\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.publicKey.jwk.crv ?? 'P-256'\n }, true, ['verify'])\n }\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n\n/**\n * Convert a RSA or ECDSA WebCrypto CryptoKeyPair to a libp2p private key\n */\nexport async function privateKeyFromCryptoKeyPair (keyPair: CryptoKeyPair): Promise<PrivateKey> {\n if (keyPair.privateKey.algorithm.name === 'RSASSA-PKCS1-v1_5') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return jwkToRSAPrivateKey(jwk)\n }\n\n if (keyPair.privateKey.algorithm.name === 'ECDSA') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return new ECDSAPrivateKeyClass(jwk)\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { peerIdSymbol } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Ed25519PeerId as Ed25519PeerIdInterface, PeerIdType, RSAPeerId as RSAPeerIdInterface, URLPeerId as URLPeerIdInterface, Secp256k1PeerId as Secp256k1PeerIdInterface, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\ninterface PeerIdInit <DigestCode extends number> {\n type: PeerIdType\n multihash: MultihashDigest<DigestCode>\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest<0x12>\n publicKey?: RSAPublicKey\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Ed25519PublicKey\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Secp256k1PublicKey\n}\n\nclass PeerIdImpl <DigestCode extends number> {\n public type: PeerIdType\n private readonly multihash: MultihashDigest<DigestCode>\n public readonly publicKey?: PublicKey\n private string?: string\n\n constructor (init: PeerIdInit<DigestCode>) {\n this.type = init.type\n this.multihash = init.multihash\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n toMultihash (): MultihashDigest<DigestCode> {\n return this.multihash\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID<Uint8Array, 0x72, DigestCode, 1> {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return this.toString() === id\n } else if (id?.toMultihash()?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.toMultihash().bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nexport class RSAPeerId extends PeerIdImpl<0x12> implements RSAPeerIdInterface {\n public readonly type = 'RSA'\n public readonly publicKey?: RSAPublicKey\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Ed25519PeerId extends PeerIdImpl<0x0> implements Ed25519PeerIdInterface {\n public readonly type = 'Ed25519'\n public readonly publicKey: Ed25519PublicKey\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Secp256k1PeerId extends PeerIdImpl<0x0> implements Secp256k1PeerIdInterface {\n public readonly type = 'secp256k1'\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.publicKey\n }\n}\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport class URLPeerId implements URLPeerIdInterface {\n readonly type = 'url'\n readonly multihash: MultihashDigest<0x0>\n readonly publicKey: undefined\n readonly url: string\n\n constructor (url: URL) {\n this.url = url.toString()\n this.multihash = identity.digest(uint8ArrayFromString(this.url))\n }\n\n [inspect] (): string {\n return `PeerId(${this.url})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n return this.toCID().toString()\n }\n\n toMultihash (): MultihashDigest<0x0> {\n return this.multihash\n }\n\n toCID (): CID<Uint8Array, 0x0920, 0x0, 1> {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash())\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n equals (other?: PeerId | Uint8Array | string): boolean {\n if (other == null) {\n return false\n }\n\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other)\n }\n\n return other.toString() === this.toString()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { publicKeyFromMultihash } from '@libp2p/crypto/keys'\nimport { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID, type MultibaseDecoder } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RSAPeerId as RSAPeerIdClass, Ed25519PeerId as Ed25519PeerIdClass, Secp256k1PeerId as Secp256k1PeerIdClass, URLPeerId as URLPeerIdClass } from './peer-id.js'\nimport type { Ed25519PeerId, RSAPeerId, URLPeerId, Secp256k1PeerId, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey, Ed25519PrivateKey, Secp256k1PrivateKey, RSAPrivateKey, PrivateKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n let multihash: MultihashDigest\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n multihash = Digest.decode(base58btc.decode(`z${str}`))\n } else if (str.startsWith('k51qzi5uqu5') || str.startsWith('kzwfwjn5ji4') || str.startsWith('k2k4r8') || str.startsWith('bafz')) {\n // base36 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) or base32 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa)\n return peerIdFromCID(CID.parse(str))\n } else {\n if (decoder == null) {\n throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with \"1\" or \"Q\"')\n }\n\n multihash = Digest.decode(decoder.decode(str))\n }\n\n return peerIdFromMultihash(multihash)\n}\n\nexport function peerIdFromPublicKey (publicKey: Ed25519PublicKey): Ed25519PeerId\nexport function peerIdFromPublicKey (publicKey: Secp256k1PublicKey): Secp256k1PeerId\nexport function peerIdFromPublicKey (publicKey: RSAPublicKey): RSAPeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId {\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'RSA') {\n return new RSAPeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\nexport function peerIdFromPrivateKey (privateKey: Ed25519PrivateKey): Ed25519PeerId\nexport function peerIdFromPrivateKey (privateKey: Secp256k1PrivateKey): Secp256k1PeerId\nexport function peerIdFromPrivateKey (privateKey: RSAPrivateKey): RSAPeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId {\n return peerIdFromPublicKey(privateKey.publicKey)\n}\n\nexport function peerIdFromMultihash (multihash: MultihashDigest): PeerId {\n if (isSha256Multihash(multihash)) {\n return new RSAPeerIdClass({ multihash })\n } else if (isIdentityMultihash(multihash)) {\n try {\n const publicKey = publicKeyFromMultihash(multihash)\n\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({ multihash, publicKey })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({ multihash, publicKey })\n }\n } catch (err) {\n // was not Ed or secp key, try URL\n const url = uint8ArrayToString(multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n }\n\n throw new InvalidMultihashError('Supplied PeerID Multihash is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new InvalidCIDError('Supplied PeerID CID is invalid')\n }\n\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n\n return peerIdFromMultihash(cid.multihash)\n}\n\nfunction isIdentityMultihash (multihash: MultihashDigest): multihash is MultihashDigest<0x0> {\n return multihash.code === identity.code\n}\n\nfunction isSha256Multihash (multihash: MultihashDigest): multihash is MultihashDigest<0x12> {\n return multihash.code === sha256.code\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array<string>} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array<string>}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array<string>}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array<Key>} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array<any>} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "import { publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { logger } from '@libp2p/logger'\nimport { type Key } from 'interface-datastore/key'\nimport NanoDate from 'timestamp-nano'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { SignatureCreationError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { createCborData, ipnsRecordDataForV1Sig, ipnsRecordDataForV2Sig, normalizeValue } from './utils.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst log = logger('ipns')\nconst DEFAULT_TTL_NS = 5 * 60 * 1e+9 // 5 Minutes or 300 Seconds, as suggested by https://specs.ipfs.tech/ipns/ipns-record/#ttl-uint64\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSRecordV1V2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * signature of the record\n */\n signatureV1: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * expiration datetime for the record in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport interface IPNSRecordV2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * If the validity type is EOL, this is the expiration datetime for the record\n * in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport type IPNSRecord = IPNSRecordV1V2 | IPNSRecordV2\n\nexport interface IPNSRecordData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\nexport interface CreateOptions {\n ttlNs?: number | bigint\n v1Compatible?: boolean\n}\n\nexport interface CreateV2OrV1Options {\n v1Compatible: true\n}\n\nexport interface CreateV2Options {\n v1Compatible: false\n}\n\nconst defaultCreateOptions: CreateOptions = {\n v1Compatible: true,\n ttlNs: DEFAULT_TTL_NS\n}\n\n/**\n * Creates a new IPNS record and signs it with the given private key.\n * The IPNS Record validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n * @param {CreateOptions} options - additional create options.\n */\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * @param {CreateOptions} options - additional creation options.\n */\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\nconst _create = async (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, validityType: IpnsEntry.ValidityType, validity: string, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(validity)\n const normalizedValue = normalizeValue(value)\n const encodedValue = uint8ArrayFromString(normalizedValue)\n const data = createCborData(encodedValue, validityType, isoValidity, seq, ttl)\n const sigData = ipnsRecordDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData)\n let pubKey: Uint8Array | undefined\n\n // if we cannot derive the public key from the PeerId (e.g. RSA PeerIDs),\n // we have to embed it in the IPNS record\n if (privateKey.type === 'RSA') {\n pubKey = publicKeyToProtobuf(privateKey.publicKey)\n }\n\n if (options.v1Compatible === true) {\n const signatureV1 = await signLegacyV1(privateKey, encodedValue, validityType, isoValidity)\n\n const record: IPNSRecord = {\n value: normalizedValue,\n signatureV1,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n } else {\n const record: IPNSRecordV2 = {\n value: normalizedValue,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n }\n}\n\nexport { unmarshalIPNSRecord } from './utils.js'\nexport { marshalIPNSRecord } from './utils.js'\nexport { multihashToIPNSRoutingKey } from './utils.js'\nexport { multihashFromIPNSRoutingKey } from './utils.js'\nexport { extractPublicKeyFromIPNSRecord } from './utils.js'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Promise<Uint8Array> => {\n try {\n const dataForSignature = ipnsRecordDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw new SignatureCreationError('Record signature creation failed')\n }\n}\n", "export class SignatureCreationError extends Error {\n static name = 'SignatureCreationError'\n\n constructor (message = 'Record signature creation failed') {\n super(message)\n this.name = 'SignatureCreationError'\n }\n}\n\nexport class SignatureVerificationError extends Error {\n static name = 'SignatureVerificationError'\n\n constructor (message = 'Record signature verification failed') {\n super(message)\n this.name = 'SignatureVerificationError'\n }\n}\n\nexport class RecordExpiredError extends Error {\n static name = 'RecordExpiredError'\n\n constructor (message = 'Record has expired') {\n super(message)\n this.name = 'RecordExpiredError'\n }\n}\n\nexport class UnsupportedValidityError extends Error {\n static name = 'UnsupportedValidityError'\n\n constructor (message = 'The validity type is unsupported') {\n super(message)\n this.name = 'UnsupportedValidityError'\n }\n}\n\nexport class RecordTooLargeError extends Error {\n static name = 'RecordTooLargeError'\n\n constructor (message = 'The record is too large') {\n super(message)\n this.name = 'RecordTooLargeError'\n }\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n\n constructor (message = 'Value must be a valid content path starting with /') {\n super(message)\n this.name = 'InvalidValueError'\n }\n}\n\nexport class InvalidRecordDataError extends Error {\n static name = 'InvalidRecordDataError'\n\n constructor (message = 'Invalid record data') {\n super(message)\n this.name = 'InvalidRecordDataError'\n }\n}\n\nexport class InvalidEmbeddedPublicKeyError extends Error {\n static name = 'InvalidEmbeddedPublicKeyError'\n\n constructor (message = 'Invalid embedded public key') {\n super(message)\n this.name = 'InvalidEmbeddedPublicKeyError'\n }\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface IpnsEntry {\n value?: Uint8Array\n signatureV1?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n pubKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec<ValidityType> => {\n return enumeration<ValidityType>(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec<IpnsEntry>\n\n export const codec = (): Codec<IpnsEntry> => {\n if (_codec == null) {\n _codec = message<IpnsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signatureV1 != null) {\n w.uint32(18)\n w.bytes(obj.signatureV1)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.pubKey != null) {\n w.uint32(58)\n w.bytes(obj.pubKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.value = reader.bytes()\n break\n }\n case 2: {\n obj.signatureV1 = reader.bytes()\n break\n }\n case 3: {\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n }\n case 4: {\n obj.validity = reader.bytes()\n break\n }\n case 5: {\n obj.sequence = reader.uint64()\n break\n }\n case 6: {\n obj.ttl = reader.uint64()\n break\n }\n case 7: {\n obj.pubKey = reader.bytes()\n break\n }\n case 8: {\n obj.signatureV2 = reader.bytes()\n break\n }\n case 9: {\n obj.data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<IpnsEntry>): Uint8Array => {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): IpnsEntry => {\n return decodeMessage(buf, IpnsEntry.codec(), opts)\n }\n}\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[offset + 1]\n if ((secondByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0x1f) << 0x6 | (secondByte & 0x3f)\n if (tempCodePoint > 0x7f) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 3]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0x12 | (secondByte & 0x3f) << 0xc | (thirdByte & 0x3f) << 0x6 | (fourthByte & 0x3f)\n if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n /* c8 ignore next 5 */\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xfffd\n bytesPerSequence = 1\n } else if (codePoint > 0xffff) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n res.push(codePoint)\n offset += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n /* c8 ignore next 10 */\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidMultihashError } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport * as cborg from 'cborg'\nimport { base36 } from 'multiformats/bases/base36'\nimport { CID, type MultihashDigest } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidRecordDataError, InvalidValueError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport type { IPNSRecord, IPNSRecordV2, IPNSRecordData } from './index.js'\nimport type { PublicKey } from '@libp2p/interface'\n\nconst log = logger('ipns:utils')\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nconst LIBP2P_CID_CODEC = 0x72\nconst IDENTITY_CODEC = 0x0\nconst SHA2_256_CODEC = 0x12\n\n/**\n * Extracts a public key from the passed PeerId, falling back to the pubKey\n * embedded in the ipns record\n */\nexport function extractPublicKeyFromIPNSRecord (record: IPNSRecord | IPNSRecordV2): PublicKey | undefined {\n let pubKey: PublicKey | undefined\n\n if (record.pubKey != null) {\n try {\n pubKey = publicKeyFromProtobuf(record.pubKey)\n } catch (err) {\n log.error(err)\n throw err\n }\n }\n\n if (pubKey != null) {\n return pubKey\n }\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV1Sig (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n\n return uint8ArrayConcat([value, validity, validityTypeBuffer])\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV2Sig (data: Uint8Array): Uint8Array {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport function marshalIPNSRecord (obj: IPNSRecord | IPNSRecordV2): Uint8Array {\n if ('signatureV1' in obj) {\n return IpnsEntry.encode({\n value: uint8ArrayFromString(obj.value),\n signatureV1: obj.signatureV1,\n validityType: obj.validityType,\n validity: uint8ArrayFromString(obj.validity),\n sequence: obj.sequence,\n ttl: obj.ttl,\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n } else {\n return IpnsEntry.encode({\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n }\n}\n\nexport function unmarshalIPNSRecord (buf: Uint8Array): IPNSRecord {\n const message = IpnsEntry.decode(buf)\n\n // protobufjs returns bigints as numbers\n if (message.sequence != null) {\n message.sequence = BigInt(message.sequence)\n }\n\n // protobufjs returns bigints as numbers\n if (message.ttl != null) {\n message.ttl = BigInt(message.ttl)\n }\n\n // Check if we have the data field. If we don't, we fail. We've been producing\n // V1+V2 records for quite a while and we don't support V1-only records during\n // validation any more\n if (message.signatureV2 == null || message.data == null) {\n throw new SignatureVerificationError('Missing data or signatureV2')\n }\n\n const data = parseCborData(message.data)\n const value = normalizeByteValue(data.Value)\n const validity = uint8ArrayToString(data.Validity)\n\n if (message.value != null && message.signatureV1 != null) {\n // V1+V2\n validateCborDataMatchesPbData(message)\n\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV1: message.signatureV1,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else if (message.signatureV2 != null) {\n // V2-only\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else {\n throw new Error('invalid record: does not include signatureV1 or signatureV2')\n }\n}\n\nexport function multihashToIPNSRoutingKey (digest: MultihashDigest<0x00 | 0x12>): Uint8Array {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n digest.bytes\n ])\n}\n\nexport function multihashFromIPNSRoutingKey (key: Uint8Array): MultihashDigest<0x00 | 0x12> {\n const digest = Digest.decode(key.slice(IPNS_PREFIX.length))\n\n if (!isCodec(digest, IDENTITY_CODEC) && !isCodec(digest, SHA2_256_CODEC)) {\n throw new InvalidMultihashError('Multihash in IPNS key was not identity or sha2-256')\n }\n\n return digest\n}\n\nexport function createCborData (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array, sequence: bigint, ttl: bigint): Uint8Array {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n const data = {\n Value: value,\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport function parseCborData (buf: Uint8Array): IPNSRecordData {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n\nexport function normalizeByteValue (value: Uint8Array): string {\n const string = uint8ArrayToString(value).trim()\n\n // if we have a path, check it is a valid path\n if (string.startsWith('/')) {\n return string\n }\n\n // try parsing what we have as CID bytes or a CID string\n try {\n return `/ipfs/${CID.decode(value).toV1().toString()}`\n } catch {\n // fall through\n }\n\n try {\n return `/ipfs/${CID.parse(string).toV1().toString()}`\n } catch {\n // fall through\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\n/**\n * Normalizes the given record value. It ensures it is a PeerID, a CID or a\n * string starting with '/'. PeerIDs become `/ipns/${cidV1Libp2pKey}`,\n * CIDs become `/ipfs/${cidAsV1}`.\n */\nexport function normalizeValue (value?: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string): string {\n if (value != null) {\n const cid = asCID(value)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code === LIBP2P_CID_CODEC) {\n return `/ipns/${cid.toString(base36)}`\n }\n\n return `/ipfs/${cid.toV1().toString()}`\n }\n\n if (hasBytes(value)) {\n return `/ipns/${base36.encode(value.bytes)}`\n }\n\n // if we have a path, check it is a valid path\n const string = value.toString().trim()\n\n if (string.startsWith('/') && string.length > 1) {\n return string\n }\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\nfunction validateCborDataMatchesPbData (entry: IpnsEntry): void {\n if (entry.data == null) {\n throw new InvalidRecordDataError('Record data is missing')\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"value\" did not match between protobuf and CBOR')\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"validity\" did not match between protobuf and CBOR')\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw new SignatureVerificationError('Field \"validityType\" did not match between protobuf and CBOR')\n }\n\n if (data.Sequence !== entry.sequence) {\n throw new SignatureVerificationError('Field \"sequence\" did not match between protobuf and CBOR')\n }\n\n if (data.TTL !== entry.ttl) {\n throw new SignatureVerificationError('Field \"ttl\" did not match between protobuf and CBOR')\n }\n}\n\nfunction hasBytes (obj?: any): obj is { bytes: Uint8Array } {\n return obj.bytes instanceof Uint8Array\n}\n\nfunction hasToCID (obj?: any): obj is { toCID(): CID } {\n return typeof obj?.toCID === 'function'\n}\n\nfunction asCID (obj?: any): CID | null {\n if (hasToCID(obj)) {\n return obj.toCID()\n }\n\n // try parsing as a CID string\n try {\n return CID.parse(obj)\n } catch {\n // fall through\n }\n\n return CID.asCID(obj)\n}\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n", "import NanoDate from 'timestamp-nano'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { unmarshalIPNSRecord } from './utils.js'\n\n/**\n * Selects the latest valid IPNS record from an array of marshalled IPNS records.\n *\n * Records are sorted by:\n * 1. Sequence number (higher takes precedence)\n * 2. Validity time for EOL records with same sequence number (longer lived record takes precedence)\n *\n * @param key - The routing key for the IPNS record\n * @param data - Array of marshalled IPNS records to select from\n * @returns The index of the most valid record from the input array\n */\nexport function ipnsSelector (key: Uint8Array, data: Uint8Array[]): number {\n const entries = data.map((buf, index) => ({\n record: unmarshalIPNSRecord(buf),\n index\n }))\n\n entries.sort((a, b) => {\n // Before we'd sort based on the signature version. Unmarshal now fails if\n // a record does not have SignatureV2, so that is no longer needed. V1-only\n // records haven't been issues in a long time.\n\n const aSeq = a.record.sequence\n const bSeq = b.record.sequence\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n if (a.record.validityType === IpnsEntry.ValidityType.EOL && b.record.validityType === IpnsEntry.ValidityType.EOL) {\n // choose longer lived record if sequence numbers the same\n const recordAValidityDate = NanoDate.fromString(a.record.validity).toDate()\n const recordBValidityDate = NanoDate.fromString(b.record.validity).toDate()\n\n if (recordAValidityDate.getTime() > recordBValidityDate.getTime()) {\n return -1\n }\n\n if (recordAValidityDate.getTime() < recordBValidityDate.getTime()) {\n return 1\n }\n }\n\n return 0\n })\n\n return entries[0].index\n}\n", "import { publicKeyFromMultihash } from '@libp2p/crypto/keys'\nimport { logger } from '@libp2p/logger'\nimport NanoDate from 'timestamp-nano'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { InvalidEmbeddedPublicKeyError, RecordExpiredError, RecordTooLargeError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { extractPublicKeyFromIPNSRecord, ipnsRecordDataForV2Sig, isCodec, multihashFromIPNSRoutingKey, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from './utils.js'\nimport type { PublicKey } from '@libp2p/interface'\n\nconst log = logger('ipns:validator')\n\n/**\n * Limit valid IPNS record sizes to 10kb\n */\nconst MAX_RECORD_SIZE = 1024 * 10\n\n/**\n * Validates the given IPNS Record against the given public key. We need a \"raw\"\n * record in order to be able to access to all of its fields.\n */\nexport const validate = async (publicKey: PublicKey, marshalledRecord: Uint8Array): Promise<void> => {\n // unmarshal ensures that (1) SignatureV2 and Data are present, (2) that ValidityType\n // and Validity are of valid types and have a value, (3) that CBOR data matches protobuf\n // if it's a V1+V2 record.\n const record = unmarshalIPNSRecord(marshalledRecord)\n\n // Validate Signature V2\n let isValid\n\n try {\n const dataForSignature = ipnsRecordDataForV2Sig(record.data)\n isValid = await publicKey.verify(dataForSignature, record.signatureV2)\n } catch (err) {\n isValid = false\n }\n\n if (!isValid) {\n log.error('record signature verification failed')\n throw new SignatureVerificationError('Record signature verification failed')\n }\n\n // Validate according to the validity type\n if (record.validityType === IpnsEntry.ValidityType.EOL) {\n if (NanoDate.fromString(record.validity).toDate().getTime() < Date.now()) {\n log.error('record has expired')\n throw new RecordExpiredError('record has expired')\n }\n } else if (record.validityType != null) {\n log.error('the validity type is unsupported')\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n log('ipns record for %s is valid', record.value)\n}\n\n/**\n * Validate the given IPNS record against the given routing key.\n *\n * @see https://specs.ipfs.tech/ipns/ipns-record/#routing-record for the binary format of the routing key\n *\n * @param routingKey - The routing key in binary format: binary(ascii(IPNS_PREFIX) + multihash(public key))\n * @param marshalledRecord - The marshalled record to validate.\n */\nexport async function ipnsValidator (routingKey: Uint8Array, marshalledRecord: Uint8Array): Promise<void> {\n if (marshalledRecord.byteLength > MAX_RECORD_SIZE) {\n throw new RecordTooLargeError('The record is too large')\n }\n\n // try to extract public key from routing key\n const routingMultihash = multihashFromIPNSRoutingKey(routingKey)\n let routingPubKey: PublicKey | undefined\n\n // identity hash\n if (isCodec(routingMultihash, 0x0)) {\n routingPubKey = publicKeyFromMultihash(routingMultihash)\n }\n\n // extract public key from record\n const receivedRecord = unmarshalIPNSRecord(marshalledRecord)\n const recordPubKey = extractPublicKeyFromIPNSRecord(receivedRecord) ?? routingPubKey\n\n if (recordPubKey == null) {\n throw new InvalidEmbeddedPublicKeyError('Could not extract public key from IPNS record or routing key')\n }\n\n const expectedRoutingKey = multihashToIPNSRoutingKey(recordPubKey.toMultihash())\n\n if (!uint8ArrayEquals(expectedRoutingKey, routingKey)) {\n throw new InvalidEmbeddedPublicKeyError('Embedded public key did not match routing key')\n }\n\n // Record validation\n await validate(recordPubKey, marshalledRecord)\n}\n", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: (evt: Event) => void\n}\n", "import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: ReturnType<typeof hashlru>\n\n constructor (maxSize: number) {\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n", "/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions<ResolveDnsProgressEvents> {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise<DNSResponse>\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record<string, DNSResolver | DNSResolver[]>\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n", "export class DNSLinkNotFoundError extends Error {\n static name = 'DNSLinkNotFoundError'\n\n constructor (message = 'DNSLink not found') {\n super(message)\n this.name = 'DNSLinkNotFoundError'\n }\n}\n\nexport class RecordsFailedValidationError extends Error {\n static name = 'RecordsFailedValidationError'\n\n constructor (message = 'Records failed validation') {\n super(message)\n this.name = 'RecordsFailedValidationError'\n }\n}\n\nexport class UnsupportedMultibasePrefixError extends Error {\n static name = 'UnsupportedMultibasePrefixError'\n\n constructor (message = 'Unsupported multibase prefix') {\n super(message)\n this.name = 'UnsupportedMultibasePrefixError'\n }\n}\n\nexport class UnsupportedMultihashCodecError extends Error {\n static name = 'UnsupportedMultihashCodecError'\n\n constructor (message = 'Unsupported multihash codec') {\n super(message)\n this.name = 'UnsupportedMultihashCodecError'\n }\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n\n constructor (message = 'Invalid value') {\n super(message)\n this.name = 'InvalidValueError'\n }\n}\n\nexport class InvalidTopicError extends Error {\n static name = 'InvalidTopicError'\n\n constructor (message = 'Invalid topic') {\n super(message)\n this.name = 'InvalidTopicError'\n }\n}\n", "import { } from '@libp2p/interface'\nimport { peerIdFromCID, peerIdFromString } from '@libp2p/peer-id'\nimport { RecordType } from '@multiformats/dns'\nimport { CID } from 'multiformats/cid'\nimport { DNSLinkNotFoundError } from './errors.js'\nimport type { ResolveDNSLinkOptions } from './index.js'\nimport type { Logger, PeerId } from '@libp2p/interface'\nimport type { Answer, DNS } from '@multiformats/dns'\n\nconst MAX_RECURSIVE_DEPTH = 32\n\nexport interface DNSLinkResult {\n answer: Answer\n value: string\n}\n\nasync function recursiveResolveDnslink (domain: string, depth: number, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n if (depth === 0) {\n throw new Error('recursion limit exceeded')\n }\n\n log('query %s for TXT and CNAME records', domain)\n const txtRecordsResponse = await dns.query(domain, {\n ...options,\n types: [\n RecordType.TXT\n ]\n })\n\n // sort the TXT records to ensure deterministic processing\n const txtRecords = (txtRecordsResponse?.Answer ?? [])\n .sort((a, b) => a.data.localeCompare(b.data))\n\n log('found %d TXT records for %s', txtRecords.length, domain)\n\n for (const answer of txtRecords) {\n try {\n let result = answer.data\n\n // strip leading and trailing \" characters\n if (result.startsWith('\"') && result.endsWith('\"')) {\n result = result.substring(1, result.length - 1)\n }\n\n if (!result.startsWith('dnslink=')) {\n // invalid record?\n continue\n }\n\n log('%s TXT %s', answer.name, result)\n\n result = result.replace('dnslink=', '')\n\n // result is now a `/ipfs/<cid>` or `/ipns/<cid>` string\n const [, protocol, domainOrCID, ...rest] = result.split('/') // e.g. [\"\", \"ipfs\", \"<cid>\"]\n\n if (protocol === 'ipfs') {\n try {\n const cid = CID.parse(domainOrCID)\n\n // if the result is a CID, we've reached the end of the recursion\n return {\n value: `/ipfs/${cid}${rest.length > 0 ? `/${rest.join('/')}` : ''}`,\n answer\n }\n } catch {}\n } else if (protocol === 'ipns') {\n try {\n let peerId: PeerId\n\n // eslint-disable-next-line max-depth\n if (domainOrCID.charAt(0) === '1' || domainOrCID.charAt(0) === 'Q') {\n peerId = peerIdFromString(domainOrCID)\n } else {\n // try parsing as a CID\n peerId = peerIdFromCID(CID.parse(domainOrCID))\n }\n\n // if the result is a PeerId, we've reached the end of the recursion\n return {\n value: `/ipns/${peerId}${rest.length > 0 ? `/${rest.join('/')}` : ''}`,\n answer\n }\n } catch {}\n\n // if the result was another IPNS domain, try to follow it\n return await recursiveResolveDomain(domainOrCID, depth - 1, dns, log, options)\n } else if (protocol === 'dnslink') {\n // if the result was another DNSLink domain, try to follow it\n return await recursiveResolveDomain(domainOrCID, depth - 1, dns, log, options)\n } else {\n log('unknown protocol \"%s\" in DNSLink record for domain: %s', protocol, domain)\n continue\n }\n } catch (err: any) {\n log.error('could not parse DNS link record for domain %s, %s', domain, answer.data, err)\n }\n }\n\n // no dnslink records found, try CNAMEs\n log('no DNSLink records found for %s, falling back to CNAME', domain)\n\n const cnameRecordsResponse = await dns.query(domain, {\n ...options,\n types: [\n RecordType.CNAME\n ]\n })\n\n // sort the CNAME records to ensure deterministic processing\n const cnameRecords = (cnameRecordsResponse?.Answer ?? [])\n .sort((a, b) => a.data.localeCompare(b.data))\n\n log('found %d CNAME records for %s', cnameRecords.length, domain)\n\n for (const cname of cnameRecords) {\n try {\n return await recursiveResolveDomain(cname.data, depth - 1, dns, log, options)\n } catch (err: any) {\n log.error('domain %s cname %s had no DNSLink records', domain, cname.data, err)\n }\n }\n\n throw new DNSLinkNotFoundError(`No DNSLink records found for domain: ${domain}`)\n}\n\nasync function recursiveResolveDomain (domain: string, depth: number, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n if (depth === 0) {\n throw new Error('recursion limit exceeded')\n }\n\n // the DNSLink spec says records MUST be stored on the `_dnslink.` subdomain\n // so start looking for records there, we will fall back to the bare domain\n // if none are found\n if (!domain.startsWith('_dnslink.')) {\n domain = `_dnslink.${domain}`\n }\n\n try {\n return await recursiveResolveDnslink(domain, depth, dns, log, options)\n } catch (err: any) {\n // If the code is not ENOTFOUND or ERR_DNSLINK_NOT_FOUND or ENODATA then throw the error\n if (err.code !== 'ENOTFOUND' && err.code !== 'ENODATA' && err.name !== 'DNSLinkNotFoundError' && err.name !== 'NotFoundError') {\n throw err\n }\n\n if (domain.startsWith('_dnslink.')) {\n // The supplied domain contains a _dnslink component\n // Check the non-_dnslink domain\n domain = domain.replace('_dnslink.', '')\n } else {\n // Check the _dnslink subdomain\n domain = `_dnslink.${domain}`\n }\n\n // If this throws then we propagate the error\n return recursiveResolveDnslink(domain, depth, dns, log, options)\n }\n}\n\nexport async function resolveDNSLink (domain: string, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n return recursiveResolveDomain(domain, options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH, dns, log, options)\n}\n", "import { CustomProgressEvent, type ProgressEvent } from 'progress-events'\nimport type { GetOptions, PutOptions } from './index.js'\nimport type { IPNSRouting } from '../index.js'\nimport type { Routing } from '@helia/interface'\n\nexport interface HeliaRoutingComponents {\n routing: Routing\n}\n\nexport type HeliaRoutingProgressEvents =\n ProgressEvent<'ipns:routing:helia:error', Error>\n\nexport class HeliaRouting implements IPNSRouting {\n private readonly routing: Routing\n\n constructor (routing: Routing) {\n this.routing = routing\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options: PutOptions = {}): Promise<void> {\n try {\n await this.routing.put(routingKey, marshaledRecord, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<Uint8Array> {\n try {\n return await this.routing.get(routingKey, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n}\n\n/**\n * The helia routing uses any available Routers configured on the passed Helia\n * node. This could be libp2p, HTTP API Delegated Routing, etc.\n */\nexport function helia (routing: Routing): IPNSRouting {\n return new HeliaRouting(routing)\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec<Record>\n\n export const codec = (): Codec<Record> => {\n if (_codec == null) {\n _codec = message<Record>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: uint8ArrayAlloc(0),\n value: uint8ArrayAlloc(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.bytes()\n break\n }\n case 2: {\n obj.value = reader.bytes()\n break\n }\n case 5: {\n obj.timeReceived = reader.string()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Record>): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Record => {\n return decodeMessage(buf, Record.codec(), opts)\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "/**\n * @packageDocumentation\n *\n * This is an implementation of the [routing record format](https://github.com/libp2p/specs/blob/b9efe152c29f93f7a87931c14d78ae11e7924d5a/kad-dht/README.md?plain=1#L408-L425) used by libp2p to store data in the datastore passed to the libp2p constructor.\n *\n * @example Deserialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const buf = Uint8Array.from([0, 1, 2, 3])\n * const record = Libp2pRecord.deserialize(buf)\n * ```\n *\n * @example Serialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const key = Uint8Array.from([0, 1, 2, 3])\n * const value = Uint8Array.from([0, 1, 2, 3])\n * const timeReceived = new Date()\n *\n * const record = new Libp2pRecord(key, value, timeReceived)\n * const buf = record.serialize()\n * ```\n */\n\nimport {\n Record\n} from './record.js'\nimport * as utils from './utils.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const receivedTime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, receivedTime\n )\n\n return rec\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module implements the [libp2p Kademlia spec](https://github.com/libp2p/specs/blob/master/kad-dht/README.md) in TypeScript.\n *\n * The Kademlia DHT allow for several operations such as finding peers, searching for providers of DHT records, etc.\n *\n * @example Using with libp2p\n *\n * ```TypeScript\n * import { kadDHT } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const node = await createLibp2p({\n * services: {\n * dht: kadDHT({\n * // DHT options\n * })\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to the IPFS Amino DHT\n *\n * The [Amino DHT](https://blog.ipfs.tech/2023-09-amino-refactoring/) is a public-good DHT used by IPFS to fetch content, find peers, etc.\n *\n * If you are trying to access content on the public internet, this is the implementation you want.\n *\n * ```TypeScript\n * import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const node = await createLibp2p({\n * services: {\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper\n * })\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to a LAN-only DHT\n *\n * This DHT only works with privately dialable peers.\n *\n * This is for use when peers are on the local area network.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false\n * })\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to both a LAN-only DHT and the IPFS Amino DHT\n *\n * When using multiple DHTs, you should specify distinct datastore, metrics and\n * log prefixes to ensure that data is kept separate for each instance.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false,\n * logPrefix: 'libp2p:dht-lan',\n * datastorePrefix: '/dht-lan',\n * metricsPrefix: 'libp2p_dht_lan'\n * }),\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper,\n * logPrefix: 'libp2p:dht-amino',\n * datastorePrefix: '/dht-amino',\n * metricsPrefix: 'libp2p_dht_amino'\n * })\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n */\n\nimport { KadDHT as KadDHTClass } from './kad-dht.js'\nimport { MessageType } from './message/dht.js'\nimport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper } from './utils.js'\nimport type { Libp2pEvents, ComponentLogger, TypedEventTarget, Metrics, PeerId, PeerInfo, PeerStore, RoutingOptions, PrivateKey } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { AdaptiveTimeoutInit } from '@libp2p/utils/src/adaptive-timeout.js'\nimport type { Datastore } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressEvent } from 'progress-events'\n\nexport { Libp2pRecord as Record } from '@libp2p/record'\nexport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper }\n\n/**\n * The types of events emitted during DHT queries\n */\nexport enum EventTypes {\n SEND_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADD_PEER,\n DIAL_PEER\n}\n\n/**\n * The types of messages sent to peers during DHT queries\n */\nexport { MessageType }\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport type DHTProgressEvents =\n ProgressEvent<'kad-dht:query:send-query', SendQueryEvent> |\n ProgressEvent<'kad-dht:query:peer-response', PeerResponseEvent> |\n ProgressEvent<'kad-dht:query:final-peer', FinalPeerEvent> |\n ProgressEvent<'kad-dht:query:query-error', QueryErrorEvent> |\n ProgressEvent<'kad-dht:query:provider', ProviderEvent> |\n ProgressEvent<'kad-dht:query:value', ValueEvent> |\n ProgressEvent<'kad-dht:query:add-peer', AddPeerEvent> |\n ProgressEvent<'kad-dht:query:dial-peer', DialPeerEvent>\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface SendQueryEvent {\n to: PeerId\n type: EventTypes.SEND_QUERY\n name: 'SEND_QUERY'\n messageName: keyof typeof MessageType\n messageType: MessageType\n}\n\n/**\n * Emitted when query responses are received form remote peers. Depending on the query\n * these events may be followed by a `FinalPeerEvent`, a `ValueEvent` or a `ProviderEvent`.\n */\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageName: keyof typeof MessageType\n messageType: MessageType\n closer: PeerInfo[]\n providers: PeerInfo[]\n record?: DHTRecord\n}\n\n/**\n * Emitted at the end of a `findPeer` query\n */\nexport interface FinalPeerEvent {\n from: PeerId\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\n/**\n * Something went wrong with the query\n */\nexport interface QueryErrorEvent {\n from: PeerId\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\n/**\n * Emitted when providers are found\n */\nexport interface ProviderEvent {\n from: PeerId\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\n/**\n * Emitted when values are found\n */\nexport interface ValueEvent {\n from: PeerId\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\n/**\n * Emitted when peers are added to a query\n */\nexport interface AddPeerEvent {\n type: EventTypes.ADD_PEER\n name: 'ADD_PEER'\n peer: PeerId\n}\n\n/**\n * Emitted when peers are dialled as part of a query\n */\nexport interface DialPeerEvent {\n peer: PeerId\n type: EventTypes.DIAL_PEER\n name: 'DIAL_PEER'\n}\n\nexport type QueryEvent = SendQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddPeerEvent | DialPeerEvent\n\nexport interface RoutingTable {\n size: number\n}\n\nexport interface PeerInfoMapper {\n (peer: PeerInfo): PeerInfo\n}\n\nexport interface KadDHT {\n /**\n * Get a value from the DHT, the final ValueEvent will be the best value\n */\n get(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find providers of a given CID\n */\n findProviders(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find a peer on the DHT\n */\n findPeer(id: PeerId, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find the closest peers to the passed key\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Store provider records for the passed CID on the DHT pointing to us\n */\n provide(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Provider records must be re-published every 24 hours - pass a previously\n * provided CID here to not re-publish a record for it any more\n */\n cancelReprovide(key: CID): Promise<void>\n\n /**\n * Store the passed value under the passed key on the DHT\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Returns the mode this node is in\n */\n getMode(): 'client' | 'server'\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node\n * will not.\n */\n setMode(mode: 'client' | 'server'): Promise<void>\n\n /**\n * Force a routing table refresh\n */\n refreshRoutingTable(): Promise<void>\n}\n\nexport interface SingleKadDHT extends KadDHT {\n routingTable: RoutingTable\n}\n\n/**\n * A selector function takes a DHT key and a list of records and returns the\n * index of the best record in the list\n */\nexport interface SelectFn { (key: Uint8Array, records: Uint8Array[]): number }\n\n/**\n * A validator function takes a DHT key and the value of the record for that key\n * and throws if the record is invalid\n */\nexport interface ValidateFn { (key: Uint8Array, value: Uint8Array): Promise<void> }\n\n/**\n * Selectors are a map of key prefixes to selector functions\n */\nexport type Selectors = Record<string, SelectFn>\n\n/**\n * Validators are a map of key prefixes to validator functions\n */\nexport type Validators = Record<string, ValidateFn>\n\nexport interface ProvidersInit {\n /**\n * @default 256\n */\n cacheSize?: number\n /**\n * How often invalid records are cleaned in seconds\n *\n * @default 5_400\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for in seconds\n *\n * @default 86_400\n */\n provideValidity?: number\n}\n\nexport interface ReProvideInit {\n /**\n * How many re-provide operations to run simultaneously\n *\n * @default 10\n */\n concurrency?: number\n\n /**\n * How long to let the re-provide queue grow\n *\n * @default 16_384\n */\n maxQueueSize?: number\n\n /**\n * How long before the record expiry to re-provide in ms\n *\n * @default 86_400_000 (24 hours)\n */\n threshold?: number\n\n /**\n * How often to check which records need re-providing in ms\n *\n * @default 3_600_000 (1 hour)\n */\n interval?: number\n\n /**\n * How long provider records are valid for in ms\n *\n * @default 172_800_000 (48 hours)\n */\n validity?: number\n}\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket. Once there are more than this\n * number of peers for a given prefix in a kBucket, the node will start to\n * ping existing peers to see if they are still online - if they are offline\n * they will be evicted and the new peer added.\n *\n * @default 20\n */\n kBucketSize?: number\n\n /**\n * The threshold at which a kBucket will be split into two smaller kBuckets.\n *\n * KBuckets will not be split once the maximum trie depth is reached\n * (controlled by the `prefixLength` option) so one can replicate go-libp2p's\n * accelerated DHT client by (for example) setting `kBucketSize` to `Infinity`\n * and `kBucketSplitThreshold` to 20.\n *\n * @default kBucketSize\n */\n kBucketSplitThreshold?: number\n\n /**\n * How many bits of the KAD-ID of peers to use when creating the routing\n * table.\n *\n * The routing table is a binary trie with peers stored in the leaf nodes. The\n * larger this number gets, the taller the trie can grow and the more peers\n * can be stored.\n *\n * Storing more peers means fewer lookups (and network operations) are needed\n * to locate a certain peer, but also that more memory is consumed and more\n * CPU while responding to queries (e.g. with more peers in the table sorting\n * the closest peers becomes more expensive) and CPU/network during table\n * maintenance (e.g. checking peers are still online).\n *\n * The larger this value, the more prefix bits must be the same for a peer to\n * be stored in a KAD bucket, so the fewer nodes that bucket is likely to\n * contain.\n *\n * The total number of peers in the table is a factor of `prefixLength` and\n * `kBucketSize`:\n *\n * ```\n * (2 ^ prefixLength) * kBucketSize\n * ```\n *\n * @default 6\n */\n prefixLength?: number\n\n /**\n * If true, only ever be a DHT client. If false, be a DHT client until told\n * to be a DHT server via `setMode`.\n *\n * In general this should be left as the default because server mode will be\n * selected automatically when libp2p establishes that the current node has\n * a publicly dialable address.\n *\n * The exception to this is LAN-only DHT (e.g. for testing purposes) where it\n * is safe to assume that the current node is dialable.\n *\n * @default false\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * During startup we run the self-query at a shorter interval to ensure\n * the containing node can respond to queries quickly. Set this interval\n * here in ms.\n *\n * @default 1000\n */\n initialQuerySelfInterval?: number\n\n /**\n * After startup by default all queries will be paused until the initial\n * self-query has run and there are some peers in the routing table.\n *\n * Pass true here to disable this behavior.\n *\n * @default false\n */\n allowQueryWithZeroPeers?: boolean\n\n /**\n * The network protocol to use\n *\n * @default \"/ipfs/kad/1.0.0\"\n */\n protocol?: string\n\n /**\n * The logging prefix to use\n *\n * @default \"libp2p:kad-dht\"\n */\n logPrefix?: string\n\n /**\n * The datastore prefix to use\n *\n * @default \"/dht\"\n */\n datastorePrefix?: string\n\n /**\n * The metrics prefix to use\n *\n * @default \"libp2p_kad_dht\"\n */\n metricsPrefix?: string\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be evicted from the routing table or not.\n */\n pingOldContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not\n *\n * @default 10\n */\n pingOldContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingOldContactMaxQueueSize?: number\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be added to the routing table or not.\n */\n pingNewContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should be added to\n * the routing table or not\n *\n * @default 10\n */\n pingNewContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingNewContactMaxQueueSize?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per\n * connection\n *\n * @default 32\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per\n * connection\n *\n * @default 64\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n\n /**\n * Initialization options for the Reprovider component\n */\n reprovide?: ReProvideInit\n\n /**\n * For every incoming and outgoing PeerInfo, override address configuration\n * with this filter.\n */\n peerInfoMapper?(peer: PeerInfo): PeerInfo\n\n /**\n * Dynamic network timeout settings for sending messages to peers\n */\n networkDialTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n}\n\n/**\n * Creates a custom DHT implementation, please ensure you pass a `protocol`\n * string as an option.\n */\nexport function kadDHT (init: KadDHTInit = {}): (components: KadDHTComponents) => KadDHT {\n return (components: KadDHTComponents) => new KadDHTClass(components, init)\n}\n", "import { Record } from '@libp2p/kad-dht'\nimport { type Datastore, Key } from 'interface-datastore'\nimport { CustomProgressEvent, type ProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { GetOptions, PutOptions } from '../routing'\nimport type { AbortOptions } from '@libp2p/interface'\n\nfunction dhtRoutingKey (key: Uint8Array): Key {\n return new Key('/dht/record/' + uint8ArrayToString(key, 'base32'), false)\n}\n\nexport type DatastoreProgressEvents =\n ProgressEvent<'ipns:routing:datastore:put'> |\n ProgressEvent<'ipns:routing:datastore:get'> |\n ProgressEvent<'ipns:routing:datastore:error', Error>\n\nexport interface GetResult {\n record: Uint8Array\n created: Date\n}\n\nexport interface LocalStore {\n put(routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void>\n get(routingKey: Uint8Array, options?: GetOptions): Promise<GetResult>\n has(routingKey: Uint8Array, options?: AbortOptions): Promise<boolean>\n delete(routingKey: Uint8Array, options?: AbortOptions): Promise<void>\n}\n\n/**\n * Returns an IPNSRouting implementation that reads/writes IPNS records to the\n * datastore as DHT records. This lets us publish IPNS records offline then\n * serve them to the network later in response to DHT queries.\n */\nexport function localStore (datastore: Datastore): LocalStore {\n return {\n async put (routingKey: Uint8Array, marshalledRecord: Uint8Array, options: PutOptions = {}) {\n try {\n const key = dhtRoutingKey(routingKey)\n\n // don't overwrite existing, identical records as this will affect the\n // TTL\n try {\n const existingBuf = await datastore.get(key)\n const existingRecord = Record.deserialize(existingBuf)\n\n if (uint8ArrayEquals(existingRecord.value, marshalledRecord)) {\n return\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Record(routingKey, marshalledRecord, new Date())\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:put'))\n await datastore.put(key, record.serialize(), options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<GetResult> {\n try {\n const key = dhtRoutingKey(routingKey)\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:get'))\n const buf = await datastore.get(key, options)\n\n // Unmarshal libp2p record as the DHT does\n const record = Record.deserialize(buf)\n\n return {\n record: record.value,\n created: record.timeReceived\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async has (routingKey: Uint8Array, options: AbortOptions = {}): Promise<boolean> {\n const key = dhtRoutingKey(routingKey)\n return datastore.has(key, options)\n },\n async delete (routingKey, options): Promise<void> {\n const key = dhtRoutingKey(routingKey)\n return datastore.delete(key, options)\n }\n }\n}\n", "import type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport const IDENTITY_CODEC = 0x0\nexport const SHA2_256_CODEC = 0x12\n\nexport const IPNS_STRING_PREFIX = '/ipns/'\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n"],
|
|
5
|
-
"mappings": ";8pBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,KAAIC,GAAU,UAAU,CAAc,OAAOD,GAApB,MAA6BA,GAAO,QAAQE,GAAG,IAAIC,EAAE,MAAMC,EAAE,KAAKC,EAAE,OAAOD,EAAE,IAAIE,EAAEH,EAAEE,EAAEE,EAAE,IAAID,EAAEE,EAAE,OAAOC,EAAE,WAAWC,EAAE,IAAIC,EAAE,YAAYC,EAAE,KAAK,OAAO,SAASC,EAAE,CAAC,IAAIC,EAAED,EAAEA,EAAE,EAAE,OAAUC,GAAH,IAAOD,EAAE,GAAOA,IAAJ,GAAO,EAAEA,GAAG,KAAK,GAAGC,CAAC,EAAED,EAAEX,EAAE,UAAUa,GAAGb,EAAE,SAAS,SAASW,EAAE,CAAC,OAAO,IAAIX,EAAE,CAACW,CAAC,CAAC,EAAEX,EAAE,YAAYc,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEd,EAAE,YAAYc,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAEd,EAAE,WAAW,SAASW,EAAE,CAAC,IAAIP,EAAEU,EAAE,IAAId,EAAEW,GAAGA,GAAG,IAAI,QAAQ,gBAAgB,SAASA,EAAE,CAAC,IAAIA,EAAE,CAACA,EAAEC,EAAE,MAAMD,EAAE,MAAM,IAAI,OAAOG,EAAE,KAAKH,EAAEC,EAAEA,CAAC,CAAC,EAAE,QAAQ,+BAA+B,SAASD,EAAEC,EAAEE,EAAE,CAAC,OAAOF,EAAE,IAAIE,GAAG,IAAIV,EAAE,KAAK,GAAG,CAACQ,GAAG,CAACE,GAAG,EAAE,CAAC,EAAE,QAAQ,SAAS,SAASH,EAAE,CAAC,OAAOG,EAAE,KAAK,EAAEH,EA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E,CAAC,CAAC,CAExG,OAASW,EAAU,CACjB,MAAAX,EAAQ,aAAa,IAAIY,GAAoB,uBAAwB,CAAE,IAAKoC,EAAI,OAAA5C,EAAQ,IAAAO,CAAG,CAAE,CAAC,EACxFA,CACR,CACF,GAOI,SAAUyC,GAAM1D,EAA4B,CAAE,QAAAC,EAAU,CAAA,CAAE,EAAkB,CAAA,EAAE,CAClF,OAAO,IAAIF,GAAYC,EAAYC,CAAO,CAC5C",
|
|
4
|
+
"sourcesContent": ["var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1<n.length?n[1]--:n[1]=0;if(r.time=e=Date.UTC.apply(Date,n)-(e||0),isNaN(e))throw new TypeError(\"Invalid Date\");return p(r)},d.fromTimeT=function(n){return y(n,0)},n.year=0,n.time=0,n.nano=0,n.addNano=function(n){return this.nano+=+n||0,this},n.getNano=function(){var n=p(this);return(n.time%1e3*h+ +n.nano+1e9)%1e9},n.getTimeT=function(){var n=p(this),t=Math.floor(n.time/1e3),n=n.year;n&&(t+=n*T*l/s);return t},n.getYear=function(){return this.toDate().getUTCFullYear()+this.year},n.toDate=function(){return M(p(this).time)},n.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,\"Z\")},n.toString=function(n){var t=this,r=t.toDate(),u={H:function(){return C(r.getUTCHours())},L:function(){return D(r.getUTCMilliseconds(),3)},M:function(){return C(r.getUTCMinutes())},N:function(){return D(t.getNano(),9)},S:function(){return C(r.getUTCSeconds())},Y:function(){var n=t.getYear();return 999999<n?\"+\"+n:9999<n?\"+\"+D(n,6):0<=n?D(n,4):-999999<=n?\"-\"+D(-n,6):n},a:function(){return a[r.getUTCDay()]},b:function(){return i[r.getUTCMonth()]},d:function(){return C(r.getUTCDate())},e:function(){return function(n){return(9<n?\"\":\" \")+(0|n)}(r.getUTCDate())},m:function(){return C(r.getUTCMonth()+1)}};return function e(n){return n.replace(/%./g,function(n){var t=n[1],r=v[t],t=u[t];return r?e(r):t?t():n})}(n||o)},n.writeInt64BE=t(0,1,2,3,0,4),n.writeInt64LE=t(3,2,1,0,4,0),\"%Y-%m-%dT%H:%M:%S.%NZ\"),i=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],a=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],v={\"%\":\"%\",F:\"%Y-%m-%d\",n:\"\\n\",R:\"%H:%M\",T:\"%H:%M:%S\",t:\"\\t\",X:\"%T\",Z:\"GMT\",z:\"+0000\"};return d;function d(n,t,r){var e=this;if(!(e instanceof d))return new d(n,t,r);e.time=+n||0,e.nano=+t||0,e.year=+r||0,p(e)}function p(n){var t,r,e,u=n.year,o=n.time,i=n.nano,a=((i<0||h<=i)&&(i-=(r=Math.floor(i/h))*h,o+=r,r=1),u%s);return(o<-c||c<o||a)&&((t=m(o/f))&&(u+=t*s,o-=t*f),(e=M(o)).setUTCFullYear(a+e.getUTCFullYear()),e=(o=+e)+(t=m((u-=a)/s))*f,t&&-c<=e&&e<=c&&(u-=t*s,o=e),r=1),r&&(n.year=u,n.time=o,n.nano=i),n}function M(n){var t=new Date(0);return t.setTime(n),t}function y(n,t){n=+n||0;var r=m((t=(t|0)*g)/e)+m(n/e),t=t%e+n%e,n=m(t/e);return n&&(r+=n,t-=n*e),new d(1e3*t,0,r*s)}function t(e,u,o,i,a,f){return function(n,t){var r=p(this);n=n||new Array(8);w(n,t|=0);var e=Math.floor(r.time/1e3),r=r.year*(T*l/s),u=m(r/g)+m(e/g),r=r%g+e%g,e=Math.floor(r/g);e&&(u+=e,r-=e*g);return c(n,t+a,u),c(n,t+f,r),n};function c(n,t,r){n[t+e]=r>>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n<t+8)throw new RangeError(\"Out of range\")}function C(n){return(9<n?\"\":\"0\")+(0|n)}function D(n,t){return(u+(0|n)).substr(-t)}}();", "module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n", "/**\n * @packageDocumentation\n *\n * IPNS operations using a Helia node\n *\n * @example Getting started\n *\n * With {@link IPNSRouting} routers:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n *\n * console.info(result.cid, result.path)\n * ```\n *\n * @example Publishing a recursive record\n *\n * A recursive record is a one that points to another record rather than to a\n * value.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // create another keypair to re-publish the original record\n * const recursivePrivateKey = await generateKeyPair('Ed25519')\n *\n * // publish the recursive name\n * await name.publish(recursivePrivateKey, privateKey.publicKey)\n *\n * // resolve the name recursively - it resolves until a CID is found\n * const result = await name.resolve(recursivePrivateKey.publicKey)\n * console.info(result.cid.toString() === cid.toString()) // true\n * ```\n *\n * @example Publishing a record with a path\n *\n * It is possible to publish CIDs with an associated path.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { unixfs } from '@helia/unixfs'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const fileCid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // store the file in a directory\n * const dirCid = await fs.addDirectory()\n * const finalDirCid = await fs.cp(fileCid, dirCid, '/foo.txt')\n *\n * // publish the name\n * await name.publish(privateKey, `/ipfs/${finalDirCid}/foo.txt`)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n *\n * console.info(result.cid, result.path) // QmFoo.. 'foo.txt'\n * ```\n *\n * @example Using custom PubSub router\n *\n * Additional IPNS routers can be configured - these enable alternative means to\n * publish and resolve IPNS names.\n *\n * One example is the PubSub router - this requires an instance of Helia with\n * libp2p PubSub configured.\n *\n * It works by subscribing to a pubsub topic for each IPNS name that we try to\n * resolve. Updated IPNS records are shared on these topics so an update must\n * occur before the name is resolvable.\n *\n * This router is only suitable for networks where IPNS updates are frequent\n * and multiple peers are listening on the topic(s), otherwise update messages\n * may fail to be published with \"Insufficient peers\" errors.\n *\n * ```TypeScript\n * import { createHelia, libp2pDefaults } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { pubsub } from '@helia/ipns/routing'\n * import { unixfs } from '@helia/unixfs'\n * import { gossipsub } from '@chainsafe/libp2p-gossipsub'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n * import type { Libp2p, PubSub } from '@libp2p/interface'\n * import type { DefaultLibp2pServices } from 'helia'\n *\n * const libp2pOptions = libp2pDefaults()\n * libp2pOptions.services.pubsub = gossipsub()\n *\n * const helia = await createHelia<Libp2p<DefaultLibp2pServices & { pubsub: PubSub }>>({\n * libp2p: libp2pOptions\n * })\n * const name = ipns(helia, {\n * routers: [\n * pubsub(helia)\n * ]\n * })\n *\n * // create a keypair to publish an IPNS name\n * const privateKey = await generateKeyPair('Ed25519')\n *\n * // store some data to publish\n * const fs = unixfs(helia)\n * const cid = await fs.addBytes(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // publish the name\n * await name.publish(privateKey, cid)\n *\n * // resolve the name\n * const result = await name.resolve(privateKey.publicKey)\n * ```\n *\n * @example Using custom DNS over HTTPS resolvers\n *\n * To use custom resolvers, configure Helia's `dns` option:\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns/resolvers'\n * import { helia } from '@helia/ipns/routing'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsOverHttps('https://private-dns-server.me/dns-query')\n * }\n * })\n * })\n * const name = ipns(node, {\n * routers: [\n * helia(node.routing)\n * ]\n * })\n *\n * const result = name.resolveDNSLink('some-domain-with-dnslink-entry.com')\n * ```\n *\n * @example Resolving a domain with a dnslink entry\n *\n * Calling `resolveDNSLink` with the `@helia/ipns` instance:\n *\n * ```TypeScript\n * // resolve a CID from a TXT record in a DNS zone file, using the default\n * // resolver for the current platform eg:\n * // > dig _dnslink.ipfs.io TXT\n * // ;; ANSWER SECTION:\n * // _dnslink.ipfs.io. 60 IN TXT \"dnslink=/ipns/website.ipfs.io\"\n * // > dig _dnslink.website.ipfs.io TXT\n * // ;; ANSWER SECTION:\n * // _dnslink.website.ipfs.io. 60 IN TXT \"dnslink=/ipfs/QmWebsite\"\n *\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n *\n * const node = await createHelia()\n * const name = ipns(node)\n *\n * const { answer } = await name.resolveDNSLink('ipfs.io')\n *\n * console.info(answer)\n * // { data: '/ipfs/QmWebsite' }\n * ```\n *\n * @example Using DNS-Over-HTTPS\n *\n * This example uses the Mozilla provided RFC 1035 DNS over HTTPS service. This\n * uses binary DNS records so requires extra dependencies to process the\n * response which can increase browser bundle sizes.\n *\n * If this is a concern, use the DNS-JSON-Over-HTTPS resolver instead.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns/resolvers'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsOverHttps('https://mozilla.cloudflare-dns.com/dns-query')\n * }\n * })\n * })\n * const name = ipns(node)\n *\n * const result = await name.resolveDNSLink('ipfs.io')\n * ```\n *\n * @example Using DNS-JSON-Over-HTTPS\n *\n * DNS-JSON-Over-HTTPS resolvers use the RFC 8427 `application/dns-json` and can\n * result in a smaller browser bundle due to the response being plain JSON.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const node = await createHelia({\n * dns: dns({\n * resolvers: {\n * '.': dnsJsonOverHttps('https://mozilla.cloudflare-dns.com/dns-query')\n * }\n * })\n * })\n * const name = ipns(node)\n *\n * const result = await name.resolveDNSLink('ipfs.io')\n * ```\n *\n * @example Republishing an existing IPNS record\n *\n * The `republishRecord` method allows you to republish an existing IPNS record without\n * needing the private key. This is useful for relay nodes or when you want to extend\n * the availability of a record that was created elsewhere.\n *\n * ```TypeScript\n * import { createHelia } from 'helia'\n * import { ipns } from '@helia/ipns'\n * import { createDelegatedRoutingV1HttpApiClient } from '@helia/delegated-routing-v1-http-api-client'\n * import { CID } from 'multiformats/cid'\n *\n * const helia = await createHelia()\n * const name = ipns(helia)\n *\n * const ipnsName = 'k51qzi5uqu5dktsyfv7xz8h631pri4ct7osmb43nibxiojpttxzoft6hdyyzg4'\n * const parsedCid: CID<unknown, 114, 0 | 18, 1> = CID.parse(ipnsName)\n * const delegatedClient = createDelegatedRoutingV1HttpApiClient('https://delegated-ipfs.dev')\n * const record = await delegatedClient.getIPNS(parsedCid)\n *\n * await name.republishRecord(ipnsName, record)\n * ```\n */\n\nimport { NotFoundError, isPublicKey } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { createIPNSRecord, extractPublicKeyFromIPNSRecord, marshalIPNSRecord, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from 'ipns'\nimport { ipnsSelector } from 'ipns/selector'\nimport { ipnsValidator } from 'ipns/validator'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { CustomProgressEvent } from 'progress-events'\nimport { resolveDNSLink } from './dnslink.js'\nimport { InvalidValueError, RecordsFailedValidationError, UnsupportedMultibasePrefixError, UnsupportedMultihashCodecError } from './errors.js'\nimport { helia } from './routing/helia.js'\nimport { localStore } from './routing/local-store.js'\nimport { isCodec, IDENTITY_CODEC, SHA2_256_CODEC, IPNS_STRING_PREFIX } from './utils.js'\nimport type { IPNSRouting, IPNSRoutingEvents } from './routing/index.js'\nimport type { LocalStore } from './routing/local-store.js'\nimport type { Routing } from '@helia/interface'\nimport type { AbortOptions, ComponentLogger, Logger, PrivateKey, PublicKey } from '@libp2p/interface'\nimport type { Answer, DNS, ResolveDnsProgressEvents } from '@multiformats/dns'\nimport type { Datastore } from 'interface-datastore'\nimport type { IPNSRecord } from 'ipns'\nimport type { MultibaseDecoder } from 'multiformats/bases/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\nconst log = logger('helia:ipns')\n\nconst MINUTE = 60 * 1000\nconst HOUR = 60 * MINUTE\n\nconst DEFAULT_LIFETIME_MS = 48 * HOUR\nconst DEFAULT_REPUBLISH_INTERVAL_MS = 23 * HOUR\n\nconst DEFAULT_TTL_NS = BigInt(MINUTE) * 5_000_000n // 5 minutes\n\nexport type PublishProgressEvents =\n ProgressEvent<'ipns:publish:start'> |\n ProgressEvent<'ipns:publish:success', IPNSRecord> |\n ProgressEvent<'ipns:publish:error', Error>\n\nexport type ResolveProgressEvents =\n ProgressEvent<'ipns:resolve:start', unknown> |\n ProgressEvent<'ipns:resolve:success', IPNSRecord> |\n ProgressEvent<'ipns:resolve:error', Error>\n\nexport type RepublishProgressEvents =\n ProgressEvent<'ipns:republish:start', unknown> |\n ProgressEvent<'ipns:republish:success', IPNSRecord> |\n ProgressEvent<'ipns:republish:error', { key?: MultihashDigest<0x00 | 0x12>, record: IPNSRecord, err: Error }>\n\nexport type ResolveDNSLinkProgressEvents =\n ResolveProgressEvents |\n IPNSRoutingEvents |\n ResolveDnsProgressEvents\n\nexport interface PublishOptions extends AbortOptions, ProgressOptions<PublishProgressEvents | IPNSRoutingEvents> {\n /**\n * Time duration of the signature validity in ms (default: 48hrs)\n */\n lifetime?: number\n\n /**\n * Only publish to a local datastore (default: false)\n */\n offline?: boolean\n\n /**\n * By default a IPNS V1 and a V2 signature is added to every record. Pass\n * false here to only add a V2 signature. (default: true)\n */\n v1Compatible?: boolean\n\n /**\n * The TTL of the record in ms (default: 5 minutes)\n */\n ttl?: number\n}\n\nexport interface ResolveOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached IPNS Record entries\n *\n * @default false\n */\n nocache?: boolean\n}\n\nexport interface ResolveDNSLinkOptions extends AbortOptions, ProgressOptions<ResolveDNSLinkProgressEvents> {\n /**\n * Do not query the network for the IPNS record\n *\n * @default false\n */\n offline?: boolean\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n nocache?: boolean\n\n /**\n * When resolving DNSLink records that resolve to other DNSLink records, limit\n * how many times we will recursively resolve them.\n *\n * @default 32\n */\n maxRecursiveDepth?: number\n}\n\nexport interface RepublishOptions extends AbortOptions, ProgressOptions<RepublishProgressEvents | IPNSRoutingEvents> {\n /**\n * The republish interval in ms (default: 23hrs)\n */\n interval?: number\n}\n\nexport interface RepublishRecordOptions extends AbortOptions, ProgressOptions<RepublishProgressEvents | IPNSRoutingEvents> {\n /**\n * Only publish to a local datastore\n *\n * @default false\n */\n offline?: boolean\n}\n\nexport interface ResolveResult {\n /**\n * The CID that was resolved\n */\n cid: CID\n\n /**\n * Any path component that was part of the resolved record\n *\n * @default \"\"\n */\n path: string\n}\n\nexport interface IPNSResolveResult extends ResolveResult {\n /**\n * The resolved record\n */\n record: IPNSRecord\n}\n\nexport interface DNSLinkResolveResult extends ResolveResult {\n /**\n * The resolved record\n */\n answer: Answer\n}\n\nexport interface IPNS {\n /**\n * Creates an IPNS record signed by the passed PeerId that will resolve to the passed value\n *\n * If the value is a PeerId, a recursive IPNS record will be created.\n */\n publish(key: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, options?: PublishOptions): Promise<IPNSRecord>\n\n /**\n * Accepts a public key formatted as a libp2p PeerID and resolves the IPNS record\n * corresponding to that public key until a value is found\n */\n resolve(key: PublicKey | MultihashDigest<0x00 | 0x12>, options?: ResolveOptions): Promise<IPNSResolveResult>\n\n /**\n * Resolve a CID from a dns-link style IPNS record\n */\n resolveDNSLink(domain: string, options?: ResolveDNSLinkOptions): Promise<DNSLinkResolveResult>\n\n /**\n * Periodically republish all IPNS records found in the datastore\n */\n republish(options?: RepublishOptions): void\n\n /**\n * Republish an existing IPNS record without the private key.\n *\n * Before republishing the record will be validated to ensure it has a valid signature and lifetime(validity) in the future.\n * The key is a multihash of the public key or a string representation of the PeerID (either base58btc encoded multihash or base36 encoded CID)\n */\n republishRecord(key: MultihashDigest<0x00 | 0x12> | string, record: IPNSRecord, options?: RepublishRecordOptions): Promise<void>\n}\n\nexport type { IPNSRouting } from './routing/index.js'\n\nexport type { IPNSRecord } from 'ipns'\n\nexport interface IPNSComponents {\n datastore: Datastore\n routing: Routing\n dns: DNS\n logger: ComponentLogger\n}\n\nconst bases: Record<string, MultibaseDecoder<string>> = {\n [base36.prefix]: base36,\n [base58btc.prefix]: base58btc\n}\n\nclass DefaultIPNS implements IPNS {\n private readonly routers: IPNSRouting[]\n private readonly localStore: LocalStore\n private timeout?: ReturnType<typeof setTimeout>\n private readonly dns: DNS\n private readonly log: Logger\n\n constructor (components: IPNSComponents, routers: IPNSRouting[] = []) {\n this.routers = [\n helia(components.routing),\n ...routers\n ]\n this.localStore = localStore(components.datastore)\n this.dns = components.dns\n this.log = components.logger.forComponent('helia:ipns')\n }\n\n async publish (key: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, options: PublishOptions = {}): Promise<IPNSRecord> {\n try {\n let sequenceNumber = 1n\n const routingKey = multihashToIPNSRoutingKey(key.publicKey.toMultihash())\n\n if (await this.localStore.has(routingKey, options)) {\n // if we have published under this key before, increment the sequence number\n const { record } = await this.localStore.get(routingKey, options)\n const existingRecord = unmarshalIPNSRecord(record)\n sequenceNumber = existingRecord.sequence + 1n\n }\n\n // convert ttl from milliseconds to nanoseconds as createIPNSRecord expects\n const ttlNs = options.ttl != null ? BigInt(options.ttl) * 1_000_000n : DEFAULT_TTL_NS\n const record = await createIPNSRecord(key, value, sequenceNumber, options.lifetime ?? DEFAULT_LIFETIME_MS, { ...options, ttlNs })\n const marshaledRecord = marshalIPNSRecord(record)\n\n await this.localStore.put(routingKey, marshaledRecord, options)\n\n if (options.offline !== true) {\n // publish record to routing\n await Promise.all(this.routers.map(async r => { await r.put(routingKey, marshaledRecord, options) }))\n }\n\n return record\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:publish:error', err))\n throw err\n }\n }\n\n async resolve (key: PublicKey | MultihashDigest<0x00 | 0x12>, options: ResolveOptions = {}): Promise<IPNSResolveResult> {\n const digest = isPublicKey(key) ? key.toMultihash() : key\n const routingKey = multihashToIPNSRoutingKey(digest)\n const record = await this.#findIpnsRecord(routingKey, options)\n\n return {\n ...(await this.#resolve(record.value, options)),\n record\n }\n }\n\n async resolveDNSLink (domain: string, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResolveResult> {\n const dnslink = await resolveDNSLink(domain, this.dns, this.log, options)\n\n return {\n ...(await this.#resolve(dnslink.value, options)),\n answer: dnslink.answer\n }\n }\n\n republish (options: RepublishOptions = {}): void {\n if (this.timeout != null) {\n throw new Error('Republish is already running')\n }\n\n options.signal?.addEventListener('abort', () => {\n clearTimeout(this.timeout)\n })\n\n async function republish (): Promise<void> {\n const startTime = Date.now()\n\n options.onProgress?.(new CustomProgressEvent('ipns:republish:start'))\n\n const finishType = Date.now()\n const timeTaken = finishType - startTime\n let nextInterval = DEFAULT_REPUBLISH_INTERVAL_MS - timeTaken\n\n if (nextInterval < 0) {\n nextInterval = options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS\n }\n\n setTimeout(() => {\n republish().catch(err => {\n log.error('error republishing', err)\n })\n }, nextInterval)\n }\n\n this.timeout = setTimeout(() => {\n republish().catch(err => {\n log.error('error republishing', err)\n })\n }, options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS)\n }\n\n async #resolve (ipfsPath: string, options: ResolveOptions = {}): Promise<{ cid: CID, path: string }> {\n const parts = ipfsPath.split('/')\n try {\n const scheme = parts[1]\n\n if (scheme === 'ipns') {\n const str = parts[2]\n const prefix = str.substring(0, 1)\n let buf: Uint8Array | undefined\n\n if (prefix === '1' || prefix === 'Q') {\n buf = base58btc.decode(`z${str}`)\n } else if (bases[prefix] != null) {\n buf = bases[prefix].decode(str)\n } else {\n throw new UnsupportedMultibasePrefixError(`Unsupported multibase prefix \"${prefix}\"`)\n }\n\n let digest: MultihashDigest<number>\n\n try {\n digest = Digest.decode(buf)\n } catch {\n digest = CID.decode(buf).multihash\n }\n\n if (!isCodec(digest, IDENTITY_CODEC) && !isCodec(digest, SHA2_256_CODEC)) {\n throw new UnsupportedMultihashCodecError(`Unsupported multihash codec \"${digest.code}\"`)\n }\n\n const { cid } = await this.resolve(digest, options)\n const path = parts.slice(3).join('/')\n return {\n cid,\n path\n }\n } else if (scheme === 'ipfs') {\n const cid = CID.parse(parts[2])\n const path = parts.slice(3).join('/')\n return {\n cid,\n path\n }\n }\n } catch (err) {\n log.error('error parsing ipfs path', err)\n }\n\n log.error('invalid ipfs path %s', ipfsPath)\n throw new InvalidValueError('Invalid value')\n }\n\n async #findIpnsRecord (routingKey: Uint8Array, options: ResolveOptions = {}): Promise<IPNSRecord> {\n const records: Uint8Array[] = []\n const cached = await this.localStore.has(routingKey, options)\n\n if (cached) {\n log('record is present in the cache')\n\n if (options.nocache !== true) {\n try {\n // check the local cache first\n const { record, created } = await this.localStore.get(routingKey, options)\n\n this.log('record retrieved from cache')\n\n // validate the record\n await ipnsValidator(routingKey, record)\n\n this.log('record was valid')\n\n // check the TTL\n const ipnsRecord = unmarshalIPNSRecord(record)\n\n // IPNS TTL is in nanoseconds, convert to milliseconds, default to one\n // hour\n const ttlMs = Number((ipnsRecord.ttl ?? DEFAULT_TTL_NS) / 1_000_000n)\n const ttlExpires = created.getTime() + ttlMs\n\n if (ttlExpires > Date.now()) {\n // the TTL has not yet expired, return the cached record\n this.log('record TTL was valid')\n return ipnsRecord\n }\n\n if (options.offline === true) {\n // the TTL has expired but we are skipping the routing search\n this.log('record TTL has been reached but we are resolving offline-only, returning record')\n return ipnsRecord\n }\n\n this.log('record TTL has been reached, searching routing for updates')\n\n // add the local record to our list of resolved record, and also\n // search the routing for updates - the most up to date record will be\n // returned\n records.push(record)\n } catch (err) {\n this.log('cached record was invalid', err)\n await this.localStore.delete(routingKey, options)\n }\n } else {\n log('ignoring local cache due to nocache=true option')\n }\n }\n\n if (options.offline === true) {\n throw new NotFoundError('Record was not present in the cache or has expired')\n }\n\n log('did not have record locally')\n\n let foundInvalid = 0\n\n await Promise.all(\n this.routers.map(async (router) => {\n let record: Uint8Array\n\n try {\n record = await router.get(routingKey, {\n ...options,\n validate: false\n })\n } catch (err: any) {\n log.error('error finding IPNS record', err)\n\n return\n }\n\n try {\n await ipnsValidator(routingKey, record)\n\n records.push(record)\n } catch (err) {\n // we found a record, but the validator rejected it\n foundInvalid++\n log.error('error finding IPNS record', err)\n }\n })\n )\n\n if (records.length === 0) {\n if (foundInvalid > 0) {\n throw new RecordsFailedValidationError(`${foundInvalid > 1 ? `${foundInvalid} records` : 'Record'} found for routing key ${foundInvalid > 1 ? 'were' : 'was'} invalid`)\n }\n\n throw new NotFoundError('Could not find record for routing key')\n }\n\n const record = records[ipnsSelector(routingKey, records)]\n\n await this.localStore.put(routingKey, record, options)\n\n return unmarshalIPNSRecord(record)\n }\n\n async republishRecord (key: MultihashDigest<0x00 | 0x12> | string, record: IPNSRecord, options: RepublishRecordOptions = {}): Promise<void> {\n let mh: MultihashDigest<0x00 | 0x12> | undefined\n try {\n mh = extractPublicKeyFromIPNSRecord(record)?.toMultihash() // embedded public key take precedence, if present\n if (mh == null) {\n // if no public key is embedded in the record, use the key that was passed in\n if (typeof key === 'string') {\n if (key.startsWith(IPNS_STRING_PREFIX)) {\n // remove the /ipns/ prefix from the key\n key = key.slice(IPNS_STRING_PREFIX.length)\n }\n // Convert string key to MultihashDigest\n try {\n mh = peerIdFromString(key).toMultihash()\n } catch (err: any) {\n throw new Error(`Invalid string key: ${err.message}`)\n }\n } else {\n mh = key\n }\n }\n\n if (mh == null) {\n throw new Error('No public key multihash found to determine the routing key')\n }\n\n const routingKey = multihashToIPNSRoutingKey(mh)\n const marshaledRecord = marshalIPNSRecord(record)\n\n await ipnsValidator(routingKey, marshaledRecord) // validate that they key corresponds to the record\n\n await this.localStore.put(routingKey, marshaledRecord, options) // add to local store\n\n if (options.offline !== true) {\n // publish record to routing\n await Promise.all(this.routers.map(async r => { await r.put(routingKey, marshaledRecord, options) }))\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent('ipns:republish:error', { key: mh, record, err }))\n throw err\n }\n }\n}\n\nexport interface IPNSOptions {\n routers?: IPNSRouting[]\n}\n\nexport function ipns (components: IPNSComponents, { routers = [] }: IPNSOptions = {}): IPNS {\n return new DefaultIPNS(components, routers)\n}\n\nexport { ipnsValidator, type IPNSRoutingEvents }\nexport { ipnsSelector } from 'ipns/selector'\n", "import type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport type KeyType = 'RSA' | 'Ed25519' | 'secp256k1' | 'ECDSA'\n\nexport interface RSAPublicKey {\n /**\n * The type of this key\n */\n readonly type: 'RSA'\n\n /**\n * PKIX in ASN1 DER format\n */\n readonly raw: Uint8Array\n\n /**\n * The public key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as a Multihash digest.\n *\n * It contains a sha256 hash of the protobuf version of the public key.\n */\n toMultihash(): MultihashDigest<0x12>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains a sha256 hash of the protobuf version of the public\n * key.\n */\n toCID(): CID<unknown, 0x72, 0x12, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface Ed25519PublicKey {\n /**\n * The type of this key\n */\n readonly type: 'Ed25519'\n\n /**\n * The raw public key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface Secp256k1PublicKey {\n /**\n * The type of this key\n */\n readonly type: 'secp256k1'\n\n /**\n * The raw public key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport interface ECDSAPublicKey {\n /**\n * The type of this key\n */\n readonly type: 'ECDSA'\n\n /**\n * The public key as a DER-encoded PKIMessage\n */\n readonly raw: Uint8Array\n\n /**\n * The public key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Returns this public key as an identity hash containing the protobuf wrapped\n * public key\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Return this public key as a CID encoded with the `libp2p-key` codec\n *\n * The digest contains an identity hash containing the protobuf wrapped\n * version of the public key.\n */\n toCID(): CID<unknown, 0x72, 0x0, 1>\n\n /**\n * Verify the passed data was signed by the private key corresponding to this\n * public key\n */\n verify(data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean>\n\n /**\n * Returns this key as a multihash with base58btc encoding\n */\n toString(): string\n}\n\nexport type PublicKey = RSAPublicKey | Ed25519PublicKey | Secp256k1PublicKey | ECDSAPublicKey\n\n/**\n * Returns true if the passed argument has type overlap with the `PublicKey`\n * interface. Can be used to disambiguate object types.\n */\nexport function isPublicKey (key?: any): key is PublicKey {\n if (key == null) {\n return false\n }\n\n return (key.type === 'RSA' || key.type === 'Ed25519' || key.type === 'secp256k1' || key.type === 'ECDSA') &&\n key.raw instanceof Uint8Array &&\n typeof key.equals === 'function' &&\n typeof key.toMultihash === 'function' &&\n typeof key.toCID === 'function' &&\n typeof key.verify === 'function'\n}\n\n/**\n * Generic private key interface\n */\nexport interface RSAPrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'RSA'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: RSAPublicKey\n\n /**\n * PKIX in ASN1 DER format\n */\n readonly raw: Uint8Array\n\n /**\n * The private key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface Ed25519PrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'Ed25519'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: Ed25519PublicKey\n\n /**\n * The raw private key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface Secp256k1PrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'secp256k1'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: Secp256k1PublicKey\n\n /**\n * The raw private key bytes\n */\n readonly raw: Uint8Array\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport interface ECDSAPrivateKey {\n /**\n * The type of this key\n */\n readonly type: 'ECDSA'\n\n /**\n * The public key that corresponds to this private key\n */\n readonly publicKey: ECDSAPublicKey\n\n /**\n * The private key as a DER-encoded PKIMessage\n */\n readonly raw: Uint8Array\n\n /**\n * The private key as a JSON web key\n */\n readonly jwk: JsonWebKey\n\n /**\n * Returns `true` if the passed object matches this key\n */\n equals(key?: any): boolean\n\n /**\n * Sign the passed data with this private key and return the signature for\n * later verification\n */\n sign(data: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array>\n}\n\nexport type PrivateKey = RSAPrivateKey | Ed25519PrivateKey | Secp256k1PrivateKey | ECDSAPrivateKey\n\n/**\n * Returns true if the passed argument has type overlap with the `PrivateKey`\n * interface. Can be used to disambiguate object types.\n */\nexport function isPrivateKey (key?: any): key is PrivateKey {\n if (key == null) {\n return false\n }\n\n return (key.type === 'RSA' || key.type === 'Ed25519' || key.type === 'secp256k1' || key.type === 'ECDSA') &&\n isPublicKey(key.publicKey) &&\n key.raw instanceof Uint8Array &&\n typeof key.equals === 'function' &&\n typeof key.sign === 'function'\n}\n", "import type { Ed25519PublicKey, KeyType, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport type PeerIdType = KeyType | string\n\n/**\n * A PeerId generated from an RSA public key - it is a base58btc encoded sha-256\n * hash of the public key.\n *\n * RSA public keys are too large to pass around freely, instead Ed25519 or\n * secp256k1 should be preferred as they can embed their public key in the\n * PeerId itself.\n *\n * @deprecated Ed25519 or secp256k1 keys are preferred to RSA\n */\nexport interface RSAPeerId {\n readonly type: 'RSA'\n\n /**\n * RSA public keys are too large to embed in the multihash commonly used to\n * refer to peers, so this will only be defined if the public key has\n * previously been found through a routing query or during normal protocol\n * operations\n */\n readonly publicKey?: RSAPublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the SHA2-256 hash of the public\n * key\n */\n toMultihash(): MultihashDigest<0x12>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x12, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Ed25519PeerId {\n readonly type: 'Ed25519'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Ed25519PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface Secp256k1PeerId {\n readonly type: 'secp256k1'\n\n /**\n * This will always be defined as the public key is embedded in the multihash\n * of this PeerId\n */\n readonly publicKey: Secp256k1PublicKey\n\n /**\n * Returns the multihash from `toMultihash()` as a base58btc encoded string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the protobuf-encoded public key\n * encoded as an identity hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the libp2p key code and the same multihash as\n * `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x72, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\nexport interface URLPeerId {\n readonly type: 'url'\n\n /**\n * This will always be undefined as URL Peers do not have public keys\n */\n readonly publicKey: undefined\n\n /**\n * Returns CID from `toCID()` encoded as a base36 string\n */\n toString(): string\n\n /**\n * Returns a multihash, the digest of which is the URL encoded as an identity\n * hash\n */\n toMultihash(): MultihashDigest<0x0>\n\n /**\n * Returns a CID with the Transport IPFS Gateway HTTP code and the same\n * multihash as `toMultihash()`\n */\n toCID(): CID<Uint8Array, 0x0920, 0x0, 1>\n\n /**\n * Returns true if the passed argument is equivalent to this PeerId\n */\n equals(other?: any): boolean\n}\n\n/**\n * This is a union of all known PeerId types - use the `.type` field to\n * disambiguate them\n */\nexport type PeerId = RSAPeerId | Ed25519PeerId | Secp256k1PeerId | URLPeerId\n\n/**\n * All PeerId implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id')\n\n/**\n * Returns true if the passed argument is a PeerId implementation\n */\nexport function isPeerId (other?: any): other is PeerId {\n return Boolean(other?.[peerIdSymbol])\n}\n", "/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError'\n\n constructor (message: string = 'The operation was aborted') {\n super(message)\n this.name = 'AbortError'\n }\n}\n\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError'\n\n constructor (message = 'Unexpected Peer') {\n super(message)\n this.name = 'UnexpectedPeerError'\n }\n}\n\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError'\n\n constructor (message = 'Invalid crypto exchange') {\n super(message)\n this.name = 'InvalidCryptoExchangeError'\n }\n}\n\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n\n constructor (message = 'Invalid parameters') {\n super(message)\n this.name = 'InvalidParametersError'\n }\n}\n\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError'\n\n constructor (message = 'Invalid public key') {\n super(message)\n this.name = 'InvalidPublicKeyError'\n }\n}\n\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError'\n\n constructor (message = 'Invalid private key') {\n super(message)\n this.name = 'InvalidPrivateKeyError'\n }\n}\n\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError'\n\n constructor (message = 'Unsupported operation') {\n super(message)\n this.name = 'UnsupportedOperationError'\n }\n}\n\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError'\n\n constructor (message = 'The connection is closing') {\n super(message)\n this.name = 'ConnectionClosingError'\n }\n}\n\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError'\n\n constructor (message = 'The connection is closed') {\n super(message)\n this.name = 'ConnectionClosedError'\n }\n}\n\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError'\n\n constructor (message = 'Connection failed') {\n super(message)\n this.name = 'ConnectionFailedError'\n }\n}\n\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError'\n\n constructor (message = 'The muxer is closed') {\n super(message)\n this.name = 'MuxerClosedError'\n }\n}\n\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError'\n\n constructor (message = 'The stream has been reset') {\n super(message)\n this.name = 'StreamResetError'\n }\n}\n\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError'\n\n constructor (message = 'The stream is in an invalid state') {\n super(message)\n this.name = 'StreamStateError'\n }\n}\n\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError'\n\n constructor (message = 'Not found') {\n super(message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError'\n\n constructor (message = 'Invalid PeerID') {\n super(message)\n this.name = 'InvalidPeerIdError'\n }\n}\n\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n\n constructor (message = 'Invalid multiaddr') {\n super(message)\n this.name = 'InvalidMultiaddrError'\n }\n}\n\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError'\n\n constructor (message = 'Invalid CID') {\n super(message)\n this.name = 'InvalidCIDError'\n }\n}\n\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError'\n\n constructor (message = 'Invalid Multihash') {\n super(message)\n this.name = 'InvalidMultihashError'\n }\n}\n\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError'\n\n constructor (message = 'Unsupported protocol error') {\n super(message)\n this.name = 'UnsupportedProtocolError'\n }\n}\n\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError'\n\n constructor (message = 'Invalid message') {\n super(message)\n this.name = 'InvalidMessageError'\n }\n}\n\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError'\n\n constructor (message = 'Protocol error') {\n super(message)\n this.name = 'ProtocolError'\n }\n}\n\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError'\n\n constructor (message = 'Timed out') {\n super(message)\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError'\n\n constructor (message = 'Not started') {\n super(message)\n this.name = 'NotStartedError'\n }\n}\n\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError'\n\n constructor (message = 'Already started') {\n super(message)\n this.name = 'AlreadyStartedError'\n }\n}\n\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError'\n\n constructor (message = 'Dial error') {\n super(message)\n this.name = 'DialError'\n }\n}\n\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError'\n\n constructor (message = 'Listen error') {\n super(message)\n this.name = 'ListenError'\n }\n}\n\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError'\n\n constructor (message = 'Limited connection') {\n super(message)\n this.name = 'LimitedConnectionError'\n }\n}\n\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError'\n\n constructor (message = 'Too many inbound protocol streams') {\n super(message)\n this.name = 'TooManyInboundProtocolStreamsError'\n }\n}\n\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError'\n\n constructor (message = 'Too many outbound protocol streams') {\n super(message)\n this.name = 'TooManyOutboundProtocolStreamsError'\n }\n}\n\n/**\n * Thrown when and attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError'\n\n constructor (message = 'Unsupported key type') {\n super(message)\n this.name = 'UnsupportedKeyTypeError'\n }\n}\n", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n const prefixCodePoint = prefix.codePointAt(0)\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefixCodePoint\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\n // Count the padding bytes:\n let end = string.length\n while (string[end - 1] === '=') {\n --end\n }\n\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0)\n\n // Parse the data:\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n let written = 0 // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]]\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`)\n }\n\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value\n bits += bitsPerChar\n\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8\n out[written++] = 0xff & (buffer >> bits)\n }\n }\n\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\nfunction encode (data: Uint8Array, alphabet: string, bitsPerChar: number): string {\n const pad = alphabet[alphabet.length - 1] === '='\n const mask = (1 << bitsPerChar) - 1\n let out = ''\n\n let bits = 0 // Number of bits currently in the buffer\n let buffer = 0 // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i]\n bits += 8\n\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar\n out += alphabet[mask & (buffer >> bits)]\n }\n }\n\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))]\n }\n\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n */\nexport function rfc4648 <Base extends string, Prefix extends string> ({ name, prefix, bitsPerChar, alphabet }: { name: Base, prefix: Prefix, bitsPerChar: number, alphabet: string }): Codec<Base, Prefix> {\n return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\nexport default ms;\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n", "/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n", "/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Debug {\n (namespace: string): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n}\n\nexport default weald\n", "/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString()\n}\n\nexport interface Logger {\n (formatter: any, ...args: any[]): void\n error(formatter: any, ...args: any[]): void\n trace(formatter: any, ...args: any[]): void\n enabled: boolean\n}\n\nexport interface ComponentLogger {\n forComponent(name: string): Logger\n}\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12\u2026oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial<PeerLoggerOptions> = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n", "import { baseX } from './base.js'\n\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n})\n\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n})\n", "/* eslint-disable */\nvar encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\n\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n\n while(num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while(num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n \n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint')\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1)\n\n // @ts-ignore\n read.bytes = counter - offset;\n\n return res\n}\n\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\n\nvar length = function (/** @type {number} */ value) {\n return (\n value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10\n )\n};\n\nvar varint = {\n encode: encode_1\n , decode: decode\n , encodingLength: length\n};\n\nvar _brrp_varint = varint;\n\nexport default _brrp_varint;\n", "import varint from './vendor/varint.js'\n\nexport function decode (data: Uint8Array, offset = 0): [number, number] {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\nexport function encodeTo (int: number, target: Uint8Array, offset = 0): Uint8Array {\n varint.encode(int, target, offset)\n return target\n}\n\nexport function encodingLength (int: number): number {\n return varint.encodingLength(int)\n}\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode <T extends number> (digest: MultihashDigest, code: T): digest is MultihashDigest<T> {\n return digest.code === code\n}\n", "import { base32 } from './bases/base32.js'\nimport { base36 } from './bases/base36.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n case base36.prefix: {\n const decoder = base ?? base36\n return [base36.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { coerce } from '../bytes.js'\nimport * as Digest from './digest.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array): Digest.Digest<typeof code, number> {\n return Digest.create(code, encode(input))\n}\n\nexport const identity = { code, name, encode, digest }\n", "/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals (a: Uint8Array, b: Uint8Array): boolean {\n if (a === b) {\n return true\n }\n\n if (a.byteLength !== b.byteLength) {\n return false\n }\n\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}\n", "/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe (size: number = 0): Uint8Array {\n return new Uint8Array(size)\n}\n", "import { allocUnsafe } from '#alloc'\nimport { asUint8Array } from '#util/as-uint8array'\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat (arrays: Uint8Array[], length?: number): Uint8Array {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0)\n }\n\n const output = allocUnsafe(length)\n let offset = 0\n\n for (const arr of arrays) {\n output.set(arr, offset)\n offset += arr.length\n }\n\n return asUint8Array(output)\n}\n", "/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc'\nimport { concat } from 'uint8arrays/concat'\nimport { equals } from 'uint8arrays/equals'\n\nconst symbol = Symbol.for('@achingbrain/uint8arraylist')\n\nexport type Appendable = Uint8ArrayList | Uint8Array\n\nfunction findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds')\n }\n\n let offset = 0\n\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength\n\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n }\n }\n\n offset = bufEnd\n }\n\n throw new RangeError('index is out of bounds')\n}\n\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList (value: any): value is Uint8ArrayList {\n return Boolean(value?.[symbol])\n}\n\nexport class Uint8ArrayList implements Iterable<Uint8Array> {\n private bufs: Uint8Array[]\n public length: number\n public readonly [symbol] = true\n\n constructor (...data: Appendable[]) {\n this.bufs = []\n this.length = 0\n\n if (data.length > 0) {\n this.appendAll(data)\n }\n }\n\n * [Symbol.iterator] (): Iterator<Uint8Array> {\n yield * this.bufs\n }\n\n get byteLength (): number {\n return this.length\n }\n\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append (...bufs: Appendable[]): void {\n this.appendAll(bufs)\n }\n\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.push(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.push(...buf.bufs)\n } else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend (...bufs: Appendable[]): void {\n this.prependAll(bufs)\n }\n\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll (bufs: Appendable[]): void {\n let length = 0\n\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength\n this.bufs.unshift(buf)\n } else if (isUint8ArrayList(buf)) {\n length += buf.byteLength\n this.bufs.unshift(...buf.bufs)\n } else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n this.length += length\n }\n\n /**\n * Read the value at `index`\n */\n get (index: number): number {\n const res = findBufAndOffset(this.bufs, index)\n\n return res.buf[res.index]\n }\n\n /**\n * Set the value at `index` to `value`\n */\n set (index: number, value: number): void {\n const res = findBufAndOffset(this.bufs, index)\n\n res.buf[res.index] = value\n }\n\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write (buf: Appendable, offset: number = 0): void {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i])\n }\n } else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i))\n }\n } else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')\n }\n }\n\n /**\n * Remove bytes from the front of the pool\n */\n consume (bytes: number): void {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return\n }\n\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = []\n this.length = 0\n return\n }\n\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength\n this.length -= this.bufs[0].byteLength\n this.bufs.shift()\n } else {\n this.bufs[0] = this.bufs[0].subarray(bytes)\n this.length -= bytes\n break\n }\n }\n }\n\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return concat(bufs, length)\n }\n\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {\n const { bufs, length } = this._subList(beginInclusive, endExclusive)\n\n const list = new Uint8ArrayList()\n list.length = length\n // don't loop, just set the bufs\n list.bufs = [...bufs]\n\n return list\n }\n\n private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {\n beginInclusive = beginInclusive ?? 0\n endExclusive = endExclusive ?? this.length\n\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive\n }\n\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive\n }\n\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds')\n }\n\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 }\n }\n\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length }\n }\n\n const bufs: Uint8Array[] = []\n let offset = 0\n\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i]\n const bufStart = offset\n const bufEnd = bufStart + buf.byteLength\n\n // for next loop\n offset = bufEnd\n\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue\n }\n\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd\n\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n const start = beginInclusive - bufStart\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))\n break\n }\n\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf)\n continue\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart))\n continue\n }\n\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf)\n break\n }\n\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart))\n break\n }\n\n // slice started before this buffer and ends after it\n bufs.push(buf)\n }\n\n return { bufs, length: endExclusive - beginInclusive }\n }\n\n indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array')\n }\n\n const needle = search instanceof Uint8Array ? search : search.subarray()\n\n offset = Number(offset ?? 0)\n\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M: number = needle.byteLength\n\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long')\n }\n\n // radix\n const radix: number = 256\n const rightmostPositions: Int32Array = new Int32Array(radix)\n\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c: number = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1\n }\n\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j\n }\n\n // Return offset of first match, -1 if no match\n const right = rightmostPositions\n const lastIndex = this.byteLength - needle.byteLength\n const lastPatIndex = needle.byteLength - 1\n let skip: number\n\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0\n\n for (let j = lastPatIndex; j >= 0; j--) {\n const char: number = this.get(i + j)\n\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char])\n break\n }\n }\n\n if (skip === 0) {\n return i\n }\n }\n\n return -1\n }\n\n getInt8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt8(0)\n }\n\n setInt8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getInt16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt16(0, littleEndian)\n }\n\n setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getInt32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getInt32(0, littleEndian)\n }\n\n setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setInt32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigInt64(0, littleEndian)\n }\n\n setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigInt64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint8 (byteOffset: number): number {\n const buf = this.subarray(byteOffset, byteOffset + 1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint8(0)\n }\n\n setUint8 (byteOffset: number, value: number): void {\n const buf = allocUnsafe(1)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint8(0, value)\n\n this.write(buf, byteOffset)\n }\n\n getUint16 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint16(0, littleEndian)\n }\n\n setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(2)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint16(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getUint32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getUint32(0, littleEndian)\n }\n\n setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setUint32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getBigUint64(0, littleEndian)\n }\n\n setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setBigUint64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat32 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat32(0, littleEndian)\n }\n\n setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(4)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat32(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n getFloat64 (byteOffset: number, littleEndian?: boolean): number {\n const buf = this.subarray(byteOffset, byteOffset + 8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n\n return view.getFloat64(0, littleEndian)\n }\n\n setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {\n const buf = alloc(8)\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)\n view.setFloat64(0, value, littleEndian)\n\n this.write(buf, byteOffset)\n }\n\n equals (other: any): other is Uint8ArrayList {\n if (other == null) {\n return false\n }\n\n if (!(other instanceof Uint8ArrayList)) {\n return false\n }\n\n if (other.bufs.length !== this.bufs.length) {\n return false\n }\n\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {\n const list = new Uint8ArrayList()\n list.bufs = bufs\n\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)\n }\n\n list.length = length\n\n return list\n }\n}\n\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n", "import { baseX } from './base.js'\n\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n})\n\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n})\n", "import { from } from './base.js'\n\nconst alphabet = Array.from('\uD83D\uDE80\uD83E\uDE90\u2604\uD83D\uDEF0\uD83C\uDF0C\uD83C\uDF11\uD83C\uDF12\uD83C\uDF13\uD83C\uDF14\uD83C\uDF15\uD83C\uDF16\uD83C\uDF17\uD83C\uDF18\uD83C\uDF0D\uD83C\uDF0F\uD83C\uDF0E\uD83D\uDC09\u2600\uD83D\uDCBB\uD83D\uDDA5\uD83D\uDCBE\uD83D\uDCBF\uD83D\uDE02\u2764\uD83D\uDE0D\uD83E\uDD23\uD83D\uDE0A\uD83D\uDE4F\uD83D\uDC95\uD83D\uDE2D\uD83D\uDE18\uD83D\uDC4D\uD83D\uDE05\uD83D\uDC4F\uD83D\uDE01\uD83D\uDD25\uD83E\uDD70\uD83D\uDC94\uD83D\uDC96\uD83D\uDC99\uD83D\uDE22\uD83E\uDD14\uD83D\uDE06\uD83D\uDE44\uD83D\uDCAA\uD83D\uDE09\u263A\uD83D\uDC4C\uD83E\uDD17\uD83D\uDC9C\uD83D\uDE14\uD83D\uDE0E\uD83D\uDE07\uD83C\uDF39\uD83E\uDD26\uD83C\uDF89\uD83D\uDC9E\u270C\u2728\uD83E\uDD37\uD83D\uDE31\uD83D\uDE0C\uD83C\uDF38\uD83D\uDE4C\uD83D\uDE0B\uD83D\uDC97\uD83D\uDC9A\uD83D\uDE0F\uD83D\uDC9B\uD83D\uDE42\uD83D\uDC93\uD83E\uDD29\uD83D\uDE04\uD83D\uDE00\uD83D\uDDA4\uD83D\uDE03\uD83D\uDCAF\uD83D\uDE48\uD83D\uDC47\uD83C\uDFB6\uD83D\uDE12\uD83E\uDD2D\u2763\uD83D\uDE1C\uD83D\uDC8B\uD83D\uDC40\uD83D\uDE2A\uD83D\uDE11\uD83D\uDCA5\uD83D\uDE4B\uD83D\uDE1E\uD83D\uDE29\uD83D\uDE21\uD83E\uDD2A\uD83D\uDC4A\uD83E\uDD73\uD83D\uDE25\uD83E\uDD24\uD83D\uDC49\uD83D\uDC83\uD83D\uDE33\u270B\uD83D\uDE1A\uD83D\uDE1D\uD83D\uDE34\uD83C\uDF1F\uD83D\uDE2C\uD83D\uDE43\uD83C\uDF40\uD83C\uDF37\uD83D\uDE3B\uD83D\uDE13\u2B50\u2705\uD83E\uDD7A\uD83C\uDF08\uD83D\uDE08\uD83E\uDD18\uD83D\uDCA6\u2714\uD83D\uDE23\uD83C\uDFC3\uD83D\uDC90\u2639\uD83C\uDF8A\uD83D\uDC98\uD83D\uDE20\u261D\uD83D\uDE15\uD83C\uDF3A\uD83C\uDF82\uD83C\uDF3B\uD83D\uDE10\uD83D\uDD95\uD83D\uDC9D\uD83D\uDE4A\uD83D\uDE39\uD83D\uDDE3\uD83D\uDCAB\uD83D\uDC80\uD83D\uDC51\uD83C\uDFB5\uD83E\uDD1E\uD83D\uDE1B\uD83D\uDD34\uD83D\uDE24\uD83C\uDF3C\uD83D\uDE2B\u26BD\uD83E\uDD19\u2615\uD83C\uDFC6\uD83E\uDD2B\uD83D\uDC48\uD83D\uDE2E\uD83D\uDE46\uD83C\uDF7B\uD83C\uDF43\uD83D\uDC36\uD83D\uDC81\uD83D\uDE32\uD83C\uDF3F\uD83E\uDDE1\uD83C\uDF81\u26A1\uD83C\uDF1E\uD83C\uDF88\u274C\u270A\uD83D\uDC4B\uD83D\uDE30\uD83E\uDD28\uD83D\uDE36\uD83E\uDD1D\uD83D\uDEB6\uD83D\uDCB0\uD83C\uDF53\uD83D\uDCA2\uD83E\uDD1F\uD83D\uDE41\uD83D\uDEA8\uD83D\uDCA8\uD83E\uDD2C\u2708\uD83C\uDF80\uD83C\uDF7A\uD83E\uDD13\uD83D\uDE19\uD83D\uDC9F\uD83C\uDF31\uD83D\uDE16\uD83D\uDC76\uD83E\uDD74\u25B6\u27A1\u2753\uD83D\uDC8E\uD83D\uDCB8\u2B07\uD83D\uDE28\uD83C\uDF1A\uD83E\uDD8B\uD83D\uDE37\uD83D\uDD7A\u26A0\uD83D\uDE45\uD83D\uDE1F\uD83D\uDE35\uD83D\uDC4E\uD83E\uDD32\uD83E\uDD20\uD83E\uDD27\uD83D\uDCCC\uD83D\uDD35\uD83D\uDC85\uD83E\uDDD0\uD83D\uDC3E\uD83C\uDF52\uD83D\uDE17\uD83E\uDD11\uD83C\uDF0A\uD83E\uDD2F\uD83D\uDC37\u260E\uD83D\uDCA7\uD83D\uDE2F\uD83D\uDC86\uD83D\uDC46\uD83C\uDFA4\uD83D\uDE47\uD83C\uDF51\u2744\uD83C\uDF34\uD83D\uDCA3\uD83D\uDC38\uD83D\uDC8C\uD83D\uDCCD\uD83E\uDD40\uD83E\uDD22\uD83D\uDC45\uD83D\uDCA1\uD83D\uDCA9\uD83D\uDC50\uD83D\uDCF8\uD83D\uDC7B\uD83E\uDD10\uD83E\uDD2E\uD83C\uDFBC\uD83E\uDD75\uD83D\uDEA9\uD83C\uDF4E\uD83C\uDF4A\uD83D\uDC7C\uD83D\uDC8D\uD83D\uDCE3\uD83E\uDD42')\nconst alphabetBytesToChars: string[] = (alphabet.reduce<string[]>((p, c, i) => { p[i] = c; return p }, ([])))\nconst alphabetCharsToBytes: number[] = (alphabet.reduce<number[]>((p, c, i) => {\n const codePoint = c.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`)\n }\n p[codePoint] = i\n return p\n}, ([])))\n\nfunction encode (data: Uint8Array): string {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c]\n return p\n }, '')\n}\n\nfunction decode (str: string): Uint8Array {\n const byts = []\n for (const char of str) {\n const codePoint = char.codePointAt(0)\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`)\n }\n const byt = alphabetCharsToBytes[codePoint]\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`)\n }\n byts.push(byt)\n }\n return new Uint8Array(byts)\n}\n\nexport const base256emoji = from({\n prefix: '\uD83D\uDE80',\n name: 'base256emoji',\n encode,\n decode\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n", "import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n", "import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n", "/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "import * as base10 from './bases/base10.js'\nimport * as base16 from './bases/base16.js'\nimport * as base2 from './bases/base2.js'\nimport * as base256emoji from './bases/base256emoji.js'\nimport * as base32 from './bases/base32.js'\nimport * as base36 from './bases/base36.js'\nimport * as base58 from './bases/base58.js'\nimport * as base64 from './bases/base64.js'\nimport * as base8 from './bases/base8.js'\nimport * as identityBase from './bases/identity.js'\nimport * as json from './codecs/json.js'\nimport * as raw from './codecs/raw.js'\nimport * as identity from './hashes/identity.js'\nimport * as sha2 from './hashes/sha2.js'\nimport { CID, hasher, digest, varint, bytes } from './index.js'\n\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji }\nexport const hashes = { ...sha2, ...identity }\nexport const codecs = { raw, json }\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { bases } from 'multiformats/basics'\nimport type { MultibaseCodec } from 'multiformats'\nimport { allocUnsafe } from '#alloc'\n\nfunction createCodec (name: string, prefix: string, encode: (buf: Uint8Array) => string, decode: (str: string) => Uint8Array): MultibaseCodec<any> {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n }\n}\n\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8')\n return 'u' + decoder.decode(buf)\n}, (str) => {\n const encoder = new TextEncoder()\n return encoder.encode(str.substring(1))\n})\n\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a'\n\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i])\n }\n return string\n}, (str) => {\n str = str.substring(1)\n const buf = allocUnsafe(str.length)\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i)\n }\n\n return buf\n})\n\nexport type SupportedEncodings = 'utf8' | 'utf-8' | 'hex' | 'latin1' | 'ascii' | 'binary' | keyof typeof bases\n\nconst BASES: Record<SupportedEncodings, MultibaseCodec<any>> = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n\n ...bases\n}\n\nexport default BASES\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString (string: string, encoding: SupportedEncodings = 'utf8'): Uint8Array {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`) // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n", "import bases, { type SupportedEncodings } from './util/bases.js'\n\nexport type { SupportedEncodings }\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString (array: Uint8Array, encoding: SupportedEncodings = 'utf8'): string {\n const base = bases[encoding]\n\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`)\n }\n\n // strip multibase prefix\n return base.encoder.encode(array).substring(1)\n}\n", "import { Uint8ArrayList } from 'uint8arraylist'\n\ninterface Context {\n offset: number\n}\n\nconst TAG_MASK = parseInt('11111', 2)\nconst LONG_LENGTH_MASK = parseInt('10000000', 2)\nconst LONG_LENGTH_BYTES_MASK = parseInt('01111111', 2)\n\ninterface Decoder {\n (buf: Uint8Array, context: Context): any\n}\n\nconst decoders: Record<number, Decoder> = {\n 0x0: readSequence,\n 0x1: readSequence,\n 0x2: readInteger,\n 0x3: readBitString,\n 0x4: readOctetString,\n 0x5: readNull,\n 0x6: readObjectIdentifier,\n 0x10: readSequence,\n 0x16: readSequence,\n 0x30: readSequence\n}\n\nexport function decodeDer (buf: Uint8Array, context: Context = { offset: 0 }): any {\n const tag = buf[context.offset] & TAG_MASK\n context.offset++\n\n if (decoders[tag] != null) {\n return decoders[tag](buf, context)\n }\n\n throw new Error('No decoder for tag ' + tag)\n}\n\nfunction readLength (buf: Uint8Array, context: Context): number {\n let length = 0\n\n if ((buf[context.offset] & LONG_LENGTH_MASK) === LONG_LENGTH_MASK) {\n // long length\n const count = buf[context.offset] & LONG_LENGTH_BYTES_MASK\n let str = '0x'\n context.offset++\n\n for (let i = 0; i < count; i++, context.offset++) {\n str += buf[context.offset].toString(16).padStart(2, '0')\n }\n\n length = parseInt(str, 16)\n } else {\n length = buf[context.offset]\n context.offset++\n }\n\n return length\n}\n\nfunction readSequence (buf: Uint8Array, context: Context): any[] {\n readLength(buf, context)\n const entries: any[] = []\n\n while (true) {\n if (context.offset >= buf.byteLength) {\n break\n }\n\n const result = decodeDer(buf, context)\n\n if (result === null) {\n break\n }\n\n entries.push(result)\n }\n\n return entries\n}\n\nfunction readInteger (buf: Uint8Array, context: Context): Uint8Array {\n const length = readLength(buf, context)\n const start = context.offset\n const end = context.offset + length\n\n const vals: number[] = []\n\n for (let i = start; i < end; i++) {\n if (i === start && buf[i] === 0) {\n continue\n }\n\n vals.push(buf[i])\n }\n\n context.offset += length\n\n return Uint8Array.from(vals)\n}\n\nfunction readObjectIdentifier (buf: Uint8Array, context: Context): string {\n const count = readLength(buf, context)\n const finalOffset = context.offset + count\n\n const byte = buf[context.offset]\n context.offset++\n\n let val1 = 0\n let val2 = 0\n\n if (byte < 40) {\n val1 = 0\n val2 = byte\n } else if (byte < 80) {\n val1 = 1\n val2 = byte - 40\n } else {\n val1 = 2\n val2 = byte - 80\n }\n\n let oid = `${val1}.${val2}`\n let num: number[] = []\n\n while (context.offset < finalOffset) {\n const byte = buf[context.offset]\n context.offset++\n\n // remove msb\n num.push(byte & 0b01111111)\n\n if (byte < 128) {\n num.reverse()\n\n // reached the end of the encoding\n let val = 0\n\n for (let i = 0; i < num.length; i++) {\n val += num[i] << (i * 7)\n }\n\n oid += `.${val}`\n num = []\n }\n }\n\n return oid\n}\n\nfunction readNull (buf: Uint8Array, context: Context): null {\n context.offset++\n\n return null\n}\n\nfunction readBitString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const unusedBits = buf[context.offset]\n context.offset++\n const bytes = buf.subarray(context.offset, context.offset + length - 1)\n context.offset += length\n\n if (unusedBits !== 0) {\n // need to shift all bytes along by this many bits\n throw new Error('Unused bits in bit string is unimplemented')\n }\n\n return bytes\n}\n\nfunction readOctetString (buf: Uint8Array, context: Context): any {\n const length = readLength(buf, context)\n const bytes = buf.subarray(context.offset, context.offset + length)\n context.offset += length\n\n return bytes\n}\n\nfunction encodeNumber (value: number): Uint8ArrayList {\n let number = value.toString(16)\n\n if (number.length % 2 === 1) {\n number = '0' + number\n }\n\n const array = new Uint8ArrayList()\n\n for (let i = 0; i < number.length; i += 2) {\n array.append(Uint8Array.from([parseInt(`${number[i]}${number[i + 1]}`, 16)]))\n }\n\n return array\n}\n\nfunction encodeLength (bytes: { byteLength: number }): Uint8Array | Uint8ArrayList {\n if (bytes.byteLength < 128) {\n return Uint8Array.from([bytes.byteLength])\n }\n\n // long length\n const length = encodeNumber(bytes.byteLength)\n\n return new Uint8ArrayList(\n Uint8Array.from([\n length.byteLength | LONG_LENGTH_MASK\n ]),\n length\n )\n}\n\nexport function encodeInteger (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n const contents = new Uint8ArrayList()\n\n const mask = 0b10000000\n const positive = (value.subarray()[0] & mask) === mask\n\n if (positive) {\n contents.append(Uint8Array.from([0]))\n }\n\n contents.append(value)\n\n return new Uint8ArrayList(\n Uint8Array.from([0x02]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeBitString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n // unused bits is always 0 with full-byte-only values\n const unusedBits = Uint8Array.from([0])\n\n const contents = new Uint8ArrayList(\n unusedBits,\n value\n )\n\n return new Uint8ArrayList(\n Uint8Array.from([0x03]),\n encodeLength(contents),\n contents\n )\n}\n\nexport function encodeOctetString (value: Uint8Array | Uint8ArrayList): Uint8ArrayList {\n return new Uint8ArrayList(\n Uint8Array.from([0x04]),\n encodeLength(value),\n value\n )\n}\n\nexport function encodeSequence (values: Array<Uint8Array | Uint8ArrayList>, tag = 0x30): Uint8ArrayList {\n const output = new Uint8ArrayList()\n\n for (const buf of values) {\n output.append(\n buf\n )\n }\n\n return new Uint8ArrayList(\n Uint8Array.from([tag]),\n encodeLength(output),\n output\n )\n}\n", "import type { JWKKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport type Curve = 'P-256' | 'P-384' | 'P-521'\n\nexport const ECDSA_P_256_OID = '1.2.840.10045.3.1.7'\nexport const ECDSA_P_384_OID = '1.3.132.0.34'\nexport const ECDSA_P_521_OID = '1.3.132.0.35'\n\nexport async function generateECDSAKey (curve: Curve = 'P-256'): Promise<JWKKeyPair> {\n const keyPair = await crypto.subtle.generateKey({\n name: 'ECDSA',\n namedCurve: curve\n }, true, ['sign', 'verify'])\n\n return {\n publicKey: await crypto.subtle.exportKey('jwk', keyPair.publicKey),\n privateKey: await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n }\n}\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n\n return crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Uint8ArrayList } from 'uint8arraylist'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { decodeDer, encodeBitString, encodeInteger, encodeOctetString, encodeSequence } from '../rsa/der.js'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass, ECDSAPublicKey as ECDSAPublicKeyClass } from './ecdsa.js'\nimport { generateECDSAKey } from './index.js'\nimport type { Curve } from '../ecdh/index.js'\nimport type { ECDSAPublicKey, ECDSAPrivateKey } from '@libp2p/interface'\n\n// 1.2.840.10045.3.1.7 prime256v1 (ANSI X9.62 named elliptic curve)\nconst OID_256 = Uint8Array.from([0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07])\n// 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)\nconst OID_384 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22])\n// 1.3.132.0.35 secp521r1 (SECG (Certicom) named elliptic curve)\nconst OID_521 = Uint8Array.from([0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23])\n\nconst P_256_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-256'\n}\n\nconst P_384_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-384'\n}\n\nconst P_521_KEY_JWK = {\n ext: true,\n kty: 'EC',\n crv: 'P-521'\n}\n\nconst P_256_KEY_LENGTH = 32\nconst P_384_KEY_LENGTH = 48\nconst P_521_KEY_LENGTH = 66\n\nexport function unmarshalECDSAPrivateKey (bytes: Uint8Array): ECDSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPrivateKey(message)\n}\n\nexport function pkiMessageToECDSAPrivateKey (message: any): ECDSAPrivateKey {\n const privateKey = message[1]\n const d = uint8ArrayToString(privateKey, 'base64url')\n const coordinates: Uint8Array = message[2][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (privateKey.byteLength === P_256_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_384_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n if (privateKey.byteLength === P_521_KEY_LENGTH) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPrivateKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['sign'],\n d,\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`Private key length was wrong length, got ${privateKey.byteLength}, expected 32, 48 or 66`)\n}\n\nexport function unmarshalECDSAPublicKey (bytes: Uint8Array): ECDSAPublicKey {\n const message = decodeDer(bytes)\n\n return pkiMessageToECDSAPublicKey(message)\n}\n\nexport function pkiMessageToECDSAPublicKey (message: any): ECDSAPublicKey {\n const coordinates = message[1][1][0]\n const offset = 1\n let x: string\n let y: string\n\n if (coordinates.byteLength === ((P_256_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_256_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_256_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_256_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_384_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_384_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_384_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_384_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n if (coordinates.byteLength === ((P_521_KEY_LENGTH * 2) + 1)) {\n x = uint8ArrayToString(coordinates.subarray(offset, offset + P_521_KEY_LENGTH), 'base64url')\n y = uint8ArrayToString(coordinates.subarray(offset + P_521_KEY_LENGTH), 'base64url')\n\n return new ECDSAPublicKeyClass({\n ...P_521_KEY_JWK,\n key_ops: ['verify'],\n x,\n y\n })\n }\n\n throw new InvalidParametersError(`coordinates were wrong length, got ${coordinates.byteLength}, expected 65, 97 or 133`)\n}\n\nexport function privateKeyToPKIMessage (privateKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeOctetString(uint8ArrayFromString(privateKey.d ?? '', 'base64url')), // body\n encodeSequence([ // PKIProtection\n getOID(privateKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(privateKey.x ?? '', 'base64url'),\n uint8ArrayFromString(privateKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nexport function publicKeyToPKIMessage (publicKey: JsonWebKey): Uint8Array {\n return encodeSequence([\n encodeInteger(Uint8Array.from([1])), // header\n encodeSequence([ // PKIProtection\n getOID(publicKey.crv)\n ], 0xA0),\n encodeSequence([ // extraCerts\n encodeBitString(\n new Uint8ArrayList(\n Uint8Array.from([0x04]),\n uint8ArrayFromString(publicKey.x ?? '', 'base64url'),\n uint8ArrayFromString(publicKey.y ?? '', 'base64url')\n )\n )\n ], 0xA1)\n ]).subarray()\n}\n\nfunction getOID (curve?: string): Uint8Array {\n if (curve === 'P-256') {\n return OID_256\n }\n\n if (curve === 'P-384') {\n return OID_384\n }\n\n if (curve === 'P-521') {\n return OID_521\n }\n\n throw new InvalidParametersError(`Invalid curve ${curve}`)\n}\n\nexport async function generateECDSAKeyPair (curve: Curve = 'P-256'): Promise<ECDSAPrivateKey> {\n const key = await generateECDSAKey(curve)\n\n return new ECDSAPrivateKeyClass(key.privateKey)\n}\n\nexport function ensureECDSAKey (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { privateKeyToPKIMessage, publicKeyToPKIMessage } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { ECDSAPublicKey as ECDSAPublicKeyInterface, ECDSAPrivateKey as ECDSAPrivateKeyInterface } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class ECDSAPublicKey implements ECDSAPublicKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = publicKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\n }\n}\n\nexport class ECDSAPrivateKey implements ECDSAPrivateKeyInterface {\n public readonly type = 'ECDSA'\n public readonly jwk: JsonWebKey\n public readonly publicKey: ECDSAPublicKey\n private _raw?: Uint8Array\n\n constructor (jwk: JsonWebKey) {\n this.jwk = jwk\n this.publicKey = new ECDSAPublicKey({\n crv: jwk.crv,\n ext: jwk.ext,\n key_ops: ['verify'],\n kty: 'EC',\n x: jwk.x,\n y: jwk.y\n })\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = privateKeyToPKIMessage(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n async sign (message: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\n }\n}\n", "/**\n * Internal webcrypto alias.\n * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n * See utils.ts for details.\n * @module\n */\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto: any =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { type Input, Hash, abytes, aexists, aoutput, clean, createView, toBytes } from './utils.ts';\n\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n/** Choice: a ? b : c */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): Uint8Array {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV: Uint32Array = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, rotr } from './utils.ts';\n\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n\n constructor(outputLen: number = 32) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\nexport class SHA224 extends SHA256 {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor(outputLen: number = 64) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nexport class SHA384 extends SHA512 {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\nexport class SHA512_224 extends SHA512 {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\nexport class SHA512_256 extends SHA512 {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256: CHash = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash = /* @__PURE__ */ createHasher(() => new SHA224());\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash = /* @__PURE__ */ createHasher(() => new SHA384());\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256: CHash = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224: CHash = /* @__PURE__ */ createHasher(() => new SHA512_224());\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\nexport function abytes(item: unknown): void {\n if (!isBytes(item)) throw new Error('Uint8Array expected');\n}\n\nexport function abool(title: string, value: boolean): void {\n if (typeof value !== 'boolean') throw new Error(title + ' boolean expected, got ' + value);\n}\n\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean =\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Is positive bigint\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n: bigint): number {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\nconst u8n = (len: number) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr: ArrayLike<number>) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n(0)) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any): boolean => typeof val === 'bigint',\n function: (val: any): boolean => typeof val === 'function',\n boolean: (val: any): boolean => typeof val === 'boolean',\n string: (val: any): boolean => typeof val === 'string',\n stringOrUint8Array: (val: any): boolean => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any): boolean => Number.isSafeInteger(val),\n array: (val: any): boolean => Array.isArray(val),\n field: (val: any, object: any): any => (object as any).Fp.isValid(val),\n hash: (val: any): boolean => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n): T {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function') throw new Error('invalid validator function');\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n 'param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n\n/**\n * throws not implemented error\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized<T extends object, R, O extends any[]>(\n fn: (arg: T, ...args: O) => R\n): (arg: T, ...args: O) => R {\n const map = new WeakMap<T, R>();\n return (arg: T, ...args: O): R => {\n const val = map.get(arg);\n if (val !== undefined) return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n", "/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport {\n bitMask,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from './utils.ts';\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n =/* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n) throw new Error('invalid modulus');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // Do expensive precomputation step\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p-1 == q*(2^s) with q odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n let Z = _2n;\n const _Fp = Field(P);\n while (Z < P && FpIsSquare(_Fp, Z)) {\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (!FpIsSquare(Fp, n)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: test on Fp2 and others\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n // (4. If t = 0, return r = 0)\n // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO;\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,\n // otherwise there will be overflow.\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (P + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const c1 = (P - _5n) / _8n;\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Field is not always over prime: for example, Fp2 has ORDER(q)=p^m. */\nexport interface IField<T> {\n ORDER: bigint;\n isLE: boolean;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>): IField<T> {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(Fp: IField<T>, num: T, power: bigint): T {\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return Fp.ONE;\n if (power === _1n) return num;\n // @ts-ignore\n let p = Fp.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = Fp.mul(p, d);\n d = Fp.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch<T>(Fp: IField<T>, nums: T[], passZero = false): T[] {\n const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = acc;\n return Fp.mul(acc, num);\n }, Fp.ONE);\n // Invert last element\n const invertedAcc = Fp.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (Fp.is0(num)) return acc;\n inverted[i] = Fp.mul(acc, inverted[i]);\n return Fp.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n// TODO: remove\nexport function FpDiv<T>(Fp: IField<T>, lhs: T, rhs: T | bigint): T {\n return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p)..\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n */\nexport function FpLegendre<T>(Fp: IField<T>, n: T): number {\n const legc = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, legc);\n const yes = Fp.eql(powered, Fp.ONE);\n const zero = Fp.eql(powered, Fp.ZERO);\n const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n if (!yes && !zero && !no) throw new Error('Cannot find square root: probably non-prime P');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(Fp: IField<T>, n: T): boolean {\n const l = FpLegendre(Fp, n);\n return l === 0 || l === 1;\n}\n\n// CURVE.n lengths\nexport function nLength(\n n: bigint,\n nBitLength?: number\n): {\n nBitLength: number;\n nByteLength: number;\n} {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP: ReturnType<typeof FpSqrt>; // cached sqrtP\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt:\n redef.sqrt ||\n ((n) => {\n if (!sqrtP) sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n // TODO: we don't need it here, move out to separate fn\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov: (a, b, c) => (c ? b : a),\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T): T {\n if (!Fp.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(\n 'hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen\n );\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { type IField, nLength, validateField } from './modular.ts';\nimport { bitLen, bitMask, validateObject } from './utils.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\nfunction constTimeNegate<T extends Group<T>>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits */\nexport type WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake random statement for noise\n const offsetF = offsetStart; // fake offset for noise\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n return pointWindowSizes.get(P) || 1;\n}\n\nexport type IWNAF<T extends Group<T>> = {\n constTimeNegate: <T extends Group<T>>(condition: boolean, item: T) => T;\n hasPrecomputes(elm: T): boolean;\n unsafeLadder(elm: T, n: bigint, p?: T): T;\n precomputeWindow(elm: T, W: number): Group<T>[];\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[];\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T };\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc?: T): T;\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T };\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T;\n setWindowSize(P: T, W: number): void;\n};\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number): IWNAF<T> {\n return {\n constTimeNegate,\n\n hasPrecomputes(elm: T) {\n return getW(elm) !== 1;\n },\n\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint, p = c.ZERO) {\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // Smaller version:\n // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n // TODO: check the scalar is less than group order?\n // wNAF behavior is undefined otherwise. But have to carefully remove\n // other checks before wNAF. ORDER == bits here.\n // Accumulators\n let p = c.ZERO;\n let f = c.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n }\n }\n // Return both real and fake points: JIT won't eliminate f.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W: number, precomputes: T[], n: bigint, acc: T = c.ZERO): T {\n const wo = calcWOpts(W, bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n return acc;\n },\n\n getPrecomputes(W: number, P: T, transform: Mapper<T>): T[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n\n wNAFCached(P: T, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n\n wNAFCachedUnsafe(P: T, n: bigint, transform: Mapper<T>, prev?: T): T {\n const W = getW(P);\n if (W === 1) return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n\n setWindowSize(P: T, W: number) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n scalars: bigint[]\n): T {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as T;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe<T extends Group<T>>(\n c: GroupConstructor<T>,\n fieldN: IField<bigint>,\n points: T[],\n windowSize: number\n): (scalars: bigint[]) => T {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: T) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): T => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/**\n * Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n * Though generator can be different (Fp2 / Fp6 for BLS).\n */\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(\n curve: BasicCurve<FP> & T\n): Readonly<\n {\n readonly nBitLength: number;\n readonly nByteLength: number;\n } & BasicCurve<FP> &\n T & {\n p: bigint;\n }\n> {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/**\n * Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2.\n * For design rationale of types / exports, see weierstrass module documentation.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n pippenger, validateBasic, wNAF,\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor\n} from './curve.ts';\nimport { Field, FpInvertBatch, mod } from './modular.ts';\n// prettier-ignore\nimport {\n abool, aInRange, bytesToHex, bytesToNumberLE, concatBytes,\n ensureBytes, memoized, numberToBytesLE, validateObject,\n type FHash, type Hex\n} from './utils.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n/** Edwards curves must declare params a & d. */\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\nexport type CurveTypeWithLength = Readonly<CurveType & { nByteLength: number; nBitLength: number }>;\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType): CurveTypeWithLength {\n const opts = validateBasic(curve);\n validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n _setWindowSize(windowSize: number): void;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n msm(points: ExtPointType[], scalars: bigint[]): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n precompute: (windowSize?: number, point?: ExtPointType) => ExtPointType;\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool('phflag', phflag);\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n }\n\n function aextpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n\n constructor(ex: bigint, ey: bigint, ez: bigint, et: bigint) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez, true);\n aCoordinate('t', et);\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.ez)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aextpoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aextpoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar: bigint, acc = Point.ZERO): Point {\n const n = scalar;\n aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.is0() || n === _1n) return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('pointHex.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex): Point {\n const { scalar } = getPrivateScalar(privKey);\n return G.multiply(scalar); // reduced one call of `toRawBytes`\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(bytesToNumberLE(hash));\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Hex) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n // Convenience method that creates public key from scalar. RFC8032 5.1.5\n function getExtendedPublicKey(key: Hex) {\n const { head, prefix, scalar } = getPrivateScalar(key);\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = concatBytes(R, numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = bytesToNumberLE(sig.slice(len, 2 * len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n /** ed25519 priv keys are uniform 32b. No need to check for modulo bias, like in secp256k1. */\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point: ExtPointType = Point.BASE): ExtPointType {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { type AffinePoint, type Group, pippenger } from './abstract/curve.ts';\nimport { type CurveFn, type ExtPointType, twistedEdwards } from './abstract/edwards.ts';\nimport {\n createHasher,\n expand_message_xmd,\n type Hasher,\n type htfBasicOpts,\n type HTFMethod,\n} from './abstract/hash-to-curve.ts';\nimport { Field, FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.ts';\nimport { montgomery, type CurveFn as XCurveFn } from './abstract/montgomery.ts';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n type Hex,\n numberToBytesLE,\n} from './abstract/utils.ts';\n\n// 2n**255n - 19n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n/** Weird / bogus points, useful for debugging. */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Removing Fp.create() will still work, and is 10% faster on sign\n a: Fp.create(BigInt(-1)),\n // d is -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 2n**255n - 19n\n Fp,\n // Subgroup order 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n h: _8n,\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph: CurveFn = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519: XCurveFn = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery: typeof edwardsToMontgomeryPub = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\nexport const ed25519_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() => ed25519_hasher.hashToCurve)();\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n ed25519_hasher.encodeToCurve)();\n\nfunction aristp(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n private readonly ep: ExtendedPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep: ExtendedPoint) {\n this.ep = ep;\n }\n\n static fromAffine(ap: AffinePoint<bigint>): RistPoint {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n static msm(points: RistPoint[], scalars: bigint[]): RistPoint {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n aristp(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n aristp(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint: typeof RistPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts): RistPoint => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\n/** @deprecated */\nexport const hash_to_ristretto255: (msg: Uint8Array, options: htfBasicOpts) => RistPoint =\n hashToRistretto255; // legacy\n", "import { ed25519 as ed } from '@noble/curves/ed25519'\nimport type { Uint8ArrayKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32\nconst PRIVATE_KEY_BYTE_LENGTH = 64 // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey()\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed (seed: Uint8Array): Uint8ArrayKeyPair {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.')\n } else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.')\n }\n\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed\n const publicKey = ed.getPublicKey(privateKeyRaw)\n\n const privateKey = concatKeys(privateKeyRaw, publicKey)\n\n return {\n privateKey,\n publicKey\n }\n}\n\nexport function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH)\n\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw)\n}\n\nexport function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nfunction concatKeys (privateKeyRaw: Uint8Array, publicKey: Uint8Array): Uint8Array {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH)\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i]\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i]\n }\n return privateKey\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { type Digest } from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Ed25519PublicKey implements Ed25519PublicKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n\n constructor (key: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.publicKeyLength)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return crypto.hashAndVerify(this.raw, sig, data)\n }\n}\n\nexport class Ed25519PrivateKey implements Ed25519PrivateKeyInterface {\n public readonly type = 'Ed25519'\n public readonly raw: Uint8Array\n public readonly publicKey: Ed25519PublicKey\n\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor (key: Uint8Array, publicKey: Uint8Array) {\n this.raw = ensureEd25519Key(key, crypto.privateKeyLength)\n this.publicKey = new Ed25519PublicKey(publicKey)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array {\n return crypto.hashAndSign(this.raw, message)\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { Ed25519PublicKey as Ed25519PublicKeyClass, Ed25519PrivateKey as Ed25519PrivateKeyClass } from './ed25519.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey, Ed25519PrivateKey } from '@libp2p/interface'\n\nexport function unmarshalEd25519PrivateKey (bytes: Uint8Array): Ed25519PrivateKey {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength + crypto.publicKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n }\n\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength)\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength)\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength)\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes)\n}\n\nexport function unmarshalEd25519PublicKey (bytes: Uint8Array): Ed25519PublicKey {\n bytes = ensureEd25519Key(bytes, crypto.publicKeyLength)\n return new Ed25519PublicKeyClass(bytes)\n}\n\nexport async function generateEd25519KeyPair (): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKey()\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport async function generateEd25519KeyPairFromSeed (seed: Uint8Array): Promise<Ed25519PrivateKey> {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed)\n return new Ed25519PrivateKeyClass(privateKey, publicKey)\n}\n\nexport function ensureEd25519Key (key: Uint8Array, length: number): Uint8Array {\n key = Uint8Array.from(key ?? [])\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`)\n }\n return key\n}\n", "/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst N1 = Math.pow(2, 7)\nconst N2 = Math.pow(2, 14)\nconst N3 = Math.pow(2, 21)\nconst N4 = Math.pow(2, 28)\nconst N5 = Math.pow(2, 35)\nconst N6 = Math.pow(2, 42)\nconst N7 = Math.pow(2, 49)\n\n/** Most significant bit of a byte */\nconst MSB = 0x80\n/** Rest of the bits in a byte */\nconst REST = 0x7f\n\nexport function encodingLength (value: number): number {\n if (value < N1) {\n return 1\n }\n\n if (value < N2) {\n return 2\n }\n\n if (value < N3) {\n return 3\n }\n\n if (value < N4) {\n return 4\n }\n\n if (value < N5) {\n return 5\n }\n\n if (value < N6) {\n return 6\n }\n\n if (value < N7) {\n return 7\n }\n\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint')\n }\n\n return 8\n}\n\nexport function encodeUint8Array (value: number, buf: Uint8Array, offset: number = 0): Uint8Array {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB\n value /= 128\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB\n value >>>= 7\n }\n case 1: {\n buf[offset++] = (value & 0xFF)\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function encodeUint8ArrayList (value: number, buf: Uint8ArrayList, offset: number = 0): Uint8ArrayList {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value /= 128\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB)\n value >>>= 7\n }\n case 1: {\n buf.set(offset++, (value & 0xFF))\n value >>>= 7\n break\n }\n default: throw new Error('unreachable')\n }\n return buf\n}\n\nexport function decodeUint8Array (buf: Uint8Array, offset: number): number {\n let b = buf[offset]\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 1]\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 2]\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 3]\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 4]\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 5]\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 6]\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf[offset + 7]\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function decodeUint8ArrayList (buf: Uint8ArrayList, offset: number): number {\n let b = buf.get(offset)\n let res = 0\n\n res += b & REST\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 1)\n res += (b & REST) << 7\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 2)\n res += (b & REST) << 14\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 3)\n res += (b & REST) << 21\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 4)\n res += (b & REST) * N4\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 5)\n res += (b & REST) * N5\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 6)\n res += (b & REST) * N6\n if (b < MSB) {\n return res\n }\n\n b = buf.get(offset + 7)\n res += (b & REST) * N7\n if (b < MSB) {\n return res\n }\n\n throw new RangeError('Could not decode varint')\n}\n\nexport function encode (value: number): Uint8Array\nexport function encode (value: number, buf: Uint8Array, offset?: number): Uint8Array\nexport function encode (value: number, buf: Uint8ArrayList, offset?: number): Uint8ArrayList\nexport function encode <T extends Uint8Array | Uint8ArrayList = Uint8Array> (value: number, buf?: T, offset: number = 0): T {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value)) as T\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset) as T\n } else {\n return encodeUint8ArrayList(value, buf, offset) as T\n }\n}\n\nexport function decode (buf: Uint8ArrayList | Uint8Array, offset: number = 0): number {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset)\n } else {\n return decodeUint8ArrayList(buf, offset)\n }\n}\n", "const f32 = new Float32Array([-0])\nconst f8b = new Uint8Array(f32.buffer)\n\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[0]\n buf[pos + 1] = f8b[1]\n buf[pos + 2] = f8b[2]\n buf[pos + 3] = f8b[3]\n}\n\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE (val: number, buf: Uint8Array, pos: number): void {\n f32[0] = val\n buf[pos] = f8b[3]\n buf[pos + 1] = f8b[2]\n buf[pos + 2] = f8b[1]\n buf[pos + 3] = f8b[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE (buf: Uint8Array, pos: number): number {\n f8b[0] = buf[pos]\n f8b[1] = buf[pos + 1]\n f8b[2] = buf[pos + 2]\n f8b[3] = buf[pos + 3]\n return f32[0]\n}\n\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE (buf: Uint8Array, pos: number): number {\n f8b[3] = buf[pos]\n f8b[2] = buf[pos + 1]\n f8b[1] = buf[pos + 2]\n f8b[0] = buf[pos + 3]\n return f32[0]\n}\n\nconst f64 = new Float64Array([-0])\nconst d8b = new Uint8Array(f64.buffer)\n\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[0]\n buf[pos + 1] = d8b[1]\n buf[pos + 2] = d8b[2]\n buf[pos + 3] = d8b[3]\n buf[pos + 4] = d8b[4]\n buf[pos + 5] = d8b[5]\n buf[pos + 6] = d8b[6]\n buf[pos + 7] = d8b[7]\n}\n\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE (val: number, buf: Uint8Array, pos: number): void {\n f64[0] = val\n buf[pos] = d8b[7]\n buf[pos + 1] = d8b[6]\n buf[pos + 2] = d8b[5]\n buf[pos + 3] = d8b[4]\n buf[pos + 4] = d8b[3]\n buf[pos + 5] = d8b[2]\n buf[pos + 6] = d8b[1]\n buf[pos + 7] = d8b[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE (buf: Uint8Array, pos: number): number {\n d8b[0] = buf[pos]\n d8b[1] = buf[pos + 1]\n d8b[2] = buf[pos + 2]\n d8b[3] = buf[pos + 3]\n d8b[4] = buf[pos + 4]\n d8b[5] = buf[pos + 5]\n d8b[6] = buf[pos + 6]\n d8b[7] = buf[pos + 7]\n return f64[0]\n}\n\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE (buf: Uint8Array, pos: number): number {\n d8b[7] = buf[pos]\n d8b[6] = buf[pos + 1]\n d8b[5] = buf[pos + 2]\n d8b[4] = buf[pos + 3]\n d8b[3] = buf[pos + 4]\n d8b[2] = buf[pos + 5]\n d8b[1] = buf[pos + 6]\n d8b[0] = buf[pos + 7]\n return f64[0]\n}\n", "// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER)\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER)\n\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n public lo: number\n public hi: number\n\n constructor (lo: number, hi: number) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits\n */\n this.lo = lo | 0\n\n /**\n * High bits\n */\n this.hi = hi | 0\n }\n\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber (unsigned: boolean = false): number {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(lo + hi * 4294967296)\n }\n return this.lo + this.hi * 4294967296\n }\n\n /**\n * Converts this long bits to a bigint\n */\n toBigInt (unsigned: boolean = false): bigint {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0\n let hi = ~this.hi >>> 0\n if (lo === 0) {\n hi = hi + 1 >>> 0\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n))\n }\n\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n)\n }\n\n /**\n * Converts this long bits to a string\n */\n toString (unsigned: boolean = false): string {\n return this.toBigInt(unsigned).toString()\n }\n\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode (): this {\n const mask = this.hi >> 31\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0\n this.lo = (this.lo << 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode (): this {\n const mask = -(this.lo & 1)\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0\n this.hi = (this.hi >>> 1 ^ mask) >>> 0\n return this\n }\n\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length (): number {\n const part0 = this.lo\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0\n const part2 = this.hi >>> 24\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt (value: bigint): LongBits {\n if (value === 0n) {\n return zero\n }\n\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value))\n }\n\n const negative = value < 0n\n\n if (negative) {\n value = -value\n }\n\n let hi = value >> 32n\n let lo = value - (hi << 32n)\n\n if (negative) {\n hi = ~hi | 0n\n lo = ~lo | 0n\n\n if (++lo > TWO_32) {\n lo = 0n\n if (++hi > TWO_32) { hi = 0n }\n }\n }\n\n return new LongBits(Number(lo), Number(hi))\n }\n\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber (value: number): LongBits {\n if (value === 0) { return zero }\n const sign = value < 0\n if (sign) { value = -value }\n let lo = value >>> 0\n let hi = (value - lo) / 4294967296 >>> 0\n if (sign) {\n hi = ~hi >>> 0\n lo = ~lo >>> 0\n if (++lo > 4294967295) {\n lo = 0\n if (++hi > 4294967295) { hi = 0 }\n }\n }\n return new LongBits(lo, hi)\n }\n\n /**\n * Constructs new long bits from a number, long or string\n */\n static from (value: bigint | number | string | { low: number, high: number }): LongBits {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value)\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value)\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value))\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero\n }\n}\n\nconst zero = new LongBits(0, 0)\nzero.toBigInt = function () { return 0n }\nzero.zzEncode = zero.zzDecode = function () { return this }\nzero.length = function () { return 1 }\n\nconst TWO_32 = 4294967296n\n", "/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length (string: string): number {\n let len = 0\n let c = 0\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i)\n\n if (c < 128) {\n len += 1\n } else if (c < 2048) {\n len += 2\n } else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i\n len += 4\n } else {\n len += 3\n }\n }\n\n return len\n}\n\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read (buffer: Uint8Array, start: number, end: number): string {\n const len = end - start\n\n if (len < 1) {\n return ''\n }\n\n let parts: string[] | undefined\n const chunk: number[] = []\n let i = 0 // char offset\n let t: number // temporary\n\n while (start < end) {\n t = buffer[start++]\n\n if (t < 128) {\n chunk[i++] = t\n } else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63\n } else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000\n chunk[i++] = 0xD800 + (t >> 10)\n chunk[i++] = 0xDC00 + (t & 1023)\n } else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63\n }\n\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk))\n i = 0\n }\n }\n\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)))\n }\n\n return parts.join('')\n }\n\n return String.fromCharCode.apply(String, chunk.slice(0, i))\n}\n\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write (string: string, buffer: Uint8Array, offset: number): number {\n const start = offset\n let c1 // character 1\n let c2 // character 2\n\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i)\n\n if (c1 < 128) {\n buffer[offset++] = c1\n } else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192\n buffer[offset++] = c1 & 63 | 128\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF)\n ++i\n buffer[offset++] = c1 >> 18 | 240\n buffer[offset++] = c1 >> 12 & 63 | 128\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n } else {\n buffer[offset++] = c1 >> 12 | 224\n buffer[offset++] = c1 >> 6 & 63 | 128\n buffer[offset++] = c1 & 63 | 128\n }\n }\n\n return offset - start\n}\n", "import { decodeUint8Array, encodingLength } from 'uint8-varint'\nimport { readFloatLE, readDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n", "import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n", "import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n", "import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n", "import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n", "import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n", "import { createCodec, CODEC_TYPES, type EncodeFunction, type DecodeFunction, type Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport enum KeyType {\n RSA = 'RSA',\n Ed25519 = 'Ed25519',\n secp256k1 = 'secp256k1',\n ECDSA = 'ECDSA'\n}\n\nenum __KeyTypeValues {\n RSA = 0,\n Ed25519 = 1,\n secp256k1 = 2,\n ECDSA = 3\n}\n\nexport namespace KeyType {\n export const codec = (): Codec<KeyType> => {\n return enumeration<KeyType>(__KeyTypeValues)\n }\n}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec<PublicKey>\n\n export const codec = (): Codec<PublicKey> => {\n if (_codec == null) {\n _codec = message<PublicKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PublicKey>): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey => {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec<PrivateKey>\n\n export const codec = (): Codec<PrivateKey> => {\n if (_codec == null) {\n _codec = message<PrivateKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PrivateKey>): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n}\n", "/**\n * Signing a message failed\n */\nexport class SigningError extends Error {\n constructor (message = 'An error occurred while signing a message') {\n super(message)\n this.name = 'SigningError'\n }\n}\n\n/**\n * Verifying a message signature failed\n */\nexport class VerificationError extends Error {\n constructor (message = 'An error occurred while verifying a message') {\n super(message)\n this.name = 'VerificationError'\n }\n}\n\n/**\n * WebCrypto was not available in the current context\n */\nexport class WebCryptoMissingError extends Error {\n constructor (message = 'Missing Web Crypto API') {\n super(message)\n this.name = 'WebCryptoMissingError'\n }\n}\n", "/* eslint-env browser */\n\nimport { WebCryptoMissingError } from '../errors.js'\n\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get (win = globalThis) {\n const nativeCrypto = win.crypto\n\n if (nativeCrypto?.subtle == null) {\n throw new WebCryptoMissingError(\n 'Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'\n )\n }\n\n return nativeCrypto\n }\n}\n", "import webcrypto from './webcrypto.js'\n\nexport default webcrypto\n", "import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { create } from 'multiformats/hashes/digest'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as pb from '../keys.js'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.js'\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from './rsa.js'\nimport { generateRSAKey, rsaKeySize } from './index.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { RSAPrivateKey, RSAPublicKey } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport const MAX_RSA_KEY_SIZE = 8192\nconst SHA2_256_CODE = 0x12\nconst MAX_RSA_JWK_SIZE = 1062\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToJwk(message)\n}\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1MessageToJwk (message: any): JsonWebKey {\n return {\n n: uint8ArrayToString(message[1], 'base64url'),\n e: uint8ArrayToString(message[2], 'base64url'),\n d: uint8ArrayToString(message[3], 'base64url'),\n p: uint8ArrayToString(message[4], 'base64url'),\n q: uint8ArrayToString(message[5], 'base64url'),\n dp: uint8ArrayToString(message[6], 'base64url'),\n dq: uint8ArrayToString(message[7], 'base64url'),\n qi: uint8ArrayToString(message[8], 'base64url'),\n kty: 'RSA'\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.d, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.p, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.q, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dp, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dq, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.qi, 'base64url'))\n ]).subarray()\n}\n\n/**\n * Convert a PKIX in ASN1 DER format to a JWK public key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToJwk(message)\n}\n\nexport function pkixMessageToJwk (message: any): JsonWebKey {\n const keys = decodeDer(message[1], {\n offset: 0\n })\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deeply property chains like this\n return {\n kty: 'RSA',\n n: uint8ArrayToString(\n keys[0],\n 'base64url'\n ),\n e: uint8ArrayToString(\n keys[1],\n 'base64url'\n )\n }\n}\n\n/**\n * Convert a JWK public key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url'))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey (bytes: Uint8Array): RSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToRSAPrivateKey(message)\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1MessageToRSAPrivateKey (message: any): RSAPrivateKey {\n const jwk = pkcs1MessageToJwk(message)\n\n return jwkToRSAPrivateKey(jwk)\n}\n\n/**\n * Turn a PKIX message into a PublicKey\n */\nexport function pkixToRSAPublicKey (bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n if (bytes.byteLength >= MAX_RSA_JWK_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large')\n }\n\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToRSAPublicKey(message, bytes, digest)\n}\n\nexport function pkixMessageToRSAPublicKey (message: any, bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n const jwk = pkixMessageToJwk(message)\n\n if (digest == null) {\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }))\n digest = create(SHA2_256_CODE, hash)\n }\n\n return new RSAPublicKeyClass(jwk, digest)\n}\n\nexport function jwkToRSAPrivateKey (jwk: JsonWebKey): RSAPrivateKey {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = jwkToJWKKeyPair(jwk)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\nexport async function generateRSAKeyPair (bits: number): Promise<RSAPrivateKey> {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = await generateRSAKey(bits)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair (key: JsonWebKey): JWKKeyPair {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter')\n }\n\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n }\n}\n", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport {\n SHA224 as SHA224n,\n sha224 as sha224n,\n SHA256 as SHA256n,\n sha256 as sha256n,\n} from './sha2.ts';\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256: typeof SHA256n = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256: typeof sha256n = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224: typeof SHA224n = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224: typeof sha224n = sha224n;\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { type Digest } from 'multiformats/hashes/digest'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { hashAndSign, utils, hashAndVerify } from './index.js'\nimport type { RSAPublicKey as RSAPublicKeyInterface, RSAPrivateKey as RSAPrivateKeyInterface } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class RSAPublicKey implements RSAPublicKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n private readonly _multihash: Digest<18, number>\n\n constructor (jwk: JsonWebKey, digest: Digest<18, number>) {\n this.jwk = jwk\n this._multihash = digest\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<18, number> {\n return this._multihash\n }\n\n toCID (): CID<unknown, 114, 18, 1> {\n return CID.createV1(114, this._multihash)\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean | Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data)\n }\n}\n\nexport class RSAPrivateKey implements RSAPrivateKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n public readonly publicKey: RSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: RSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.jwk, message)\n }\n}\n", "import { InvalidParametersError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../../random-bytes.js'\nimport webcrypto from '../../webcrypto/index.js'\nimport * as utils from './utils.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const RSAES_PKCS1_V1_5_OID = '1.2.840.113549.1.1.1'\nexport { utils }\n\nexport async function generateRSAKey (bits: number): Promise<JWKKeyPair> {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n\n const keys = await exportKey(pair)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n\n return webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n}\n\nasync function exportKey (pair: CryptoKeyPair): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required')\n }\n\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n}\n\nexport function rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes, type CHash, type Input } from './utils.ts';\n\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: Input): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array): void {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest(): Uint8Array {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): HMAC<T> {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac: {\n (hash: CHash, key: Input, message: Input): Uint8Array;\n create(hash: CHash, key: Input): HMAC<any>;\n} = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)\n * * n: Curve prime subgroup order, total count of valid points in the field\n * * Gx: Base point (x, y) aka generator point x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport {\n type AffinePoint, type BasicCurve, type Group, type GroupConstructor,\n pippenger, validateBasic, wNAF\n} from './curve.ts';\n// prettier-ignore\nimport {\n Field,\n FpInvertBatch,\n type IField, getMinHashLength, invert, mapHashToField, mod, validateField\n} from './modular.ts';\n// prettier-ignore\nimport {\n type CHash, type Hex, type PrivKey,\n aInRange, abool,\n bitMask,\n bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes,\n inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject\n} from './utils.ts';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\nexport type Entropy = Hex | boolean;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean; format?: 'compact' | 'der' | undefined };\n\nfunction validateSigVerOpts(opts: SignOpts | VerOpts) {\n if (opts.lowS !== undefined) abool('lowS', opts.lowS);\n if (opts.prehash !== undefined) abool('prehash', opts.prehash);\n}\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n toAffine(iz?: T): AffinePoint<T>;\n toHex(isCompressed?: boolean): string;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n\n assertValidity(): void;\n hasEvenY(): boolean;\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n msm(points: ProjPointType<T>[], scalars: bigint[]): ProjPointType<T>;\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nexport type CurvePointsTypeWithLength<T> = Readonly<\n CurvePointsType<T> & { nByteLength: number; nBitLength: number }\n>;\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>): CurvePointsTypeWithLength<T> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\nexport type IDER = {\n // asn.1 DER encoding utils\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array };\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string;\n decode(data: Uint8Array): bigint;\n };\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint };\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: Uint8Array): { v: Uint8Array; l: Uint8Array } {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 0b1000_0000); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: Uint8Array): bigint {\n const { Err: E } = DER;\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = ensureBytes('signature', hex);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula. Takes x, returns y\u00B2.\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (isBytes(key)) key = bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(\n 'invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key\n );\n }\n if (wrapPrivateKey) num = mod(num, N); // disabled by default, enabled for BLS\n aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n const toAffineMemo = memoized((p: Point, iz?: T): AffinePoint<T> => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE)) return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p: Point) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) \u220B (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType<T> {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n\n constructor(px: T, py: T, pz: T) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py) || Fp.is0(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n this.px = px;\n this.py = py;\n this.pz = pz;\n Object.freeze(this);\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = FpInvertBatch(\n Fp,\n points.map((p) => p.pz)\n );\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // Multiscalar Multiplication\n static msm(points: Point[], scalars: bigint[]): Point {\n return pippenger(Point, Fn, points, scalars);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n aprjpoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n is0() {\n return this.equals(Point.ZERO);\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n) return I;\n if (this.is0() || sc === _1n) return this;\n\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo, n: N } = CURVE;\n aInRange('scalar', scalar, _1n, N);\n let point: Point, fake: Point; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint<T> {\n return toAffineMemo(this, iz);\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n abool('isCompressed', isCompressed);\n return bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(\n curve: CurveType\n): Readonly<CurveType & { nByteLength: number; nBitLength: number }> {\n const opts = validateBasic(curve);\n validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = bytesToNumberBE(tail);\n if (!inRange(x, _1n, Fp.ORDER)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: bigint;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error(\n 'invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len\n );\n }\n },\n });\n const numToNByteHex = (num: bigint): string =>\n bytesToHex(numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n constructor(r: bigint, s: bigint, recovery?: number) {\n aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n this.r = r;\n this.s = s;\n if (recovery != null) this.recovery = recovery;\n Object.freeze(this);\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n /**\n * @todo remove\n * @deprecated\n */\n assertValidity(): void {}\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteHex(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig(this);\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteHex(this.r) + numToNByteHex(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // Our custom check \"just in case\"\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1\u22C5G - U2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || isBytes(sg);\n const isObj =\n !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (isObj) _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact') _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n }\n if (!_sig && format !== 'der') _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n return false;\n }\n if (!_sig) return false;\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: IField<T>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n x = Fp.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport type { CHash } from './abstract/utils.ts';\nimport { type CurveFn, type CurveType, weierstrass } from './abstract/weierstrass.ts';\n\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash: CHash): {\n hash: CHash;\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => Uint8Array;\n randomBytes: typeof randomBytes;\n} {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n/** Same API as @noble/hashes, with ability to create curve with custom hash */\nexport type CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport type CurveFnWithCreate = CurveFn & { create: (hash: CHash) => CurveFn };\n\nexport function createCurve(curveDef: CurveDef, defHash: CHash): CurveFnWithCreate {\n const create = (hash: CHash): CurveFn => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n", "/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve, type CurveFnWithCreate } from './_shortw_utils.ts';\nimport { createHasher, type Hasher, type HTFMethod, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mod, pow2 } from './abstract/modular.ts';\nimport type { Hex, PrivKey } from './abstract/utils.ts';\nimport {\n aInRange,\n bytesToNumberBE,\n concatBytes,\n ensureBytes,\n inRange,\n numberToBytesBE,\n} from './abstract/utils.ts';\nimport { mapToCurveSimpleSWU, type ProjPointType as PointType } from './abstract/weierstrass.ts';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\n/**\n * secp256k1 curve, ECDSA and ECDH methods.\n *\n * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1';\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n * ```\n */\nexport const secp256k1: CurveFnWithCreate = createCurve(\n {\n a: BigInt(0),\n b: BigInt(7),\n Fp: Fpk1,\n n: secp256k1N,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n aInRange('x', x, _1n, secp256k1P); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!inRange(r, _1n, secp256k1P)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!inRange(s, _1n, secp256k1N)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n utils: {\n randomPrivateKey: () => Uint8Array;\n lift_x: typeof lift_x;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n numberToBytesBE: typeof numberToBytesBE;\n bytesToNumberBE: typeof bytesToNumberBE;\n taggedHash: typeof taggedHash;\n mod: typeof mod;\n };\n};\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }))();\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: Hasher<bigint> = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n } as const\n ))();\n\nexport const hashToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.hashToCurve)();\n\nexport const encodeToCurve: HTFMethod<bigint> = /* @__PURE__ */ (() =>\n secp256k1_hasher.encodeToCurve)();\n", "import { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\n\nexport function base64urlToBuffer (str: string, len?: number): Uint8Array {\n let buf = uint8ArrayFromString(str, 'base64urlpad')\n\n if (len != null) {\n if (buf.length > len) throw new Error('byte array longer than desired length')\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf])\n }\n\n return buf\n}\n\nexport function isPromise <T = unknown> (thing: any): thing is Promise<T> {\n if (thing == null) {\n return false\n }\n\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function'\n}\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nconst PUBLIC_KEY_BYTE_LENGTH = 33\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign (key: Uint8Array, msg: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key).toDERRawBytes()\n } catch (err) {\n throw new SigningError(String(err))\n }\n}\n\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new VerificationError(String(err))\n })\n }\n\n try {\n return secp.verify(sig, p.digest, key)\n } catch (err) {\n throw new VerificationError(String(err))\n }\n}\n", "import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { validateSecp256k1PublicKey, compressSecp256k1PublicKey, computeSecp256k1PublicKey, validateSecp256k1PrivateKey } from './utils.js'\nimport { hashAndVerify, hashAndSign } from './index.js'\nimport type { Secp256k1PublicKey as Secp256k1PublicKeyInterface, Secp256k1PrivateKey as Secp256k1PrivateKeyInterface } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Secp256k1PublicKey implements Secp256k1PublicKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly _key: Uint8Array\n\n constructor (key: Uint8Array) {\n this._key = validateSecp256k1PublicKey(key)\n this.raw = compressSecp256k1PublicKey(this._key)\n }\n\n toMultihash (): Digest<0x0, number> {\n return identity.digest(publicKeyToProtobuf(this))\n }\n\n toCID (): CID<unknown, 114, 0x0, 1> {\n return CID.createV1(114, this.toMultihash())\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array): boolean {\n return hashAndVerify(this._key, sig, data)\n }\n}\n\nexport class Secp256k1PrivateKey implements Secp256k1PrivateKeyInterface {\n public readonly type = 'secp256k1'\n public readonly raw: Uint8Array\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (key: Uint8Array, publicKey?: Uint8Array) {\n this.raw = validateSecp256k1PrivateKey(key)\n this.publicKey = new Secp256k1PublicKey(publicKey ?? computeSecp256k1PublicKey(key))\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1'\nimport { Secp256k1PublicKey as Secp256k1PublicKeyClass, Secp256k1PrivateKey as Secp256k1PrivateKeyClass } from './secp256k1.js'\nimport type { Secp256k1PublicKey, Secp256k1PrivateKey } from '@libp2p/interface'\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32\n\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }\n\nexport function unmarshalSecp256k1PrivateKey (bytes: Uint8Array): Secp256k1PrivateKey {\n return new Secp256k1PrivateKeyClass(bytes)\n}\n\nexport function unmarshalSecp256k1PublicKey (bytes: Uint8Array): Secp256k1PublicKey {\n return new Secp256k1PublicKeyClass(bytes)\n}\n\nexport async function generateSecp256k1KeyPair (): Promise<Secp256k1PrivateKey> {\n const privateKeyBytes = generateSecp256k1PrivateKey()\n return new Secp256k1PrivateKeyClass(privateKeyBytes)\n}\n\nexport function compressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true)\n return point\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false)\n return point\n}\n\nexport function validateSecp256k1PrivateKey (key: Uint8Array): Uint8Array {\n try {\n secp.getPublicKey(key, true)\n\n return key\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function validateSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n try {\n secp.ProjectivePoint.fromHex(key)\n\n return key\n } catch (err) {\n throw new InvalidPublicKeyError(String(err))\n }\n}\n\nexport function computeSecp256k1PublicKey (privateKey: Uint8Array): Uint8Array {\n try {\n return secp.getPublicKey(privateKey, true)\n } catch (err) {\n throw new InvalidPrivateKeyError(String(err))\n }\n}\n\nexport function generateSecp256k1PrivateKey (): Uint8Array {\n return secp.utils.randomPrivateKey()\n}\n", "/**\n * @packageDocumentation\n *\n * ## Supported Key Types\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\nimport { InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { ECDSAPrivateKey as ECDSAPrivateKeyClass } from './ecdsa/ecdsa.js'\nimport { ECDSA_P_256_OID, ECDSA_P_384_OID, ECDSA_P_521_OID } from './ecdsa/index.js'\nimport { generateECDSAKeyPair, pkiMessageToECDSAPrivateKey, pkiMessageToECDSAPublicKey, unmarshalECDSAPrivateKey, unmarshalECDSAPublicKey } from './ecdsa/utils.js'\nimport { privateKeyLength as ed25519PrivateKeyLength, publicKeyLength as ed25519PublicKeyLength } from './ed25519/index.js'\nimport { generateEd25519KeyPair, generateEd25519KeyPairFromSeed, unmarshalEd25519PrivateKey, unmarshalEd25519PublicKey } from './ed25519/utils.js'\nimport * as pb from './keys.js'\nimport { decodeDer } from './rsa/der.js'\nimport { RSAES_PKCS1_V1_5_OID } from './rsa/index.js'\nimport { pkcs1ToRSAPrivateKey, pkixToRSAPublicKey, generateRSAKeyPair, pkcs1MessageToRSAPrivateKey, pkixMessageToRSAPublicKey, jwkToRSAPrivateKey } from './rsa/utils.js'\nimport { privateKeyLength as secp256k1PrivateKeyLength, publicKeyLength as secp256k1PublicKeyLength } from './secp256k1/index.js'\nimport { generateSecp256k1KeyPair, unmarshalSecp256k1PrivateKey, unmarshalSecp256k1PublicKey } from './secp256k1/utils.js'\nimport type { Curve } from './ecdsa/index.js'\nimport type { PrivateKey, PublicKey, KeyType, RSAPrivateKey, Secp256k1PrivateKey, Ed25519PrivateKey, Secp256k1PublicKey, Ed25519PublicKey, ECDSAPrivateKey, ECDSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport { generateEphemeralKeyPair } from './ecdh/index.js'\nexport type { Curve } from './ecdh/index.js'\nexport type { ECDHKey, EnhancedKey, EnhancedKeyPair, ECDHKeyPair } from './interface.js'\nexport { keyStretcher } from './key-stretcher.js'\n\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair (type: 'Ed25519'): Promise<Ed25519PrivateKey>\nexport async function generateKeyPair (type: 'secp256k1'): Promise<Secp256k1PrivateKey>\nexport async function generateKeyPair (type: 'ECDSA', curve?: Curve): Promise<ECDSAPrivateKey>\nexport async function generateKeyPair (type: 'RSA', bits?: number): Promise<RSAPrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number): Promise<PrivateKey>\nexport async function generateKeyPair (type: KeyType, bits?: number | string): Promise<unknown> {\n if (type === 'Ed25519') {\n return generateEd25519KeyPair()\n }\n\n if (type === 'secp256k1') {\n return generateSecp256k1KeyPair()\n }\n\n if (type === 'RSA') {\n return generateRSAKeyPair(toBits(bits))\n }\n\n if (type === 'ECDSA') {\n return generateECDSAKeyPair(toCurve(bits))\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\n/**\n * Generates a keypair of the given type from the passed seed. Currently only\n * supports Ed25519 keys.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed (type: 'Ed25519', seed: Uint8Array): Promise<Ed25519PrivateKey>\nexport async function generateKeyPairFromSeed <T extends KeyType> (type: T, seed: Uint8Array, bits?: number): Promise<never>\nexport async function generateKeyPairFromSeed (type: string, seed: Uint8Array): Promise<unknown> {\n if (type !== 'Ed25519') {\n throw new UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys')\n }\n\n return generateEd25519KeyPairFromSeed(seed)\n}\n\n/**\n * Converts a protobuf serialized public key into its representative object.\n *\n * For RSA public keys optionally pass the multihash digest of the public key if\n * it is known. If the digest is omitted it will be calculated which can be\n * expensive.\n *\n * For other key types the digest option is ignored.\n */\nexport function publicKeyFromProtobuf (buf: Uint8Array, digest?: Digest<18, number>): PublicKey {\n const { Type, Data } = pb.PublicKey.decode(buf)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.RSA:\n return pkixToRSAPublicKey(data, digest)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a public key from the raw key bytes\n */\nexport function publicKeyFromRaw (buf: Uint8Array): PublicKey {\n if (buf.byteLength === ed25519PublicKeyLength) {\n return unmarshalEd25519PublicKey(buf)\n } else if (buf.byteLength === secp256k1PublicKeyLength) {\n return unmarshalSecp256k1PublicKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[1]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPublicKey(message)\n }\n\n if (message[0]?.[0] === RSAES_PKCS1_V1_5_OID) {\n return pkixMessageToRSAPublicKey(message, buf)\n }\n\n throw new InvalidParametersError('Could not extract public key from raw bytes')\n}\n\n/**\n * Creates a public key from an identity multihash which contains a protobuf\n * encoded Ed25519 or secp256k1 public key.\n *\n * RSA keys are not supported as in practice we they are not stored in identity\n * multihash since the hash would be very large.\n */\nexport function publicKeyFromMultihash (digest: MultihashDigest<0x0>): Ed25519PublicKey | Secp256k1PublicKey | ECDSAPublicKey {\n const { Type, Data } = pb.PublicKey.decode(digest.digest)\n const data = Data ?? new Uint8Array()\n\n switch (Type) {\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPublicKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function publicKeyToProtobuf (key: PublicKey): Uint8Array {\n return pb.PublicKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport function privateKeyFromProtobuf (buf: Uint8Array): Ed25519PrivateKey | Secp256k1PrivateKey | RSAPrivateKey | ECDSAPrivateKey {\n const decoded = pb.PrivateKey.decode(buf)\n const data = decoded.Data ?? new Uint8Array()\n\n switch (decoded.Type) {\n case pb.KeyType.RSA:\n return pkcs1ToRSAPrivateKey(data)\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PrivateKey(data)\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PrivateKey(data)\n case pb.KeyType.ECDSA:\n return unmarshalECDSAPrivateKey(data)\n default:\n throw new UnsupportedKeyTypeError()\n }\n}\n\n/**\n * Creates a private key from the raw key bytes. For Ed25519 keys this requires\n * the public key to be appended to the private key otherwise we can't\n * differentiate between Ed25519 and secp256k1 keys as they are the same length.\n */\nexport function privateKeyFromRaw (buf: Uint8Array): PrivateKey {\n if (buf.byteLength === ed25519PrivateKeyLength) {\n return unmarshalEd25519PrivateKey(buf)\n } else if (buf.byteLength === secp256k1PrivateKeyLength) {\n return unmarshalSecp256k1PrivateKey(buf)\n }\n\n const message = decodeDer(buf)\n const ecdsaOid = message[2]?.[0]\n\n if (ecdsaOid === ECDSA_P_256_OID || ecdsaOid === ECDSA_P_384_OID || ecdsaOid === ECDSA_P_521_OID) {\n return pkiMessageToECDSAPrivateKey(message)\n }\n\n if (message.length > 8) {\n return pkcs1MessageToRSAPrivateKey(message)\n }\n\n throw new InvalidParametersError('Could not extract private key from raw bytes')\n}\n\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function privateKeyToProtobuf (key: PrivateKey): Uint8Array {\n return pb.PrivateKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n })\n}\n\nfunction toBits (bits: any): number {\n if (bits == null) {\n return 2048\n }\n\n return parseInt(bits, 10)\n}\n\nfunction toCurve (curve: any): Curve {\n if (curve === 'P-256' || curve == null) {\n return 'P-256'\n }\n\n if (curve === 'P-384') {\n return 'P-384'\n }\n\n if (curve === 'P-521') {\n return 'P-521'\n }\n\n throw new InvalidParametersError('Unsupported curve, should be P-256, P-384 or P-521')\n}\n\n/**\n * Convert a libp2p RSA or ECDSA private key to a WebCrypto CryptoKeyPair\n */\nexport async function privateKeyToCryptoKeyPair (privateKey: PrivateKey): Promise<CryptoKeyPair> {\n if (privateKey.type === 'RSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify'])\n }\n }\n\n if (privateKey.type === 'ECDSA') {\n return {\n privateKey: await crypto.subtle.importKey('jwk', privateKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.jwk.crv ?? 'P-256'\n }, true, ['sign']),\n publicKey: await crypto.subtle.importKey('jwk', privateKey.publicKey.jwk, {\n name: 'ECDSA',\n namedCurve: privateKey.publicKey.jwk.crv ?? 'P-256'\n }, true, ['verify'])\n }\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n\n/**\n * Convert a RSA or ECDSA WebCrypto CryptoKeyPair to a libp2p private key\n */\nexport async function privateKeyFromCryptoKeyPair (keyPair: CryptoKeyPair): Promise<PrivateKey> {\n if (keyPair.privateKey.algorithm.name === 'RSASSA-PKCS1-v1_5') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return jwkToRSAPrivateKey(jwk)\n }\n\n if (keyPair.privateKey.algorithm.name === 'ECDSA') {\n const jwk = await crypto.subtle.exportKey('jwk', keyPair.privateKey)\n\n return new ECDSAPrivateKeyClass(jwk)\n }\n\n throw new InvalidParametersError('Only RSA and ECDSA keys are supported')\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { peerIdSymbol } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { Ed25519PeerId as Ed25519PeerIdInterface, PeerIdType, RSAPeerId as RSAPeerIdInterface, URLPeerId as URLPeerIdInterface, Secp256k1PeerId as Secp256k1PeerIdInterface, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\n\ninterface PeerIdInit <DigestCode extends number> {\n type: PeerIdType\n multihash: MultihashDigest<DigestCode>\n}\n\ninterface RSAPeerIdInit {\n multihash: MultihashDigest<0x12>\n publicKey?: RSAPublicKey\n}\n\ninterface Ed25519PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Ed25519PublicKey\n}\n\ninterface Secp256k1PeerIdInit {\n multihash: MultihashDigest<0x0>\n publicKey: Secp256k1PublicKey\n}\n\nclass PeerIdImpl <DigestCode extends number> {\n public type: PeerIdType\n private readonly multihash: MultihashDigest<DigestCode>\n public readonly publicKey?: PublicKey\n private string?: string\n\n constructor (init: PeerIdInit<DigestCode>) {\n this.type = init.type\n this.multihash = init.multihash\n\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n })\n }\n\n get [Symbol.toStringTag] (): string {\n return `PeerId(${this.toString()})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1)\n }\n\n return this.string\n }\n\n toMultihash (): MultihashDigest<DigestCode> {\n return this.multihash\n }\n\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID (): CID<Uint8Array, 0x72, DigestCode, 1> {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash)\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals (id?: PeerId | Uint8Array | string): boolean {\n if (id == null) {\n return false\n }\n\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id)\n } else if (typeof id === 'string') {\n return this.toString() === id\n } else if (id?.toMultihash()?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.toMultihash().bytes)\n } else {\n throw new Error('not valid Id')\n }\n }\n\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect] (): string {\n return `PeerId(${this.toString()})`\n }\n}\n\nexport class RSAPeerId extends PeerIdImpl<0x12> implements RSAPeerIdInterface {\n public readonly type = 'RSA'\n public readonly publicKey?: RSAPublicKey\n\n constructor (init: RSAPeerIdInit) {\n super({ ...init, type: 'RSA' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Ed25519PeerId extends PeerIdImpl<0x0> implements Ed25519PeerIdInterface {\n public readonly type = 'Ed25519'\n public readonly publicKey: Ed25519PublicKey\n\n constructor (init: Ed25519PeerIdInit) {\n super({ ...init, type: 'Ed25519' })\n\n this.publicKey = init.publicKey\n }\n}\n\nexport class Secp256k1PeerId extends PeerIdImpl<0x0> implements Secp256k1PeerIdInterface {\n public readonly type = 'secp256k1'\n public readonly publicKey: Secp256k1PublicKey\n\n constructor (init: Secp256k1PeerIdInit) {\n super({ ...init, type: 'secp256k1' })\n\n this.publicKey = init.publicKey\n }\n}\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport class URLPeerId implements URLPeerIdInterface {\n readonly type = 'url'\n readonly multihash: MultihashDigest<0x0>\n readonly publicKey: undefined\n readonly url: string\n\n constructor (url: URL) {\n this.url = url.toString()\n this.multihash = identity.digest(uint8ArrayFromString(this.url))\n }\n\n [inspect] (): string {\n return `PeerId(${this.url})`\n }\n\n readonly [peerIdSymbol] = true\n\n toString (): string {\n return this.toCID().toString()\n }\n\n toMultihash (): MultihashDigest<0x0> {\n return this.multihash\n }\n\n toCID (): CID<Uint8Array, 0x0920, 0x0, 1> {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash())\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n equals (other?: PeerId | Uint8Array | string): boolean {\n if (other == null) {\n return false\n }\n\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other)\n }\n\n return other.toString() === this.toString()\n }\n}\n", "/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\nimport { publicKeyFromMultihash } from '@libp2p/crypto/keys'\nimport { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { CID, type MultibaseDecoder } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { identity } from 'multiformats/hashes/identity'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { RSAPeerId as RSAPeerIdClass, Ed25519PeerId as Ed25519PeerIdClass, Secp256k1PeerId as Secp256k1PeerIdClass, URLPeerId as URLPeerIdClass } from './peer-id.js'\nimport type { Ed25519PeerId, RSAPeerId, URLPeerId, Secp256k1PeerId, PeerId, PublicKey, Ed25519PublicKey, Secp256k1PublicKey, RSAPublicKey, Ed25519PrivateKey, Secp256k1PrivateKey, RSAPrivateKey, PrivateKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920\n\nexport function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n let multihash: MultihashDigest\n\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n multihash = Digest.decode(base58btc.decode(`z${str}`))\n } else if (str.startsWith('k51qzi5uqu5') || str.startsWith('kzwfwjn5ji4') || str.startsWith('k2k4r8') || str.startsWith('bafz')) {\n // base36 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa) or base32 encoded CIDv1 with libp2p-key and identity hash (for ed25519/secp256k1/rsa)\n return peerIdFromCID(CID.parse(str))\n } else {\n if (decoder == null) {\n throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with \"1\" or \"Q\"')\n }\n\n multihash = Digest.decode(decoder.decode(str))\n }\n\n return peerIdFromMultihash(multihash)\n}\n\nexport function peerIdFromPublicKey (publicKey: Ed25519PublicKey): Ed25519PeerId\nexport function peerIdFromPublicKey (publicKey: Secp256k1PublicKey): Secp256k1PeerId\nexport function peerIdFromPublicKey (publicKey: RSAPublicKey): RSAPeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId\nexport function peerIdFromPublicKey (publicKey: PublicKey): PeerId {\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n } else if (publicKey.type === 'RSA') {\n return new RSAPeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n })\n }\n\n throw new UnsupportedKeyTypeError()\n}\n\nexport function peerIdFromPrivateKey (privateKey: Ed25519PrivateKey): Ed25519PeerId\nexport function peerIdFromPrivateKey (privateKey: Secp256k1PrivateKey): Secp256k1PeerId\nexport function peerIdFromPrivateKey (privateKey: RSAPrivateKey): RSAPeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId\nexport function peerIdFromPrivateKey (privateKey: PrivateKey): PeerId {\n return peerIdFromPublicKey(privateKey.publicKey)\n}\n\nexport function peerIdFromMultihash (multihash: MultihashDigest): PeerId {\n if (isSha256Multihash(multihash)) {\n return new RSAPeerIdClass({ multihash })\n } else if (isIdentityMultihash(multihash)) {\n try {\n const publicKey = publicKeyFromMultihash(multihash)\n\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({ multihash, publicKey })\n } else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({ multihash, publicKey })\n }\n } catch (err) {\n // was not Ed or secp key, try URL\n const url = uint8ArrayToString(multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n }\n\n throw new InvalidMultihashError('Supplied PeerID Multihash is invalid')\n}\n\nexport function peerIdFromCID (cid: CID): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new InvalidCIDError('Supplied PeerID CID is invalid')\n }\n\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest)\n\n return new URLPeerIdClass(new URL(url))\n }\n\n return peerIdFromMultihash(cid.multihash)\n}\n\nfunction isIdentityMultihash (multihash: MultihashDigest): multihash is MultihashDigest<0x0> {\n return multihash.code === identity.code\n}\n\nfunction isSha256Multihash (multihash: MultihashDigest): multihash is MultihashDigest<0x12> {\n return multihash.code === sha256.code\n}\n", "import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { type SupportedEncodings, toString as uint8ArrayToString } from 'uint8arrays/to-string'\n\nconst pathSepS = '/'\nconst pathSepB = new TextEncoder().encode(pathSepS)\nconst pathSep = pathSepB[0]\n\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n private _buf: Uint8Array\n\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor (s: string | Uint8Array, clean?: boolean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s)\n } else if (s instanceof Uint8Array) {\n this._buf = s\n } else {\n throw new Error('Invalid key, should be String of Uint8Array')\n }\n\n if (clean == null) {\n clean = true\n }\n\n if (clean) {\n this.clean()\n }\n\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key')\n }\n }\n\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString (encoding: SupportedEncodings = 'utf8'): string {\n return uint8ArrayToString(this._buf, encoding)\n }\n\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array (): Uint8Array {\n return this._buf\n }\n\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag] (): string {\n return `Key(${this.toString()})`\n }\n\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array<string>} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces (list: string[]): Key {\n return new Key(list.join(pathSepS))\n }\n\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random (): Key {\n return new Key(Math.random().toString().substring(2))\n }\n\n /**\n * @param {*} other\n */\n static asKey (other: any): Key | null {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other)\n }\n\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array())\n }\n\n return null\n }\n\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean (): void {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB\n }\n\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1)\n bytes.fill(pathSep, 0, 1)\n bytes.set(this._buf, 1)\n this._buf = bytes\n }\n\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1)\n }\n }\n\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less (key: Key): boolean {\n const list1 = this.list()\n const list2 = key.list()\n\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false\n }\n\n const c1 = list1[i]\n const c2 = list2[i]\n\n if (c1 < c2) {\n return true\n } else if (c1 > c2) {\n return false\n }\n }\n\n return list1.length < list2.length\n }\n\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse (): Key {\n return Key.withNamespaces(this.list().slice().reverse())\n }\n\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array<string>}\n */\n namespaces (): string[] {\n return this.list()\n }\n\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace (): string {\n const ns = this.namespaces()\n return ns[ns.length - 1]\n }\n\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array<string>}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list (): string[] {\n return this.toString().split(pathSepS).slice(1)\n }\n\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type (): string {\n return namespaceType(this.baseNamespace())\n }\n\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name (): string {\n return namespaceValue(this.baseNamespace())\n }\n\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance (s: string): Key {\n return new Key(this.toString() + ':' + s)\n }\n\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path (): Key {\n let p = this.parent().toString()\n if (!p.endsWith(pathSepS)) {\n p += pathSepS\n }\n p += this.type()\n return new Key(p)\n }\n\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent (): Key {\n const list = this.list()\n if (list.length === 1) {\n return new Key(pathSepS)\n }\n\n return new Key(list.slice(0, -1).join(pathSepS))\n }\n\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child (key: Key): Key {\n if (this.toString() === pathSepS) {\n return key\n } else if (key.toString() === pathSepS) {\n return this\n }\n\n return new Key(this.toString() + key.toString(), false)\n }\n\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return other.toString().startsWith(this.toString())\n }\n\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf (other: Key): boolean {\n if (other.toString() === this.toString()) {\n return false\n }\n\n return this.toString().startsWith(other.toString())\n }\n\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel (): boolean {\n return this.list().length === 1\n }\n\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array<Key>} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat (...keys: Key[]): Key {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))])\n }\n}\n\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType (ns: string): string {\n const parts = ns.split(':')\n if (parts.length < 2) {\n return ''\n }\n return parts.slice(0, -1).join(':')\n}\n\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue (ns: string): string {\n const parts = ns.split(':')\n return parts[parts.length - 1]\n}\n\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array<any>} arr\n * @returns {T[]}\n */\nfunction flatten (arr: any[]): string[] {\n return ([]).concat(...arr)\n}\n", "import { publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { logger } from '@libp2p/logger'\nimport { type Key } from 'interface-datastore/key'\nimport NanoDate from 'timestamp-nano'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { SignatureCreationError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { createCborData, ipnsRecordDataForV1Sig, ipnsRecordDataForV2Sig, normalizeValue } from './utils.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst log = logger('ipns')\nconst DEFAULT_TTL_NS = 5 * 60 * 1e+9 // 5 Minutes or 300 Seconds, as suggested by https://specs.ipfs.tech/ipns/ipns-record/#ttl-uint64\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSRecordV1V2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * signature of the record\n */\n signatureV1: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * expiration datetime for the record in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport interface IPNSRecordV2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * If the validity type is EOL, this is the expiration datetime for the record\n * in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport type IPNSRecord = IPNSRecordV1V2 | IPNSRecordV2\n\nexport interface IPNSRecordData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\nexport interface CreateOptions {\n ttlNs?: number | bigint\n v1Compatible?: boolean\n}\n\nexport interface CreateV2OrV1Options {\n v1Compatible: true\n}\n\nexport interface CreateV2Options {\n v1Compatible: false\n}\n\nconst defaultCreateOptions: CreateOptions = {\n v1Compatible: true,\n ttlNs: DEFAULT_TTL_NS\n}\n\n/**\n * Creates a new IPNS record and signs it with the given private key.\n * The IPNS Record validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n * @param {CreateOptions} options - additional create options.\n */\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * @param {CreateOptions} options - additional creation options.\n */\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\nconst _create = async (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, validityType: IpnsEntry.ValidityType, validity: string, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(validity)\n const normalizedValue = normalizeValue(value)\n const encodedValue = uint8ArrayFromString(normalizedValue)\n const data = createCborData(encodedValue, validityType, isoValidity, seq, ttl)\n const sigData = ipnsRecordDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData)\n let pubKey: Uint8Array | undefined\n\n // if we cannot derive the public key from the PeerId (e.g. RSA PeerIDs),\n // we have to embed it in the IPNS record\n if (privateKey.type === 'RSA') {\n pubKey = publicKeyToProtobuf(privateKey.publicKey)\n }\n\n if (options.v1Compatible === true) {\n const signatureV1 = await signLegacyV1(privateKey, encodedValue, validityType, isoValidity)\n\n const record: IPNSRecord = {\n value: normalizedValue,\n signatureV1,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n } else {\n const record: IPNSRecordV2 = {\n value: normalizedValue,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n }\n}\n\nexport { unmarshalIPNSRecord } from './utils.js'\nexport { marshalIPNSRecord } from './utils.js'\nexport { multihashToIPNSRoutingKey } from './utils.js'\nexport { multihashFromIPNSRoutingKey } from './utils.js'\nexport { extractPublicKeyFromIPNSRecord } from './utils.js'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Promise<Uint8Array> => {\n try {\n const dataForSignature = ipnsRecordDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw new SignatureCreationError('Record signature creation failed')\n }\n}\n", "export class SignatureCreationError extends Error {\n static name = 'SignatureCreationError'\n\n constructor (message = 'Record signature creation failed') {\n super(message)\n this.name = 'SignatureCreationError'\n }\n}\n\nexport class SignatureVerificationError extends Error {\n static name = 'SignatureVerificationError'\n\n constructor (message = 'Record signature verification failed') {\n super(message)\n this.name = 'SignatureVerificationError'\n }\n}\n\nexport class RecordExpiredError extends Error {\n static name = 'RecordExpiredError'\n\n constructor (message = 'Record has expired') {\n super(message)\n this.name = 'RecordExpiredError'\n }\n}\n\nexport class UnsupportedValidityError extends Error {\n static name = 'UnsupportedValidityError'\n\n constructor (message = 'The validity type is unsupported') {\n super(message)\n this.name = 'UnsupportedValidityError'\n }\n}\n\nexport class RecordTooLargeError extends Error {\n static name = 'RecordTooLargeError'\n\n constructor (message = 'The record is too large') {\n super(message)\n this.name = 'RecordTooLargeError'\n }\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n\n constructor (message = 'Value must be a valid content path starting with /') {\n super(message)\n this.name = 'InvalidValueError'\n }\n}\n\nexport class InvalidRecordDataError extends Error {\n static name = 'InvalidRecordDataError'\n\n constructor (message = 'Invalid record data') {\n super(message)\n this.name = 'InvalidRecordDataError'\n }\n}\n\nexport class InvalidEmbeddedPublicKeyError extends Error {\n static name = 'InvalidEmbeddedPublicKeyError'\n\n constructor (message = 'Invalid embedded public key') {\n super(message)\n this.name = 'InvalidEmbeddedPublicKeyError'\n }\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface IpnsEntry {\n value?: Uint8Array\n signatureV1?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n pubKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec<ValidityType> => {\n return enumeration<ValidityType>(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec<IpnsEntry>\n\n export const codec = (): Codec<IpnsEntry> => {\n if (_codec == null) {\n _codec = message<IpnsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signatureV1 != null) {\n w.uint32(18)\n w.bytes(obj.signatureV1)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.pubKey != null) {\n w.uint32(58)\n w.bytes(obj.pubKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.value = reader.bytes()\n break\n }\n case 2: {\n obj.signatureV1 = reader.bytes()\n break\n }\n case 3: {\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n }\n case 4: {\n obj.validity = reader.bytes()\n break\n }\n case 5: {\n obj.sequence = reader.uint64()\n break\n }\n case 6: {\n obj.ttl = reader.uint64()\n break\n }\n case 7: {\n obj.pubKey = reader.bytes()\n break\n }\n case 8: {\n obj.signatureV2 = reader.bytes()\n break\n }\n case 9: {\n obj.data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<IpnsEntry>): Uint8Array => {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): IpnsEntry => {\n return decodeMessage(buf, IpnsEntry.codec(), opts)\n }\n}\n", "// This is an unfortunate replacement for @sindresorhus/is that we need to\n// re-implement for performance purposes. In particular the is.observable()\n// check is expensive, and unnecessary for our purposes. The values returned\n// are compatible with @sindresorhus/is, however.\n\nconst typeofs = [\n 'string',\n 'number',\n 'bigint',\n 'symbol'\n]\n\nconst objectTypeNames = [\n 'Function',\n 'Generator',\n 'AsyncGenerator',\n 'GeneratorFunction',\n 'AsyncGeneratorFunction',\n 'AsyncFunction',\n 'Observable',\n 'Array',\n 'Buffer',\n 'Object',\n 'RegExp',\n 'Date',\n 'Error',\n 'Map',\n 'Set',\n 'WeakMap',\n 'WeakSet',\n 'ArrayBuffer',\n 'SharedArrayBuffer',\n 'DataView',\n 'Promise',\n 'URL',\n 'HTMLElement',\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array',\n 'BigInt64Array',\n 'BigUint64Array'\n]\n\n/**\n * @param {any} value\n * @returns {string}\n */\nexport function is (value) {\n if (value === null) {\n return 'null'\n }\n if (value === undefined) {\n return 'undefined'\n }\n if (value === true || value === false) {\n return 'boolean'\n }\n const typeOf = typeof value\n if (typeofs.includes(typeOf)) {\n return typeOf\n }\n /* c8 ignore next 4 */\n // not going to bother testing this, it's not going to be valid anyway\n if (typeOf === 'function') {\n return 'Function'\n }\n if (Array.isArray(value)) {\n return 'Array'\n }\n if (isBuffer(value)) {\n return 'Buffer'\n }\n const objectType = getObjectType(value)\n if (objectType) {\n return objectType\n }\n /* c8 ignore next */\n return 'Object'\n}\n\n/**\n * @param {any} value\n * @returns {boolean}\n */\nfunction isBuffer (value) {\n return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value)\n}\n\n/**\n * @param {any} value\n * @returns {string|undefined}\n */\nfunction getObjectType (value) {\n const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)\n if (objectTypeNames.includes(objectTypeName)) {\n return objectTypeName\n }\n /* c8 ignore next */\n return undefined\n}\n", "class Type {\n /**\n * @param {number} major\n * @param {string} name\n * @param {boolean} terminal\n */\n constructor (major, name, terminal) {\n this.major = major\n this.majorEncoded = major << 5\n this.name = name\n this.terminal = terminal\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Type[${this.major}].${this.name}`\n }\n\n /**\n * @param {Type} typ\n * @returns {number}\n */\n compare (typ) {\n /* c8 ignore next 1 */\n return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0\n }\n}\n\n// convert to static fields when better supported\nType.uint = new Type(0, 'uint', true)\nType.negint = new Type(1, 'negint', true)\nType.bytes = new Type(2, 'bytes', true)\nType.string = new Type(3, 'string', true)\nType.array = new Type(4, 'array', false)\nType.map = new Type(5, 'map', false)\nType.tag = new Type(6, 'tag', false) // terminal?\nType.float = new Type(7, 'float', true)\nType.false = new Type(7, 'false', true)\nType.true = new Type(7, 'true', true)\nType.null = new Type(7, 'null', true)\nType.undefined = new Type(7, 'undefined', true)\nType.break = new Type(7, 'break', true)\n// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)\n\nclass Token {\n /**\n * @param {Type} type\n * @param {any} [value]\n * @param {number} [encodedLength]\n */\n constructor (type, value, encodedLength) {\n this.type = type\n this.value = value\n this.encodedLength = encodedLength\n /** @type {Uint8Array|undefined} */\n this.encodedBytes = undefined\n /** @type {Uint8Array|undefined} */\n this.byteValue = undefined\n }\n\n /* c8 ignore next 3 */\n toString () {\n return `Token[${this.type}].${this.value}`\n }\n}\n\nexport { Type, Token }\n", "// Use Uint8Array directly in the browser, use Buffer in Node.js but don't\n// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill\n\n// @ts-ignore\nexport const useBuffer = globalThis.process &&\n // @ts-ignore\n !globalThis.process.browser &&\n // @ts-ignore\n globalThis.Buffer &&\n // @ts-ignore\n typeof globalThis.Buffer.isBuffer === 'function'\n\nconst textDecoder = new TextDecoder()\nconst textEncoder = new TextEncoder()\n\n/**\n * @param {Uint8Array} buf\n * @returns {boolean}\n */\nfunction isBuffer (buf) {\n // @ts-ignore\n return useBuffer && globalThis.Buffer.isBuffer(buf)\n}\n\n/**\n * @param {Uint8Array|number[]} buf\n * @returns {Uint8Array}\n */\nexport function asU8A (buf) {\n /* c8 ignore next */\n if (!(buf instanceof Uint8Array)) {\n return Uint8Array.from(buf)\n }\n return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf\n}\n\nexport const toString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(bytes.subarray(start, end)).toString('utf8')\n : utf8Slice(bytes, start, end)\n }\n /* c8 ignore next 11 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return end - start > 64\n ? textDecoder.decode(bytes.subarray(start, end))\n : utf8Slice(bytes, start, end)\n }\n\nexport const fromString = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64\n ? // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(string)\n : utf8ToBytes(string)\n }\n /* c8 ignore next 7 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string} string\n */\n (string) => {\n return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string)\n }\n\n/**\n * Buffer variant not fast enough for what we need\n * @param {number[]} arr\n * @returns {Uint8Array}\n */\nexport const fromArray = (arr) => {\n return Uint8Array.from(arr)\n}\n\nexport const slice = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n if (isBuffer(bytes)) {\n return new Uint8Array(bytes.subarray(start, end))\n }\n return bytes.slice(start, end)\n }\n /* c8 ignore next 9 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} bytes\n * @param {number} start\n * @param {number} end\n */\n (bytes, start, end) => {\n return bytes.slice(start, end)\n }\n\nexport const concat = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n // might get a stray plain Array here\n /* c8 ignore next 1 */\n chunks = chunks.map((c) => c instanceof Uint8Array\n ? c\n // this case is occasionally missed during test runs so becomes coverage-flaky\n /* c8 ignore next 4 */\n : // eslint-disable-line operator-linebreak\n // @ts-ignore\n globalThis.Buffer.from(c))\n // @ts-ignore\n return asU8A(globalThis.Buffer.concat(chunks, length))\n }\n /* c8 ignore next 19 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\n (chunks, length) => {\n const out = new Uint8Array(length)\n let off = 0\n for (let b of chunks) {\n if (off + b.length > out.length) {\n // final chunk that's bigger than we need\n b = b.subarray(0, out.length - off)\n }\n out.set(b, off)\n off += b.length\n }\n return out\n }\n\nexport const alloc = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n // we always write over the contents we expose so this should be safe\n // @ts-ignore\n return globalThis.Buffer.allocUnsafe(size)\n }\n /* c8 ignore next 8 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {number} size\n * @returns {Uint8Array}\n */\n (size) => {\n return new Uint8Array(size)\n }\n\nexport const toHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore\n return globalThis.Buffer.from(toBytes(d)).toString('hex')\n }\n /* c8 ignore next 12 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {Uint8Array} d\n * @returns {string}\n */\n (d) => {\n if (typeof d === 'string') {\n return d\n }\n // @ts-ignore not smart enough to figure this out\n return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')\n }\n\nexport const fromHex = useBuffer\n ? // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n // @ts-ignore\n return globalThis.Buffer.from(hex, 'hex')\n }\n /* c8 ignore next 17 */\n : // eslint-disable-line operator-linebreak\n /**\n * @param {string|Uint8Array} hex\n * @returns {Uint8Array}\n */\n (hex) => {\n if (hex instanceof Uint8Array) {\n return hex\n }\n if (!hex.length) {\n return new Uint8Array(0)\n }\n return new Uint8Array(hex.split('')\n .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')\n .filter(Boolean)\n .map((/** @type {string} */ e) => parseInt(e, 16)))\n }\n\n/**\n * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj\n * @returns {Uint8Array}\n */\nfunction toBytes (obj) {\n if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {\n return obj\n }\n if (obj instanceof ArrayBuffer) {\n return new Uint8Array(obj)\n }\n if (ArrayBuffer.isView(obj)) {\n return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)\n }\n /* c8 ignore next */\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compare (b1, b2) {\n /* c8 ignore next 5 */\n if (isBuffer(b1) && isBuffer(b2)) {\n // probably not possible to get here in the current API\n // @ts-ignore Buffer\n return b1.compare(b2)\n }\n for (let i = 0; i < b1.length; i++) {\n if (b1[i] === b2[i]) {\n continue\n }\n return b1[i] < b2[i] ? -1 : 1\n } /* c8 ignore next 3 */\n return 0\n}\n\n// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n// Licensed Apache-2.0.\n\n/**\n * @param {string} str\n * @returns {number[]}\n */\nfunction utf8ToBytes (str) {\n const out = []\n let p = 0\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i)\n if (c < 128) {\n out[p++] = c\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192\n out[p++] = (c & 63) | 128\n } else if (\n ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)\n out[p++] = (c >> 18) | 240\n out[p++] = ((c >> 12) & 63) | 128\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n } else {\n out[p++] = (c >> 12) | 224\n out[p++] = ((c >> 6) & 63) | 128\n out[p++] = (c & 63) | 128\n }\n }\n return out\n}\n\n// The below code is mostly taken from https://github.com/feross/buffer\n// Licensed MIT. Copyright (c) Feross Aboukhadijeh\n\n/**\n * @param {Uint8Array} buf\n * @param {number} offset\n * @param {number} end\n * @returns {string}\n */\nfunction utf8Slice (buf, offset, end) {\n const res = []\n\n while (offset < end) {\n const firstByte = buf[offset]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xef) ? 4 : (firstByte > 0xdf) ? 3 : (firstByte > 0xbf) ? 2 : 1\n\n if (offset + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[offset + 1]\n if ((secondByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0x1f) << 0x6 | (secondByte & 0x3f)\n if (tempCodePoint > 0x7f) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0xc | (secondByte & 0x3f) << 0x6 | (thirdByte & 0x3f)\n /* c8 ignore next 3 */\n if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[offset + 1]\n thirdByte = buf[offset + 2]\n fourthByte = buf[offset + 3]\n if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) {\n tempCodePoint = (firstByte & 0xf) << 0x12 | (secondByte & 0x3f) << 0xc | (thirdByte & 0x3f) << 0x6 | (fourthByte & 0x3f)\n if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n /* c8 ignore next 5 */\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xfffd\n bytesPerSequence = 1\n } else if (codePoint > 0xffff) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3ff | 0xd800)\n codePoint = 0xdc00 | codePoint & 0x3ff\n }\n\n res.push(codePoint)\n offset += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\n/**\n * @param {number[]} codePoints\n * @returns {string}\n */\nexport function decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n /* c8 ignore next 10 */\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n", "/**\n * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for\n * writing rather than reading.\n * A Bl object accepts set() operations for individual bytes and copyTo() for\n * inserting byte arrays. These write operations don't automatically increment\n * the internal cursor so its \"length\" won't be changed. Instead, increment()\n * must be called to extend its length to cover the inserted data.\n * The toBytes() call will convert all internal memory to a single Uint8Array of\n * the correct length, truncating any data that is stored but hasn't been\n * included by an increment().\n * get() can retrieve a single byte.\n * All operations (except toBytes()) take an \"offset\" argument that will perform\n * the write at the offset _from the current cursor_. For most operations this\n * will be `0` to write at the current cursor position but it can be ahead of\n * the current cursor. Negative offsets probably work but are untested.\n */\n\n// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39\nimport { alloc, concat, slice } from './byte-utils.js'\n\n// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists\n// for perf reasons. Consider better approaches to this or removing it entirely, it is quite\n// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.\n\nconst defaultChunkSize = 256\n\nexport class Bl {\n /**\n * @param {number} [chunkSize]\n */\n constructor (chunkSize = defaultChunkSize) {\n this.chunkSize = chunkSize\n /** @type {number} */\n this.cursor = 0\n /** @type {number} */\n this.maxCursor = -1\n /** @type {(Uint8Array|number[])[]} */\n this.chunks = []\n // keep the first chunk around if we can to save allocations for future encodes\n /** @type {Uint8Array|number[]|null} */\n this._initReuseChunk = null\n }\n\n reset () {\n this.cursor = 0\n this.maxCursor = -1\n if (this.chunks.length) {\n this.chunks = []\n }\n if (this._initReuseChunk !== null) {\n this.chunks.push(this._initReuseChunk)\n this.maxCursor = this._initReuseChunk.length - 1\n }\n }\n\n /**\n * @param {Uint8Array|number[]} bytes\n */\n push (bytes) {\n let topChunk = this.chunks[this.chunks.length - 1]\n const newMax = this.cursor + bytes.length\n if (newMax <= this.maxCursor + 1) {\n // we have at least one chunk and we can fit these bytes into that chunk\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n // @ts-ignore\n topChunk.set(bytes, chunkPos)\n } else {\n // can't fit it in\n if (topChunk) {\n // trip the last chunk to `cursor` if we need to\n const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1\n if (chunkPos < topChunk.length) {\n // @ts-ignore\n this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)\n this.maxCursor = this.cursor - 1\n }\n }\n if (bytes.length < 64 && bytes.length < this.chunkSize) {\n // make a new chunk and copy the new one into it\n topChunk = alloc(this.chunkSize)\n this.chunks.push(topChunk)\n this.maxCursor += topChunk.length\n if (this._initReuseChunk === null) {\n this._initReuseChunk = topChunk\n }\n // @ts-ignore\n topChunk.set(bytes, 0)\n } else {\n // push the new bytes in as its own chunk\n this.chunks.push(bytes)\n this.maxCursor += bytes.length\n }\n }\n this.cursor += bytes.length\n }\n\n /**\n * @param {boolean} [reset]\n * @returns {Uint8Array}\n */\n toBytes (reset = false) {\n let byts\n if (this.chunks.length === 1) {\n const chunk = this.chunks[0]\n if (reset && this.cursor > chunk.length / 2) {\n /* c8 ignore next 2 */\n // @ts-ignore\n byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)\n this._initReuseChunk = null\n this.chunks = []\n } else {\n // @ts-ignore\n byts = slice(chunk, 0, this.cursor)\n }\n } else {\n // @ts-ignore\n byts = concat(this.chunks, this.cursor)\n }\n if (reset) {\n this.reset()\n }\n return byts\n }\n}\n", "const decodeErrPrefix = 'CBOR decode error:'\nconst encodeErrPrefix = 'CBOR encode error:'\n\nconst uintMinorPrefixBytes = []\nuintMinorPrefixBytes[23] = 1\nuintMinorPrefixBytes[24] = 2\nuintMinorPrefixBytes[25] = 3\nuintMinorPrefixBytes[26] = 5\nuintMinorPrefixBytes[27] = 9\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} need\n */\nfunction assertEnoughData (data, pos, need) {\n if (data.length - pos < need) {\n throw new Error(`${decodeErrPrefix} not enough data for type`)\n }\n}\n\nexport {\n decodeErrPrefix,\n encodeErrPrefix,\n uintMinorPrefixBytes,\n assertEnoughData\n}\n", "/* globals BigInt */\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix, assertEnoughData } from './common.js'\n\nexport const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint8 (data, offset, options) {\n assertEnoughData(data, offset, 1)\n const value = data[offset]\n if (options.strict === true && value < uintBoundaries[0]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint16 (data, offset, options) {\n assertEnoughData(data, offset, 2)\n const value = (data[offset] << 8) | data[offset + 1]\n if (options.strict === true && value < uintBoundaries[1]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number}\n */\nexport function readUint32 (data, offset, options) {\n assertEnoughData(data, offset, 4)\n const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n if (options.strict === true && value < uintBoundaries[2]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n return value\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} offset\n * @param {DecodeOptions} options\n * @returns {number|bigint}\n */\nexport function readUint64 (data, offset, options) {\n // assume BigInt, convert back to Number if within safe range\n assertEnoughData(data, offset, 8)\n const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]\n const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]\n const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)\n if (options.strict === true && value < uintBoundaries[3]) {\n throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)\n }\n if (value <= Number.MAX_SAFE_INTEGER) {\n return Number(value)\n }\n if (options.allowBigInt === true) {\n return value\n }\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n}\n\n/* not required thanks to quick[] list\nconst oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))\nexport function decodeUintCompact (data, pos, minor, options) {\n return oneByteTokens[minor]\n}\n*/\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint8 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint16 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint32 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUint64 (data, pos, _minor, options) {\n return new Token(Type.uint, readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeUint (buf, token) {\n return encodeUintValue(buf, 0, token.value)\n}\n\n/**\n * @param {Bl} buf\n * @param {number} major\n * @param {number|bigint} uint\n */\nexport function encodeUintValue (buf, major, uint) {\n if (uint < uintBoundaries[0]) {\n const nuint = Number(uint)\n // pack into one byte, minor=0, additional=value\n buf.push([major | nuint])\n } else if (uint < uintBoundaries[1]) {\n const nuint = Number(uint)\n // pack into two byte, minor=0, additional=24\n buf.push([major | 24, nuint])\n } else if (uint < uintBoundaries[2]) {\n const nuint = Number(uint)\n // pack into three byte, minor=0, additional=25\n buf.push([major | 25, nuint >>> 8, nuint & 0xff])\n } else if (uint < uintBoundaries[3]) {\n const nuint = Number(uint)\n // pack into five byte, minor=0, additional=26\n buf.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])\n } else {\n const buint = BigInt(uint)\n if (buint < uintBoundaries[4]) {\n // pack into nine byte, minor=0, additional=27\n const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]\n // simulate bitwise above 32 bits\n let lo = Number(buint & BigInt(0xffffffff))\n let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))\n set[8] = lo & 0xff\n lo = lo >> 8\n set[7] = lo & 0xff\n lo = lo >> 8\n set[6] = lo & 0xff\n lo = lo >> 8\n set[5] = lo & 0xff\n set[4] = hi & 0xff\n hi = hi >> 8\n set[3] = hi & 0xff\n hi = hi >> 8\n set[2] = hi & 0xff\n hi = hi >> 8\n set[1] = hi & 0xff\n buf.push(set)\n } else {\n throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)\n }\n }\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeUint.encodedSize = function encodedSize (token) {\n return encodeUintValue.encodedSize(token.value)\n}\n\n/**\n * @param {number} uint\n * @returns {number}\n */\nencodeUintValue.encodedSize = function encodedSize (uint) {\n if (uint < uintBoundaries[0]) {\n return 1\n }\n if (uint < uintBoundaries[1]) {\n return 2\n }\n if (uint < uintBoundaries[2]) {\n return 3\n }\n if (uint < uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeUint.compareTokens = function compareTokens (tok1, tok2) {\n return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : /* c8 ignore next */ 0\n}\n", "/* eslint-env es2020 */\n\nimport { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint8 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint16 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint32 (data, pos, _minor, options) {\n return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)\n}\n\nconst neg1b = BigInt(-1)\nconst pos1b = BigInt(1)\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeNegint64 (data, pos, _minor, options) {\n const int = uint.readUint64(data, pos + 1, options)\n if (typeof int !== 'bigint') {\n const value = -1 - int\n if (value >= Number.MIN_SAFE_INTEGER) {\n return new Token(Type.negint, value, 9)\n }\n }\n if (options.allowBigInt !== true) {\n throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)\n }\n return new Token(Type.negint, neg1b - BigInt(int), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeNegint (buf, token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n uint.encodeUintValue(buf, token.type.majorEncoded, unsigned)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeNegint.encodedSize = function encodedSize (token) {\n const negint = token.value\n const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))\n /* c8 ignore next 4 */\n // handled by quickEncode, we shouldn't get here but it's included for completeness\n if (unsigned < uint.uintBoundaries[0]) {\n return 1\n }\n if (unsigned < uint.uintBoundaries[1]) {\n return 2\n }\n if (unsigned < uint.uintBoundaries[2]) {\n return 3\n }\n if (unsigned < uint.uintBoundaries[3]) {\n return 5\n }\n return 9\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeNegint.compareTokens = function compareTokens (tok1, tok2) {\n // opposite of the uint comparison since we store the uint version in bytes\n return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : /* c8 ignore next */ 0\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { compare, fromString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length) {\n assertEnoughData(data, pos, prefix + length)\n const buf = slice(data, pos + prefix, pos + prefix + length)\n return new Token(Type.bytes, buf, prefix + length)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeBytesCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBytes64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * `encodedBytes` allows for caching when we do a byte version of a string\n * for key sorting purposes\n * @param {Token} token\n * @returns {Uint8Array}\n */\nfunction tokenBytes (token) {\n if (token.encodedBytes === undefined) {\n token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value\n }\n // @ts-ignore c'mon\n return token.encodedBytes\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeBytes (buf, token) {\n const bytes = tokenBytes(token)\n uint.encodeUintValue(buf, token.type.majorEncoded, bytes.length)\n buf.push(bytes)\n}\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeBytes.encodedSize = function encodedSize (token) {\n const bytes = tokenBytes(token)\n return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length\n}\n\n/**\n * @param {Token} tok1\n * @param {Token} tok2\n * @returns {number}\n */\nencodeBytes.compareTokens = function compareTokens (tok1, tok2) {\n return compareBytes(tokenBytes(tok1), tokenBytes(tok2))\n}\n\n/**\n * @param {Uint8Array} b1\n * @param {Uint8Array} b2\n * @returns {number}\n */\nexport function compareBytes (b1, b2) {\n return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)\n}\n", "import { Token, Type } from './token.js'\nimport { assertEnoughData, decodeErrPrefix } from './common.js'\nimport * as uint from './0uint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { toString, slice } from './byte-utils.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} prefix\n * @param {number} length\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction toToken (data, pos, prefix, length, options) {\n const totLength = prefix + length\n assertEnoughData(data, pos, totLength)\n const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength)\n if (options.retainStringBytes === true) {\n tok.byteValue = slice(data, pos + prefix, pos + totLength)\n }\n return tok\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeStringCompact (data, pos, minor, options) {\n return toToken(data, pos, 1, minor, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeString64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)\n }\n return toToken(data, pos, 9, l, options)\n}\n\nexport const encodeString = encodeBytes\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.array, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeArrayCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArray64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeArrayIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeArray (buf, token) {\n uint.encodeUintValue(buf, Type.array.majorEncoded, token.value)\n}\n\n// using an array as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeArray.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeArray.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport { decodeErrPrefix } from './common.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} prefix\n * @param {number} length\n * @returns {Token}\n */\nfunction toToken (_data, _pos, prefix, length) {\n return new Token(Type.map, length, prefix)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeMapCompact (data, pos, minor, _options) {\n return toToken(data, pos, 1, minor)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap8 (data, pos, _minor, options) {\n return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap16 (data, pos, _minor, options) {\n return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap32 (data, pos, _minor, options) {\n return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))\n}\n\n// TODO: maybe we shouldn't support this ..\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMap64 (data, pos, _minor, options) {\n const l = uint.readUint64(data, pos + 1, options)\n if (typeof l === 'bigint') {\n throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)\n }\n return toToken(data, pos, 9, l)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeMapIndefinite (data, pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return toToken(data, pos, 1, Infinity)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeMap (buf, token) {\n uint.encodeUintValue(buf, Type.map.majorEncoded, token.value)\n}\n\n// using a map as a map key, are you sure about this? we can only sort\n// by map length here, it's up to the encoder to decide to look deeper\nencodeMap.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeMap.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} minor\n * @param {DecodeOptions} _options\n * @returns {Token}\n */\nexport function decodeTagCompact (_data, _pos, minor, _options) {\n return new Token(Type.tag, minor, 1)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag8 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag16 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag32 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeTag64 (data, pos, _minor, options) {\n return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n */\nexport function encodeTag (buf, token) {\n uint.encodeUintValue(buf, Type.tag.majorEncoded, token.value)\n}\n\nencodeTag.compareTokens = uint.encodeUint.compareTokens\n\n/**\n * @param {Token} token\n * @returns {number}\n */\nencodeTag.encodedSize = function encodedSize (token) {\n return uint.encodeUintValue.encodedSize(token.value)\n}\n", "// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer\n// where possible\n\nimport { Token, Type } from './token.js'\nimport { decodeErrPrefix } from './common.js'\nimport { encodeUint } from './0uint.js'\n\n/**\n * @typedef {import('./bl.js').Bl} Bl\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n */\n\nconst MINOR_FALSE = 20\nconst MINOR_TRUE = 21\nconst MINOR_NULL = 22\nconst MINOR_UNDEFINED = 23\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeUndefined (_data, _pos, _minor, options) {\n if (options.allowUndefined === false) {\n throw new Error(`${decodeErrPrefix} undefined values are not supported`)\n } else if (options.coerceUndefinedToNull === true) {\n return new Token(Type.null, null, 1)\n }\n return new Token(Type.undefined, undefined, 1)\n}\n\n/**\n * @param {Uint8Array} _data\n * @param {number} _pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeBreak (_data, _pos, _minor, options) {\n if (options.allowIndefinite === false) {\n throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)\n }\n return new Token(Type.break, undefined, 1)\n}\n\n/**\n * @param {number} value\n * @param {number} bytes\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nfunction createToken (value, bytes, options) {\n if (options) {\n if (options.allowNaN === false && Number.isNaN(value)) {\n throw new Error(`${decodeErrPrefix} NaN values are not supported`)\n }\n if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {\n throw new Error(`${decodeErrPrefix} Infinity values are not supported`)\n }\n }\n return new Token(Type.float, value, bytes)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat16 (data, pos, _minor, options) {\n return createToken(readFloat16(data, pos + 1), 3, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat32 (data, pos, _minor, options) {\n return createToken(readFloat32(data, pos + 1), 5, options)\n}\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} _minor\n * @param {DecodeOptions} options\n * @returns {Token}\n */\nexport function decodeFloat64 (data, pos, _minor, options) {\n return createToken(readFloat64(data, pos + 1), 9, options)\n}\n\n/**\n * @param {Bl} buf\n * @param {Token} token\n * @param {EncodeOptions} options\n */\nexport function encodeFloat (buf, token, options) {\n const float = token.value\n\n if (float === false) {\n buf.push([Type.float.majorEncoded | MINOR_FALSE])\n } else if (float === true) {\n buf.push([Type.float.majorEncoded | MINOR_TRUE])\n } else if (float === null) {\n buf.push([Type.float.majorEncoded | MINOR_NULL])\n } else if (float === undefined) {\n buf.push([Type.float.majorEncoded | MINOR_UNDEFINED])\n } else {\n let decoded\n let success = false\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n ui8a[0] = 0xf9\n buf.push(ui8a.slice(0, 3))\n success = true\n } else {\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n ui8a[0] = 0xfa\n buf.push(ui8a.slice(0, 5))\n success = true\n }\n }\n }\n if (!success) {\n encodeFloat64(float)\n decoded = readFloat64(ui8a, 1)\n ui8a[0] = 0xfb\n buf.push(ui8a.slice(0, 9))\n }\n }\n}\n\n/**\n * @param {Token} token\n * @param {EncodeOptions} options\n * @returns {number}\n */\nencodeFloat.encodedSize = function encodedSize (token, options) {\n const float = token.value\n\n if (float === false || float === true || float === null || float === undefined) {\n return 1\n }\n\n if (!options || options.float64 !== true) {\n encodeFloat16(float)\n let decoded = readFloat16(ui8a, 1)\n if (float === decoded || Number.isNaN(float)) {\n return 3\n }\n encodeFloat32(float)\n decoded = readFloat32(ui8a, 1)\n if (float === decoded) {\n return 5\n }\n }\n return 9\n}\n\nconst buffer = new ArrayBuffer(9)\nconst dataView = new DataView(buffer, 1)\nconst ui8a = new Uint8Array(buffer, 0)\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat16 (inp) {\n if (inp === Infinity) {\n dataView.setUint16(0, 0x7c00, false)\n } else if (inp === -Infinity) {\n dataView.setUint16(0, 0xfc00, false)\n } else if (Number.isNaN(inp)) {\n dataView.setUint16(0, 0x7e00, false)\n } else {\n dataView.setFloat32(0, inp)\n const valu32 = dataView.getUint32(0)\n const exponent = (valu32 & 0x7f800000) >> 23\n const mantissa = valu32 & 0x7fffff\n\n /* c8 ignore next 6 */\n if (exponent === 0xff) {\n // too big, Infinity, but this should be hard (impossible?) to trigger\n dataView.setUint16(0, 0x7c00, false)\n } else if (exponent === 0x00) {\n // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int\n dataView.setUint16(0, ((inp & 0x80000000) >> 16) | (mantissa >> 13), false)\n } else { // standard numbers\n // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127\n const logicalExponent = exponent - 127\n // Now we know that 2^exponent <= 0 logically\n /* c8 ignore next 6 */\n if (logicalExponent < -24) {\n /* No unambiguous representation exists, this float is not a half float\n and is too small to be represented using a half, round off to zero.\n Consistent with the reference implementation. */\n // should be difficult (impossible?) to get here in JS\n dataView.setUint16(0, 0)\n } else if (logicalExponent < -14) {\n /* Offset the remaining decimal places by shifting the significand, the\n value is lost. This is an implementation decision that works around the\n absence of standard half-float in the language. */\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)\n } else {\n dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)\n }\n }\n }\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat16 (ui8a, pos) {\n if (ui8a.length - pos < 2) {\n throw new Error(`${decodeErrPrefix} not enough data for float16`)\n }\n\n const half = (ui8a[pos] << 8) + ui8a[pos + 1]\n if (half === 0x7c00) {\n return Infinity\n }\n if (half === 0xfc00) {\n return -Infinity\n }\n if (half === 0x7e00) {\n return NaN\n }\n const exp = (half >> 10) & 0x1f\n const mant = half & 0x3ff\n let val\n if (exp === 0) {\n val = mant * (2 ** -24)\n } else if (exp !== 31) {\n val = (mant + 1024) * (2 ** (exp - 25))\n /* c8 ignore next 4 */\n } else {\n // may not be possible to get here\n val = mant === 0 ? Infinity : NaN\n }\n return (half & 0x8000) ? -val : val\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat32 (inp) {\n dataView.setFloat32(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat32 (ui8a, pos) {\n if (ui8a.length - pos < 4) {\n throw new Error(`${decodeErrPrefix} not enough data for float32`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)\n}\n\n/**\n * @param {number} inp\n */\nfunction encodeFloat64 (inp) {\n dataView.setFloat64(0, inp, false)\n}\n\n/**\n * @param {Uint8Array} ui8a\n * @param {number} pos\n * @returns {number}\n */\nfunction readFloat64 (ui8a, pos) {\n if (ui8a.length - pos < 8) {\n throw new Error(`${decodeErrPrefix} not enough data for float64`)\n }\n const offset = (ui8a.byteOffset || 0) + pos\n return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)\n}\n\n/**\n * @param {Token} _tok1\n * @param {Token} _tok2\n * @returns {number}\n */\nencodeFloat.compareTokens = encodeUint.compareTokens\n/*\nencodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {\n return _tok1\n throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)\n}\n*/\n", "import { Token, Type } from './token.js'\nimport * as uint from './0uint.js'\nimport * as negint from './1negint.js'\nimport * as bytes from './2bytes.js'\nimport * as string from './3string.js'\nimport * as array from './4array.js'\nimport * as map from './5map.js'\nimport * as tag from './6tag.js'\nimport * as float from './7float.js'\nimport { decodeErrPrefix } from './common.js'\nimport { fromArray } from './byte-utils.js'\n\n/**\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n */\n\n/**\n * @param {Uint8Array} data\n * @param {number} pos\n * @param {number} minor\n */\nfunction invalidMinor (data, pos, minor) {\n throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)\n}\n\n/**\n * @param {string} msg\n * @returns {()=>any}\n */\nfunction errorer (msg) {\n return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }\n}\n\n/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */\nexport const jump = []\n\n// unsigned integer, 0x00..0x17 (0..23)\nfor (let i = 0; i <= 0x17; i++) {\n jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]\n}\njump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows\njump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows\njump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows\njump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows\njump[0x1c] = invalidMinor\njump[0x1d] = invalidMinor\njump[0x1e] = invalidMinor\njump[0x1f] = invalidMinor\n// negative integer, -1-0x00..-1-0x17 (-1..-24)\nfor (let i = 0x20; i <= 0x37; i++) {\n jump[i] = invalidMinor // negintDecode, handled by quick[]\n}\njump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows\njump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows\njump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows\njump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows\njump[0x3c] = invalidMinor\njump[0x3d] = invalidMinor\njump[0x3e] = invalidMinor\njump[0x3f] = invalidMinor\n// byte string, 0x00..0x17 bytes follow\nfor (let i = 0x40; i <= 0x57; i++) {\n jump[i] = bytes.decodeBytesCompact\n}\njump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow\njump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow\njump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow\njump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow\njump[0x5c] = invalidMinor\njump[0x5d] = invalidMinor\njump[0x5e] = invalidMinor\njump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by \"break\"\n// UTF-8 string 0x00..0x17 bytes follow\nfor (let i = 0x60; i <= 0x77; i++) {\n jump[i] = string.decodeStringCompact\n}\njump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow\njump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow\njump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow\njump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow\njump[0x7c] = invalidMinor\njump[0x7d] = invalidMinor\njump[0x7e] = invalidMinor\njump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by \"break\"\n// array, 0x00..0x17 data items follow\nfor (let i = 0x80; i <= 0x97; i++) {\n jump[i] = array.decodeArrayCompact\n}\njump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow\njump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow\njump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow\njump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow\njump[0x9c] = invalidMinor\njump[0x9d] = invalidMinor\njump[0x9e] = invalidMinor\njump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by \"break\"\n// map, 0x00..0x17 pairs of data items follow\nfor (let i = 0xa0; i <= 0xb7; i++) {\n jump[i] = map.decodeMapCompact\n}\njump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow\njump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow\njump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow\njump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow\njump[0xbc] = invalidMinor\njump[0xbd] = invalidMinor\njump[0xbe] = invalidMinor\njump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by \"break\"\n// tags\nfor (let i = 0xc0; i <= 0xd7; i++) {\n jump[i] = tag.decodeTagCompact\n}\njump[0xd8] = tag.decodeTag8\njump[0xd9] = tag.decodeTag16\njump[0xda] = tag.decodeTag32\njump[0xdb] = tag.decodeTag64\njump[0xdc] = invalidMinor\njump[0xdd] = invalidMinor\njump[0xde] = invalidMinor\njump[0xdf] = invalidMinor\n// 0xe0..0xf3 simple values, unsupported\nfor (let i = 0xe0; i <= 0xf3; i++) {\n jump[i] = errorer('simple values are not supported')\n}\njump[0xf4] = invalidMinor // false, handled by quick[]\njump[0xf5] = invalidMinor // true, handled by quick[]\njump[0xf6] = invalidMinor // null, handled by quick[]\njump[0xf7] = float.decodeUndefined // undefined\njump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported\njump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)\njump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)\njump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)\njump[0xfc] = invalidMinor\njump[0xfd] = invalidMinor\njump[0xfe] = invalidMinor\njump[0xff] = float.decodeBreak // \"break\" stop code\n\n/** @type {Token[]} */\nexport const quick = []\n// ints <24\nfor (let i = 0; i < 24; i++) {\n quick[i] = new Token(Type.uint, i, 1)\n}\n// negints >= -24\nfor (let i = -1; i >= -24; i--) {\n quick[31 - i] = new Token(Type.negint, i, 1)\n}\n// empty bytes\nquick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)\n// empty string\nquick[0x60] = new Token(Type.string, '', 1)\n// empty list\nquick[0x80] = new Token(Type.array, 0, 1)\n// empty map\nquick[0xa0] = new Token(Type.map, 0, 1)\n// false\nquick[0xf4] = new Token(Type.false, false, 1)\n// true\nquick[0xf5] = new Token(Type.true, true, 1)\n// null\nquick[0xf6] = new Token(Type.null, null, 1)\n\n/**\n * @param {Token} token\n * @returns {Uint8Array|undefined}\n */\nexport function quickEncodeToken (token) {\n switch (token.type) {\n case Type.false:\n return fromArray([0xf4])\n case Type.true:\n return fromArray([0xf5])\n case Type.null:\n return fromArray([0xf6])\n case Type.bytes:\n if (!token.value.length) {\n return fromArray([0x40])\n }\n return\n case Type.string:\n if (token.value === '') {\n return fromArray([0x60])\n }\n return\n case Type.array:\n if (token.value === 0) {\n return fromArray([0x80])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.map:\n if (token.value === 0) {\n return fromArray([0xa0])\n }\n /* c8 ignore next 2 */\n // shouldn't be possible if this were called when there was only one token\n return\n case Type.uint:\n if (token.value < 24) {\n return fromArray([Number(token.value)])\n }\n return\n case Type.negint:\n if (token.value >= -24) {\n return fromArray([31 - Number(token.value)])\n }\n }\n}\n", "import { is } from './is.js'\nimport { Token, Type } from './token.js'\nimport { Bl } from './bl.js'\nimport { encodeErrPrefix } from './common.js'\nimport { quickEncodeToken } from './jump.js'\nimport { asU8A } from './byte-utils.js'\n\nimport { encodeUint } from './0uint.js'\nimport { encodeNegint } from './1negint.js'\nimport { encodeBytes } from './2bytes.js'\nimport { encodeString } from './3string.js'\nimport { encodeArray } from './4array.js'\nimport { encodeMap } from './5map.js'\nimport { encodeTag } from './6tag.js'\nimport { encodeFloat } from './7float.js'\n\n/**\n * @typedef {import('../interface').EncodeOptions} EncodeOptions\n * @typedef {import('../interface').OptionalTypeEncoder} OptionalTypeEncoder\n * @typedef {import('../interface').Reference} Reference\n * @typedef {import('../interface').StrictTypeEncoder} StrictTypeEncoder\n * @typedef {import('../interface').TokenTypeEncoder} TokenTypeEncoder\n * @typedef {import('../interface').TokenOrNestedTokens} TokenOrNestedTokens\n */\n\n/** @type {EncodeOptions} */\nconst defaultEncodeOptions = {\n float64: false,\n mapSorter,\n quickEncodeToken\n}\n\n/** @returns {TokenTypeEncoder[]} */\nexport function makeCborEncoders () {\n const encoders = []\n encoders[Type.uint.major] = encodeUint\n encoders[Type.negint.major] = encodeNegint\n encoders[Type.bytes.major] = encodeBytes\n encoders[Type.string.major] = encodeString\n encoders[Type.array.major] = encodeArray\n encoders[Type.map.major] = encodeMap\n encoders[Type.tag.major] = encodeTag\n encoders[Type.float.major] = encodeFloat\n return encoders\n}\n\nconst cborEncoders = makeCborEncoders()\n\nconst buf = new Bl()\n\n/** @implements {Reference} */\nclass Ref {\n /**\n * @param {object|any[]} obj\n * @param {Reference|undefined} parent\n */\n constructor (obj, parent) {\n this.obj = obj\n this.parent = parent\n }\n\n /**\n * @param {object|any[]} obj\n * @returns {boolean}\n */\n includes (obj) {\n /** @type {Reference|undefined} */\n let p = this\n do {\n if (p.obj === obj) {\n return true\n }\n } while (p = p.parent) // eslint-disable-line\n return false\n }\n\n /**\n * @param {Reference|undefined} stack\n * @param {object|any[]} obj\n * @returns {Reference}\n */\n static createCheck (stack, obj) {\n if (stack && stack.includes(obj)) {\n throw new Error(`${encodeErrPrefix} object contains circular references`)\n }\n return new Ref(obj, stack)\n }\n}\n\nconst simpleTokens = {\n null: new Token(Type.null, null),\n undefined: new Token(Type.undefined, undefined),\n true: new Token(Type.true, true),\n false: new Token(Type.false, false),\n emptyArray: new Token(Type.array, 0),\n emptyMap: new Token(Type.map, 0)\n}\n\n/** @type {{[typeName: string]: StrictTypeEncoder}} */\nconst typeEncoders = {\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n number (obj, _typ, _options, _refStack) {\n if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {\n return new Token(Type.float, obj)\n } else if (obj >= 0) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n bigint (obj, _typ, _options, _refStack) {\n if (obj >= BigInt(0)) {\n return new Token(Type.uint, obj)\n } else {\n return new Token(Type.negint, obj)\n }\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n Uint8Array (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n string (obj, _typ, _options, _refStack) {\n return new Token(Type.string, obj)\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n boolean (obj, _typ, _options, _refStack) {\n return obj ? simpleTokens.true : simpleTokens.false\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n null (_obj, _typ, _options, _refStack) {\n return simpleTokens.null\n },\n\n /**\n * @param {any} _obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n undefined (_obj, _typ, _options, _refStack) {\n return simpleTokens.undefined\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n ArrayBuffer (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} _options\n * @param {Reference} [_refStack]\n * @returns {TokenOrNestedTokens}\n */\n DataView (obj, _typ, _options, _refStack) {\n return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))\n },\n\n /**\n * @param {any} obj\n * @param {string} _typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Array (obj, _typ, options, refStack) {\n if (!obj.length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyArray, new Token(Type.break)]\n }\n return simpleTokens.emptyArray\n }\n refStack = Ref.createCheck(refStack, obj)\n const entries = []\n let i = 0\n for (const e of obj) {\n entries[i++] = objectToTokens(e, options, refStack)\n }\n if (options.addBreakTokens) {\n return [new Token(Type.array, obj.length), entries, new Token(Type.break)]\n }\n return [new Token(Type.array, obj.length), entries]\n },\n\n /**\n * @param {any} obj\n * @param {string} typ\n * @param {EncodeOptions} options\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\n Object (obj, typ, options, refStack) {\n // could be an Object or a Map\n const isMap = typ !== 'Object'\n // it's slightly quicker to use Object.keys() than Object.entries()\n const keys = isMap ? obj.keys() : Object.keys(obj)\n const length = isMap ? obj.size : keys.length\n if (!length) {\n if (options.addBreakTokens === true) {\n return [simpleTokens.emptyMap, new Token(Type.break)]\n }\n return simpleTokens.emptyMap\n }\n refStack = Ref.createCheck(refStack, obj)\n /** @type {TokenOrNestedTokens[]} */\n const entries = []\n let i = 0\n for (const key of keys) {\n entries[i++] = [\n objectToTokens(key, options, refStack),\n objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack)\n ]\n }\n sortMapEntries(entries, options)\n if (options.addBreakTokens) {\n return [new Token(Type.map, length), entries, new Token(Type.break)]\n }\n return [new Token(Type.map, length), entries]\n }\n}\n\ntypeEncoders.Map = typeEncoders.Object\ntypeEncoders.Buffer = typeEncoders.Uint8Array\nfor (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {\n typeEncoders[`${typ}Array`] = typeEncoders.DataView\n}\n\n/**\n * @param {any} obj\n * @param {EncodeOptions} [options]\n * @param {Reference} [refStack]\n * @returns {TokenOrNestedTokens}\n */\nfunction objectToTokens (obj, options = {}, refStack) {\n const typ = is(obj)\n const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]\n if (typeof customTypeEncoder === 'function') {\n const tokens = customTypeEncoder(obj, typ, options, refStack)\n if (tokens != null) {\n return tokens\n }\n }\n const typeEncoder = typeEncoders[typ]\n if (!typeEncoder) {\n throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)\n }\n return typeEncoder(obj, typ, options, refStack)\n}\n\n/*\nCBOR key sorting is a mess.\n\nThe canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9\nincludes the wording:\n\n> The keys in every map must be sorted lowest value to highest.\n> Sorting is performed on the bytes of the representation of the key\n> data items without paying attention to the 3/5 bit splitting for\n> major types.\n> ...\n> * If two keys have different lengths, the shorter one sorts\n earlier;\n> * If two keys have the same length, the one with the lower value\n in (byte-wise) lexical order sorts earlier.\n\n1. It is not clear what \"bytes of the representation of the key\" means: is it\n the CBOR representation, or the binary representation of the object itself?\n Consider the int and uint difference here.\n2. It is not clear what \"without paying attention to\" means: do we include it\n and compare on that? Or do we omit the special prefix byte, (mostly) treating\n the key in its plain binary representation form.\n\nThe FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR\nwording and clarifies it according to their understanding.\nhttps://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding\n\n> The keys in every map must be sorted lowest value to highest. Sorting is\n> performed on the bytes of the representation of the key data items without\n> paying attention to the 3/5 bit splitting for major types. The sorting rules\n> are:\n> * If the major types are different, the one with the lower value in numerical\n> order sorts earlier.\n> * If two keys have different lengths, the shorter one sorts earlier;\n> * If two keys have the same length, the one with the lower value in\n> (byte-wise) lexical order sorts earlier.\n\nSome other implementations, such as borc, do a full encode then do a\nlength-first, byte-wise-second comparison:\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358\nhttps://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151\n\nThis has the benefit of being able to easily handle arbitrary keys, including\ncomplex types (maps and arrays).\n\nWe'll opt for the FIDO approach, since it affords some efficies since we don't\nneed a full encode of each key to determine order and can defer to the types\nto determine how to most efficiently order their values (i.e. int and uint\nordering can be done on the numbers, no need for byte-wise, for example).\n\nRecommendation: stick to single key types or you'll get into trouble, and prefer\nstring keys because it's much simpler that way.\n*/\n\n/*\n(UPDATE, Dec 2020)\nhttps://tools.ietf.org/html/rfc8949 is the updated CBOR spec and clarifies some\nof the questions above with a new recommendation for sorting order being much\ncloser to what would be expected in other environments (i.e. no length-first\nweirdness).\nThis new sorting order is not yet implemented here but could be added as an\noption. \"Determinism\" (canonicity) is system dependent and it's difficult to\nchange existing systems that are built with existing expectations. So if a new\nordering is introduced here, the old needs to be kept as well with the user\nhaving the option.\n*/\n\n/**\n * @param {TokenOrNestedTokens[]} entries\n * @param {EncodeOptions} options\n */\nfunction sortMapEntries (entries, options) {\n if (options.mapSorter) {\n entries.sort(options.mapSorter)\n }\n}\n\n/**\n * @param {(Token|Token[])[]} e1\n * @param {(Token|Token[])[]} e2\n * @returns {number}\n */\nfunction mapSorter (e1, e2) {\n // the key position ([0]) could have a single token or an array\n // almost always it'll be a single token but complex key might get involved\n /* c8 ignore next 2 */\n const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]\n const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]\n\n // different key types\n if (keyToken1.type !== keyToken2.type) {\n return keyToken1.type.compare(keyToken2.type)\n }\n\n const major = keyToken1.type.major\n // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)\n const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)\n /* c8 ignore next 5 */\n if (tcmp === 0) {\n // duplicate key or complex type where the first token matched,\n // i.e. a map or array and we're only comparing the opening token\n console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')\n }\n return tcmp\n}\n\n/**\n * @param {Bl} buf\n * @param {TokenOrNestedTokens} tokens\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n */\nfunction tokensToEncoded (buf, tokens, encoders, options) {\n if (Array.isArray(tokens)) {\n for (const token of tokens) {\n tokensToEncoded(buf, token, encoders, options)\n }\n } else {\n encoders[tokens.type.major](buf, tokens, options)\n }\n}\n\n/**\n * @param {any} data\n * @param {TokenTypeEncoder[]} encoders\n * @param {EncodeOptions} options\n * @returns {Uint8Array}\n */\nfunction encodeCustom (data, encoders, options) {\n const tokens = objectToTokens(data, options)\n if (!Array.isArray(tokens) && options.quickEncodeToken) {\n const quickBytes = options.quickEncodeToken(tokens)\n if (quickBytes) {\n return quickBytes\n }\n const encoder = encoders[tokens.type.major]\n if (encoder.encodedSize) {\n const size = encoder.encodedSize(tokens, options)\n const buf = new Bl(size)\n encoder(buf, tokens, options)\n /* c8 ignore next 4 */\n // this would be a problem with encodedSize() functions\n if (buf.chunks.length !== 1) {\n throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)\n }\n return asU8A(buf.chunks[0])\n }\n }\n buf.reset()\n tokensToEncoded(buf, tokens, encoders, options)\n return buf.toBytes(true)\n}\n\n/**\n * @param {any} data\n * @param {EncodeOptions} [options]\n * @returns {Uint8Array}\n */\nfunction encode (data, options) {\n options = Object.assign({}, defaultEncodeOptions, options)\n return encodeCustom(data, cborEncoders, options)\n}\n\nexport { objectToTokens, encode, encodeCustom, Ref }\n", "import { decodeErrPrefix } from './common.js'\nimport { Type } from './token.js'\nimport { jump, quick } from './jump.js'\n\n/**\n * @typedef {import('./token.js').Token} Token\n * @typedef {import('../interface').DecodeOptions} DecodeOptions\n * @typedef {import('../interface').DecodeTokenizer} DecodeTokenizer\n */\n\nconst defaultDecodeOptions = {\n strict: false,\n allowIndefinite: true,\n allowUndefined: true,\n allowBigInt: true\n}\n\n/**\n * @implements {DecodeTokenizer}\n */\nclass Tokeniser {\n /**\n * @param {Uint8Array} data\n * @param {DecodeOptions} options\n */\n constructor (data, options = {}) {\n this._pos = 0\n this.data = data\n this.options = options\n }\n\n pos () {\n return this._pos\n }\n\n done () {\n return this._pos >= this.data.length\n }\n\n next () {\n const byt = this.data[this._pos]\n let token = quick[byt]\n if (token === undefined) {\n const decoder = jump[byt]\n /* c8 ignore next 4 */\n // if we're here then there's something wrong with our jump or quick lists!\n if (!decoder) {\n throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)\n }\n const minor = byt & 31\n token = decoder(this.data, this._pos, minor, this.options)\n }\n // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)\n this._pos += token.encodedLength\n return token\n }\n}\n\nconst DONE = Symbol.for('DONE')\nconst BREAK = Symbol.for('BREAK')\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToArray (token, tokeniser, options) {\n const arr = []\n for (let i = 0; i < token.value; i++) {\n const value = tokensToObject(tokeniser, options)\n if (value === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length array\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)\n }\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)\n }\n arr[i] = value\n }\n return arr\n}\n\n/**\n * @param {Token} token\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokenToMap (token, tokeniser, options) {\n const useMaps = options.useMaps === true\n const obj = useMaps ? undefined : {}\n const m = useMaps ? new Map() : undefined\n for (let i = 0; i < token.value; i++) {\n const key = tokensToObject(tokeniser, options)\n if (key === BREAK) {\n if (token.value === Infinity) {\n // normal end to indefinite length map\n break\n }\n throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)\n }\n if (key === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)\n }\n if (useMaps !== true && typeof key !== 'string') {\n throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)\n }\n if (options.rejectDuplicateMapKeys === true) {\n // @ts-ignore\n if ((useMaps && m.has(key)) || (!useMaps && (key in obj))) {\n throw new Error(`${decodeErrPrefix} found repeat map key \"${key}\"`)\n }\n }\n const value = tokensToObject(tokeniser, options)\n if (value === DONE) {\n throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)\n }\n if (useMaps) {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n m.set(key, value)\n } else {\n // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types\n obj[key] = value\n }\n }\n // @ts-ignore c'mon man\n return useMaps ? m : obj\n}\n\n/**\n * @param {DecodeTokenizer} tokeniser\n * @param {DecodeOptions} options\n * @returns {any|BREAK|DONE}\n */\nfunction tokensToObject (tokeniser, options) {\n // should we support array as an argument?\n // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?\n if (tokeniser.done()) {\n return DONE\n }\n\n const token = tokeniser.next()\n\n if (token.type === Type.break) {\n return BREAK\n }\n\n if (token.type.terminal) {\n return token.value\n }\n\n if (token.type === Type.array) {\n return tokenToArray(token, tokeniser, options)\n }\n\n if (token.type === Type.map) {\n return tokenToMap(token, tokeniser, options)\n }\n\n if (token.type === Type.tag) {\n if (options.tags && typeof options.tags[token.value] === 'function') {\n const tagged = tokensToObject(tokeniser, options)\n return options.tags[token.value](tagged)\n }\n throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)\n }\n /* c8 ignore next */\n throw new Error('unsupported')\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {[any, Uint8Array]}\n */\nfunction decodeFirst (data, options) {\n if (!(data instanceof Uint8Array)) {\n throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)\n }\n options = Object.assign({}, defaultDecodeOptions, options)\n const tokeniser = options.tokenizer || new Tokeniser(data, options)\n const decoded = tokensToObject(tokeniser, options)\n if (decoded === DONE) {\n throw new Error(`${decodeErrPrefix} did not find any content to decode`)\n }\n if (decoded === BREAK) {\n throw new Error(`${decodeErrPrefix} got unexpected break`)\n }\n return [decoded, data.subarray(tokeniser.pos())]\n}\n\n/**\n * @param {Uint8Array} data\n * @param {DecodeOptions} [options]\n * @returns {any}\n */\nfunction decode (data, options) {\n const [decoded, remainder] = decodeFirst(data, options)\n if (remainder.length > 0) {\n throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)\n }\n return decoded\n}\n\nexport { Tokeniser, tokensToObject, decode, decodeFirst }\n", "import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidMultihashError } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport * as cborg from 'cborg'\nimport { base36 } from 'multiformats/bases/base36'\nimport { CID, type MultihashDigest } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidRecordDataError, InvalidValueError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport type { IPNSRecord, IPNSRecordV2, IPNSRecordData } from './index.js'\nimport type { PublicKey } from '@libp2p/interface'\n\nconst log = logger('ipns:utils')\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nconst LIBP2P_CID_CODEC = 0x72\nconst IDENTITY_CODEC = 0x0\nconst SHA2_256_CODEC = 0x12\n\n/**\n * Extracts a public key from the passed PeerId, falling back to the pubKey\n * embedded in the ipns record\n */\nexport function extractPublicKeyFromIPNSRecord (record: IPNSRecord | IPNSRecordV2): PublicKey | undefined {\n let pubKey: PublicKey | undefined\n\n if (record.pubKey != null) {\n try {\n pubKey = publicKeyFromProtobuf(record.pubKey)\n } catch (err) {\n log.error(err)\n throw err\n }\n }\n\n if (pubKey != null) {\n return pubKey\n }\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV1Sig (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n\n return uint8ArrayConcat([value, validity, validityTypeBuffer])\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV2Sig (data: Uint8Array): Uint8Array {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport function marshalIPNSRecord (obj: IPNSRecord | IPNSRecordV2): Uint8Array {\n if ('signatureV1' in obj) {\n return IpnsEntry.encode({\n value: uint8ArrayFromString(obj.value),\n signatureV1: obj.signatureV1,\n validityType: obj.validityType,\n validity: uint8ArrayFromString(obj.validity),\n sequence: obj.sequence,\n ttl: obj.ttl,\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n } else {\n return IpnsEntry.encode({\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n }\n}\n\nexport function unmarshalIPNSRecord (buf: Uint8Array): IPNSRecord {\n const message = IpnsEntry.decode(buf)\n\n // protobufjs returns bigints as numbers\n if (message.sequence != null) {\n message.sequence = BigInt(message.sequence)\n }\n\n // protobufjs returns bigints as numbers\n if (message.ttl != null) {\n message.ttl = BigInt(message.ttl)\n }\n\n // Check if we have the data field. If we don't, we fail. We've been producing\n // V1+V2 records for quite a while and we don't support V1-only records during\n // validation any more\n if (message.signatureV2 == null || message.data == null) {\n throw new SignatureVerificationError('Missing data or signatureV2')\n }\n\n const data = parseCborData(message.data)\n const value = normalizeByteValue(data.Value)\n const validity = uint8ArrayToString(data.Validity)\n\n if (message.value != null && message.signatureV1 != null) {\n // V1+V2\n validateCborDataMatchesPbData(message)\n\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV1: message.signatureV1,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else if (message.signatureV2 != null) {\n // V2-only\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else {\n throw new Error('invalid record: does not include signatureV1 or signatureV2')\n }\n}\n\nexport function multihashToIPNSRoutingKey (digest: MultihashDigest<0x00 | 0x12>): Uint8Array {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n digest.bytes\n ])\n}\n\nexport function multihashFromIPNSRoutingKey (key: Uint8Array): MultihashDigest<0x00 | 0x12> {\n const digest = Digest.decode(key.slice(IPNS_PREFIX.length))\n\n if (!isCodec(digest, IDENTITY_CODEC) && !isCodec(digest, SHA2_256_CODEC)) {\n throw new InvalidMultihashError('Multihash in IPNS key was not identity or sha2-256')\n }\n\n return digest\n}\n\nexport function createCborData (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array, sequence: bigint, ttl: bigint): Uint8Array {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n const data = {\n Value: value,\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport function parseCborData (buf: Uint8Array): IPNSRecordData {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n\nexport function normalizeByteValue (value: Uint8Array): string {\n const string = uint8ArrayToString(value).trim()\n\n // if we have a path, check it is a valid path\n if (string.startsWith('/')) {\n return string\n }\n\n // try parsing what we have as CID bytes or a CID string\n try {\n return `/ipfs/${CID.decode(value).toV1().toString()}`\n } catch {\n // fall through\n }\n\n try {\n return `/ipfs/${CID.parse(string).toV1().toString()}`\n } catch {\n // fall through\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\n/**\n * Normalizes the given record value. It ensures it is a PeerID, a CID or a\n * string starting with '/'. PeerIDs become `/ipns/${cidV1Libp2pKey}`,\n * CIDs become `/ipfs/${cidAsV1}`.\n */\nexport function normalizeValue (value?: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string): string {\n if (value != null) {\n const cid = asCID(value)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code === LIBP2P_CID_CODEC) {\n return `/ipns/${cid.toString(base36)}`\n }\n\n return `/ipfs/${cid.toV1().toString()}`\n }\n\n if (hasBytes(value)) {\n return `/ipns/${base36.encode(value.bytes)}`\n }\n\n // if we have a path, check it is a valid path\n const string = value.toString().trim()\n\n if (string.startsWith('/') && string.length > 1) {\n return string\n }\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\nfunction validateCborDataMatchesPbData (entry: IpnsEntry): void {\n if (entry.data == null) {\n throw new InvalidRecordDataError('Record data is missing')\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"value\" did not match between protobuf and CBOR')\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"validity\" did not match between protobuf and CBOR')\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw new SignatureVerificationError('Field \"validityType\" did not match between protobuf and CBOR')\n }\n\n if (data.Sequence !== entry.sequence) {\n throw new SignatureVerificationError('Field \"sequence\" did not match between protobuf and CBOR')\n }\n\n if (data.TTL !== entry.ttl) {\n throw new SignatureVerificationError('Field \"ttl\" did not match between protobuf and CBOR')\n }\n}\n\nfunction hasBytes (obj?: any): obj is { bytes: Uint8Array } {\n return obj.bytes instanceof Uint8Array\n}\n\nfunction hasToCID (obj?: any): obj is { toCID(): CID } {\n return typeof obj?.toCID === 'function'\n}\n\nfunction asCID (obj?: any): CID | null {\n if (hasToCID(obj)) {\n return obj.toCID()\n }\n\n // try parsing as a CID string\n try {\n return CID.parse(obj)\n } catch {\n // fall through\n }\n\n return CID.asCID(obj)\n}\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n", "import NanoDate from 'timestamp-nano'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { unmarshalIPNSRecord } from './utils.js'\n\n/**\n * Selects the latest valid IPNS record from an array of marshalled IPNS records.\n *\n * Records are sorted by:\n * 1. Sequence number (higher takes precedence)\n * 2. Validity time for EOL records with same sequence number (longer lived record takes precedence)\n *\n * @param key - The routing key for the IPNS record\n * @param data - Array of marshalled IPNS records to select from\n * @returns The index of the most valid record from the input array\n */\nexport function ipnsSelector (key: Uint8Array, data: Uint8Array[]): number {\n const entries = data.map((buf, index) => ({\n record: unmarshalIPNSRecord(buf),\n index\n }))\n\n entries.sort((a, b) => {\n // Before we'd sort based on the signature version. Unmarshal now fails if\n // a record does not have SignatureV2, so that is no longer needed. V1-only\n // records haven't been issues in a long time.\n\n const aSeq = a.record.sequence\n const bSeq = b.record.sequence\n\n // choose later sequence number\n if (aSeq > bSeq) {\n return -1\n } else if (aSeq < bSeq) {\n return 1\n }\n\n if (a.record.validityType === IpnsEntry.ValidityType.EOL && b.record.validityType === IpnsEntry.ValidityType.EOL) {\n // choose longer lived record if sequence numbers the same\n const recordAValidityDate = NanoDate.fromString(a.record.validity).toDate()\n const recordBValidityDate = NanoDate.fromString(b.record.validity).toDate()\n\n if (recordAValidityDate.getTime() > recordBValidityDate.getTime()) {\n return -1\n }\n\n if (recordAValidityDate.getTime() < recordBValidityDate.getTime()) {\n return 1\n }\n }\n\n return 0\n })\n\n return entries[0].index\n}\n", "import { publicKeyFromMultihash } from '@libp2p/crypto/keys'\nimport { logger } from '@libp2p/logger'\nimport NanoDate from 'timestamp-nano'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { InvalidEmbeddedPublicKeyError, RecordExpiredError, RecordTooLargeError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { extractPublicKeyFromIPNSRecord, ipnsRecordDataForV2Sig, isCodec, multihashFromIPNSRoutingKey, multihashToIPNSRoutingKey, unmarshalIPNSRecord } from './utils.js'\nimport type { PublicKey } from '@libp2p/interface'\n\nconst log = logger('ipns:validator')\n\n/**\n * Limit valid IPNS record sizes to 10kb\n */\nconst MAX_RECORD_SIZE = 1024 * 10\n\n/**\n * Validates the given IPNS Record against the given public key. We need a \"raw\"\n * record in order to be able to access to all of its fields.\n */\nexport const validate = async (publicKey: PublicKey, marshalledRecord: Uint8Array): Promise<void> => {\n // unmarshal ensures that (1) SignatureV2 and Data are present, (2) that ValidityType\n // and Validity are of valid types and have a value, (3) that CBOR data matches protobuf\n // if it's a V1+V2 record.\n const record = unmarshalIPNSRecord(marshalledRecord)\n\n // Validate Signature V2\n let isValid\n\n try {\n const dataForSignature = ipnsRecordDataForV2Sig(record.data)\n isValid = await publicKey.verify(dataForSignature, record.signatureV2)\n } catch (err) {\n isValid = false\n }\n\n if (!isValid) {\n log.error('record signature verification failed')\n throw new SignatureVerificationError('Record signature verification failed')\n }\n\n // Validate according to the validity type\n if (record.validityType === IpnsEntry.ValidityType.EOL) {\n if (NanoDate.fromString(record.validity).toDate().getTime() < Date.now()) {\n log.error('record has expired')\n throw new RecordExpiredError('record has expired')\n }\n } else if (record.validityType != null) {\n log.error('the validity type is unsupported')\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n log('ipns record for %s is valid', record.value)\n}\n\n/**\n * Validate the given IPNS record against the given routing key.\n *\n * @see https://specs.ipfs.tech/ipns/ipns-record/#routing-record for the binary format of the routing key\n *\n * @param routingKey - The routing key in binary format: binary(ascii(IPNS_PREFIX) + multihash(public key))\n * @param marshalledRecord - The marshalled record to validate.\n */\nexport async function ipnsValidator (routingKey: Uint8Array, marshalledRecord: Uint8Array): Promise<void> {\n if (marshalledRecord.byteLength > MAX_RECORD_SIZE) {\n throw new RecordTooLargeError('The record is too large')\n }\n\n // try to extract public key from routing key\n const routingMultihash = multihashFromIPNSRoutingKey(routingKey)\n let routingPubKey: PublicKey | undefined\n\n // identity hash\n if (isCodec(routingMultihash, 0x0)) {\n routingPubKey = publicKeyFromMultihash(routingMultihash)\n }\n\n // extract public key from record\n const receivedRecord = unmarshalIPNSRecord(marshalledRecord)\n const recordPubKey = extractPublicKeyFromIPNSRecord(receivedRecord) ?? routingPubKey\n\n if (recordPubKey == null) {\n throw new InvalidEmbeddedPublicKeyError('Could not extract public key from IPNS record or routing key')\n }\n\n const expectedRoutingKey = multihashToIPNSRoutingKey(recordPubKey.toMultihash())\n\n if (!uint8ArrayEquals(expectedRoutingKey, routingKey)) {\n throw new InvalidEmbeddedPublicKeyError('Embedded public key did not match routing key')\n }\n\n // Record validation\n await validate(recordPubKey, marshalledRecord)\n}\n", "/**\n * Progress events are emitted during long running operations\n */\nexport interface ProgressEvent<T extends string = any, D = unknown> {\n /**\n * The event type\n */\n type: T\n\n /**\n * Context-specific event information\n */\n detail: D\n}\n\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent<D = unknown, T extends string = any> extends Event implements ProgressEvent<T, D> {\n public type: T\n public detail: D\n\n constructor (type: T, detail?: D) {\n super(type)\n\n this.type = type\n // @ts-expect-error detail may be undefined\n this.detail = detail\n }\n}\n\n/**\n * Define an `onProgress` callback that can be invoked with `ProgressEvent`s\n *\n * @example\n *\n * ```typescript\n * type MyOperationProgressEvents =\n * ProgressEvent<'operation:start'> |\n * ProgressEvent<'operation:success', Result> |\n * ProgressEvent<'operation:error', Error>\n *\n * export interface MyOperationOptions extends ProgressOptions<MyOperationProgressEvents> {\n * // define options here\n * }\n * ```\n */\nexport interface ProgressOptions<Event extends ProgressEvent = any> {\n onProgress?: (evt: Event) => void\n}\n", "import hashlru from 'hashlru'\nimport { RecordType } from '../index.js'\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js'\nimport type { Answer, DNSResponse } from '../index.js'\n\ninterface CachedAnswer {\n expires: number\n value: Answer\n}\n\nexport interface AnswerCache {\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined\n add (domain: string, answer: Answer): void\n remove (domain: string, type: ResponseType): void\n clear (): void\n}\n\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n private readonly lru: ReturnType<typeof hashlru>\n\n constructor (maxSize: number) {\n this.lru = hashlru(maxSize)\n }\n\n get (fqdn: string, types: RecordType[]): DNSResponse | undefined {\n let foundAllAnswers = true\n const answers: Answer[] = []\n\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type)\n\n if (cached.length === 0) {\n foundAllAnswers = false\n break\n }\n\n answers.push(...cached)\n }\n\n if (foundAllAnswers) {\n return toDNSResponse({ answers })\n }\n }\n\n private getAnswers (domain: string, type: RecordType): Answer[] {\n const key = `${domain.toLowerCase()}-${type}`\n const answers: CachedAnswer[] = this.lru.get(key)\n\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now()\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }))\n\n if (cachedAnswers.length === 0) {\n this.lru.remove(key)\n }\n\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers\n }\n\n return []\n }\n\n add (domain: string, answer: Answer): void {\n const key = `${domain.toLowerCase()}-${answer.type}`\n\n const answers: CachedAnswer[] = this.lru.get(key) ?? []\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n })\n\n this.lru.set(key, answers)\n }\n\n remove (domain: string, type: ResponseType): void {\n const key = `${domain.toLowerCase()}-${type}`\n\n this.lru.remove(key)\n }\n\n clear (): void {\n this.lru.clear()\n }\n}\n\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache (size: number): AnswerCache {\n return new CachedAnswers(size)\n}\n", "/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\n\nimport { DNS as DNSClass } from './dns.js'\nimport type { DNSResolver } from './resolvers/index.js'\nimport type { ProgressEvent, ProgressOptions } from 'progress-events'\n\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport enum RecordType {\n A = 1,\n CNAME = 5,\n TXT = 16,\n AAAA = 28\n}\n\nexport interface Question {\n /**\n * The record name requested.\n */\n name: string\n\n /**\n * The type of DNS record requested.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\n type: RecordType\n}\n\nexport interface Answer {\n /**\n * The record owner.\n */\n name: string\n\n /**\n * The type of DNS record.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4\n */\n type: RecordType\n\n /**\n * The number of seconds the answer can be stored in cache before it is\n * considered stale.\n */\n TTL: number\n\n /**\n * The value of the DNS record for the given name and type. The data will be\n * in text for standardized record types and in hex for unknown types.\n */\n data: string\n}\n\nexport interface DNSResponse {\n /**\n * The Response Code of the DNS Query.\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n */\n Status: number\n\n /**\n * If true, it means the truncated bit was set. This happens when the DNS\n * answer is larger than a single UDP or TCP packet.\n */\n TC: boolean\n\n /**\n * If true, it means the Recursive Desired bit was set.\n */\n RD: boolean\n\n /**\n * If true, it means the Recursion Available bit was set.\n */\n RA: boolean\n\n /**\n * If true, it means that every record in the answer was verified with DNSSEC.\n */\n AD: boolean\n\n /**\n * If true, the client asked to disable DNSSEC validation.\n */\n CD: boolean\n\n /**\n * The records that were requested.\n */\n Question: Question[]\n\n /**\n * Values for the records that were requested.\n */\n Answer: Answer[]\n}\n\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32\n\nexport interface QueryOptions extends ProgressOptions<ResolveDnsProgressEvents> {\n signal?: AbortSignal\n\n /**\n * Do not use cached DNS entries\n *\n * @default false\n */\n cached?: boolean\n\n /**\n * The type or types of DNS records to resolve\n *\n * @default [RecordType.A, RecordType.AAAA]\n */\n types?: RecordType | RecordType[]\n}\n\nexport interface DNS {\n query(fqdn: string, options?: QueryOptions): Promise<DNSResponse>\n}\n\nexport type ResolveDnsProgressEvents =\n ProgressEvent<'dns:cache', string> |\n ProgressEvent<'dns:query', string> |\n ProgressEvent<'dns:response', DNSResponse> |\n ProgressEvent<'dns:error', Error>\n\nexport type DNSResolvers = Record<string, DNSResolver | DNSResolver[]>\n\nexport interface DNSInit {\n /**\n * A set of resolvers used to answer DNS queries\n *\n * String keys control which resolvers are used for which TLDs.\n *\n * @example\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsOverHttps } from '@multiformats/dns'\n *\n * const resolver = dns({\n * resolvers: {\n * // only used for .com domains\n * 'com.': dnsOverHttps('https://example-1.com'),\n *\n * // only used for .net domains, can be an array\n * 'net.': [\n * dnsOverHttps('https://example-2.com'),\n * dnsOverHttps('https://example-3.com'),\n * ],\n *\n * // used for everything else (can be an array)\n * '.': dnsOverHttps('https://example-4.com')\n * }\n * })\n * ```\n */\n resolvers?: DNSResolvers\n\n /**\n * To avoid repeating DNS lookups, successful answers are cached according to\n * their TTL. To avoid exhausting memory, this option controls how many\n * answers to cache.\n *\n * @default 1000\n */\n cacheSize?: number\n}\n\nexport function dns (init: DNSInit = {}): DNS {\n return new DNSClass(init)\n}\n", "export class DNSLinkNotFoundError extends Error {\n static name = 'DNSLinkNotFoundError'\n\n constructor (message = 'DNSLink not found') {\n super(message)\n this.name = 'DNSLinkNotFoundError'\n }\n}\n\nexport class RecordsFailedValidationError extends Error {\n static name = 'RecordsFailedValidationError'\n\n constructor (message = 'Records failed validation') {\n super(message)\n this.name = 'RecordsFailedValidationError'\n }\n}\n\nexport class UnsupportedMultibasePrefixError extends Error {\n static name = 'UnsupportedMultibasePrefixError'\n\n constructor (message = 'Unsupported multibase prefix') {\n super(message)\n this.name = 'UnsupportedMultibasePrefixError'\n }\n}\n\nexport class UnsupportedMultihashCodecError extends Error {\n static name = 'UnsupportedMultihashCodecError'\n\n constructor (message = 'Unsupported multihash codec') {\n super(message)\n this.name = 'UnsupportedMultihashCodecError'\n }\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n\n constructor (message = 'Invalid value') {\n super(message)\n this.name = 'InvalidValueError'\n }\n}\n\nexport class InvalidTopicError extends Error {\n static name = 'InvalidTopicError'\n\n constructor (message = 'Invalid topic') {\n super(message)\n this.name = 'InvalidTopicError'\n }\n}\n", "import { } from '@libp2p/interface'\nimport { peerIdFromCID, peerIdFromString } from '@libp2p/peer-id'\nimport { RecordType } from '@multiformats/dns'\nimport { CID } from 'multiformats/cid'\nimport { DNSLinkNotFoundError } from './errors.js'\nimport type { ResolveDNSLinkOptions } from './index.js'\nimport type { Logger, PeerId } from '@libp2p/interface'\nimport type { Answer, DNS } from '@multiformats/dns'\n\nconst MAX_RECURSIVE_DEPTH = 32\n\nexport interface DNSLinkResult {\n answer: Answer\n value: string\n}\n\nasync function recursiveResolveDnslink (domain: string, depth: number, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n if (depth === 0) {\n throw new Error('recursion limit exceeded')\n }\n\n log('query %s for TXT and CNAME records', domain)\n const txtRecordsResponse = await dns.query(domain, {\n ...options,\n types: [\n RecordType.TXT\n ]\n })\n\n // sort the TXT records to ensure deterministic processing\n const txtRecords = (txtRecordsResponse?.Answer ?? [])\n .sort((a, b) => a.data.localeCompare(b.data))\n\n log('found %d TXT records for %s', txtRecords.length, domain)\n\n for (const answer of txtRecords) {\n try {\n let result = answer.data\n\n // strip leading and trailing \" characters\n if (result.startsWith('\"') && result.endsWith('\"')) {\n result = result.substring(1, result.length - 1)\n }\n\n if (!result.startsWith('dnslink=')) {\n // invalid record?\n continue\n }\n\n log('%s TXT %s', answer.name, result)\n\n result = result.replace('dnslink=', '')\n\n // result is now a `/ipfs/<cid>` or `/ipns/<cid>` string\n const [, protocol, domainOrCID, ...rest] = result.split('/') // e.g. [\"\", \"ipfs\", \"<cid>\"]\n\n if (protocol === 'ipfs') {\n try {\n const cid = CID.parse(domainOrCID)\n\n // if the result is a CID, we've reached the end of the recursion\n return {\n value: `/ipfs/${cid}${rest.length > 0 ? `/${rest.join('/')}` : ''}`,\n answer\n }\n } catch {}\n } else if (protocol === 'ipns') {\n try {\n let peerId: PeerId\n\n // eslint-disable-next-line max-depth\n if (domainOrCID.charAt(0) === '1' || domainOrCID.charAt(0) === 'Q') {\n peerId = peerIdFromString(domainOrCID)\n } else {\n // try parsing as a CID\n peerId = peerIdFromCID(CID.parse(domainOrCID))\n }\n\n // if the result is a PeerId, we've reached the end of the recursion\n return {\n value: `/ipns/${peerId}${rest.length > 0 ? `/${rest.join('/')}` : ''}`,\n answer\n }\n } catch {}\n\n // if the result was another IPNS domain, try to follow it\n return await recursiveResolveDomain(domainOrCID, depth - 1, dns, log, options)\n } else if (protocol === 'dnslink') {\n // if the result was another DNSLink domain, try to follow it\n return await recursiveResolveDomain(domainOrCID, depth - 1, dns, log, options)\n } else {\n log('unknown protocol \"%s\" in DNSLink record for domain: %s', protocol, domain)\n continue\n }\n } catch (err: any) {\n log.error('could not parse DNS link record for domain %s, %s', domain, answer.data, err)\n }\n }\n\n // no dnslink records found, try CNAMEs\n log('no DNSLink records found for %s, falling back to CNAME', domain)\n\n const cnameRecordsResponse = await dns.query(domain, {\n ...options,\n types: [\n RecordType.CNAME\n ]\n })\n\n // sort the CNAME records to ensure deterministic processing\n const cnameRecords = (cnameRecordsResponse?.Answer ?? [])\n .sort((a, b) => a.data.localeCompare(b.data))\n\n log('found %d CNAME records for %s', cnameRecords.length, domain)\n\n for (const cname of cnameRecords) {\n try {\n return await recursiveResolveDomain(cname.data, depth - 1, dns, log, options)\n } catch (err: any) {\n log.error('domain %s cname %s had no DNSLink records', domain, cname.data, err)\n }\n }\n\n throw new DNSLinkNotFoundError(`No DNSLink records found for domain: ${domain}`)\n}\n\nasync function recursiveResolveDomain (domain: string, depth: number, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n if (depth === 0) {\n throw new Error('recursion limit exceeded')\n }\n\n // the DNSLink spec says records MUST be stored on the `_dnslink.` subdomain\n // so start looking for records there, we will fall back to the bare domain\n // if none are found\n if (!domain.startsWith('_dnslink.')) {\n domain = `_dnslink.${domain}`\n }\n\n try {\n return await recursiveResolveDnslink(domain, depth, dns, log, options)\n } catch (err: any) {\n // If the code is not ENOTFOUND or ERR_DNSLINK_NOT_FOUND or ENODATA then throw the error\n if (err.code !== 'ENOTFOUND' && err.code !== 'ENODATA' && err.name !== 'DNSLinkNotFoundError' && err.name !== 'NotFoundError') {\n throw err\n }\n\n if (domain.startsWith('_dnslink.')) {\n // The supplied domain contains a _dnslink component\n // Check the non-_dnslink domain\n domain = domain.replace('_dnslink.', '')\n } else {\n // Check the _dnslink subdomain\n domain = `_dnslink.${domain}`\n }\n\n // If this throws then we propagate the error\n return recursiveResolveDnslink(domain, depth, dns, log, options)\n }\n}\n\nexport async function resolveDNSLink (domain: string, dns: DNS, log: Logger, options: ResolveDNSLinkOptions = {}): Promise<DNSLinkResult> {\n return recursiveResolveDomain(domain, options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH, dns, log, options)\n}\n", "import { CustomProgressEvent } from 'progress-events'\nimport type { GetOptions, PutOptions } from './index.js'\nimport type { IPNSRouting } from '../index.js'\nimport type { Routing } from '@helia/interface'\nimport type { ProgressEvent } from 'progress-events'\n\nexport interface HeliaRoutingComponents {\n routing: Routing\n}\n\nexport type HeliaRoutingProgressEvents =\n ProgressEvent<'ipns:routing:helia:error', Error>\n\nexport class HeliaRouting implements IPNSRouting {\n private readonly routing: Routing\n\n constructor (routing: Routing) {\n this.routing = routing\n }\n\n async put (routingKey: Uint8Array, marshaledRecord: Uint8Array, options: PutOptions = {}): Promise<void> {\n try {\n await this.routing.put(routingKey, marshaledRecord, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<Uint8Array> {\n try {\n return await this.routing.get(routingKey, options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:helia:error', err))\n throw err\n }\n }\n}\n\n/**\n * The helia routing uses any available Routers configured on the passed Helia\n * node. This could be libp2p, HTTP API Delegated Routing, etc.\n */\nexport function helia (routing: Routing): IPNSRouting {\n return new HeliaRouting(routing)\n}\n", "/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nimport { type Codec, decodeMessage, type DecodeOptions, encodeMessage, message } from 'protons-runtime'\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface Record {\n key: Uint8Array\n value: Uint8Array\n timeReceived: string\n}\n\nexport namespace Record {\n let _codec: Codec<Record>\n\n export const codec = (): Codec<Record> => {\n if (_codec == null) {\n _codec = message<Record>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if ((obj.key != null && obj.key.byteLength > 0)) {\n w.uint32(10)\n w.bytes(obj.key)\n }\n\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18)\n w.bytes(obj.value)\n }\n\n if ((obj.timeReceived != null && obj.timeReceived !== '')) {\n w.uint32(42)\n w.string(obj.timeReceived)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {\n key: uint8ArrayAlloc(0),\n value: uint8ArrayAlloc(0),\n timeReceived: ''\n }\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.bytes()\n break\n }\n case 2: {\n obj.value = reader.bytes()\n break\n }\n case 5: {\n obj.timeReceived = reader.string()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<Record>): Uint8Array => {\n return encodeMessage(obj, Record.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<Record>): Record => {\n return decodeMessage(buf, Record.codec(), opts)\n }\n}\n", "/**\n * Convert a JavaScript date into an `RFC3339Nano` formatted\n * string\n */\nexport function toRFC3339 (time: Date): string {\n const year = time.getUTCFullYear()\n const month = String(time.getUTCMonth() + 1).padStart(2, '0')\n const day = String(time.getUTCDate()).padStart(2, '0')\n const hour = String(time.getUTCHours()).padStart(2, '0')\n const minute = String(time.getUTCMinutes()).padStart(2, '0')\n const seconds = String(time.getUTCSeconds()).padStart(2, '0')\n const milliseconds = time.getUTCMilliseconds()\n const nanoseconds = String(milliseconds * 1000 * 1000).padStart(9, '0')\n\n return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`\n}\n\n/**\n * Parses a date string formatted as `RFC3339Nano` into a\n * JavaScript Date object\n */\nexport function parseRFC3339 (time: string): Date {\n const rfc3339Matcher = new RegExp(\n // 2006-01-02T\n '(\\\\d{4})-(\\\\d{2})-(\\\\d{2})T' +\n // 15:04:05\n '(\\\\d{2}):(\\\\d{2}):(\\\\d{2})' +\n // .999999999Z\n '\\\\.(\\\\d+)Z'\n )\n const m = String(time).trim().match(rfc3339Matcher)\n\n if (m == null) {\n throw new Error('Invalid format')\n }\n\n const year = parseInt(m[1], 10)\n const month = parseInt(m[2], 10) - 1\n const date = parseInt(m[3], 10)\n const hour = parseInt(m[4], 10)\n const minute = parseInt(m[5], 10)\n const second = parseInt(m[6], 10)\n const millisecond = parseInt(m[7].slice(0, -6), 10)\n\n return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))\n}\n", "/**\n * @packageDocumentation\n *\n * This is an implementation of the [routing record format](https://github.com/libp2p/specs/blob/b9efe152c29f93f7a87931c14d78ae11e7924d5a/kad-dht/README.md?plain=1#L408-L425) used by libp2p to store data in the datastore passed to the libp2p constructor.\n *\n * @example Deserialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const buf = Uint8Array.from([0, 1, 2, 3])\n * const record = Libp2pRecord.deserialize(buf)\n * ```\n *\n * @example Serialization\n *\n * ```TypeScript\n * import { Libp2pRecord } from '@libp2p/record'\n *\n * const key = Uint8Array.from([0, 1, 2, 3])\n * const value = Uint8Array.from([0, 1, 2, 3])\n * const timeReceived = new Date()\n *\n * const record = new Libp2pRecord(key, value, timeReceived)\n * const buf = record.serialize()\n * ```\n */\n\nimport {\n Record\n} from './record.js'\nimport * as utils from './utils.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class Libp2pRecord {\n public key: Uint8Array\n public value: Uint8Array\n public timeReceived: Date\n\n constructor (key: Uint8Array, value: Uint8Array, timeReceived: Date) {\n if (!(key instanceof Uint8Array)) {\n throw new Error('key must be a Uint8Array')\n }\n\n if (!(value instanceof Uint8Array)) {\n throw new Error('value must be a Uint8Array')\n }\n\n this.key = key\n this.value = value\n this.timeReceived = timeReceived\n }\n\n serialize (): Uint8Array {\n return Record.encode(this.prepareSerialize())\n }\n\n /**\n * Return the object format ready to be given to the protobuf library.\n */\n prepareSerialize (): Record {\n return {\n key: this.key,\n value: this.value,\n timeReceived: utils.toRFC3339(this.timeReceived)\n }\n }\n\n /**\n * Decode a protobuf encoded record\n */\n static deserialize (raw: Uint8Array | Uint8ArrayList): Libp2pRecord {\n const rec = Record.decode(raw)\n\n return new Libp2pRecord(rec.key, rec.value, new Date(rec.timeReceived))\n }\n\n /**\n * Create a record from the raw object returned from the protobuf library\n */\n static fromDeserialized (obj: Record): Libp2pRecord {\n const receivedTime = utils.parseRFC3339(obj.timeReceived)\n\n if (obj.key == null) {\n throw new Error('key missing from deserialized object')\n }\n\n if (obj.value == null) {\n throw new Error('value missing from deserialized object')\n }\n\n const rec = new Libp2pRecord(\n obj.key, obj.value, receivedTime\n )\n\n return rec\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module implements the [libp2p Kademlia spec](https://github.com/libp2p/specs/blob/master/kad-dht/README.md) in TypeScript.\n *\n * The Kademlia DHT allow for several operations such as finding peers, searching for providers of DHT records, etc.\n *\n * @example Using with libp2p\n *\n * ```TypeScript\n * import { kadDHT } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * dht: kadDHT({\n * // DHT options\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to the IPFS Amino DHT\n *\n * The [Amino DHT](https://blog.ipfs.tech/2023-09-amino-refactoring/) is a public-good DHT used by IPFS to fetch content, find peers, etc.\n *\n * If you are trying to access content on the public internet, this is the implementation you want.\n *\n * ```TypeScript\n * import { kadDHT, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to a LAN-only DHT\n *\n * This DHT only works with privately dialable peers.\n *\n * This is for use when peers are on the local area network.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n *\n * @example Connecting to both a LAN-only DHT and the IPFS Amino DHT\n *\n * When using multiple DHTs, you should specify distinct datastore, metrics and\n * log prefixes to ensure that data is kept separate for each instance.\n *\n * ```TypeScript\n * import { kadDHT, removePublicAddressesMapper, removePrivateAddressesMapper } from '@libp2p/kad-dht'\n * import { createLibp2p } from 'libp2p'\n * import { peerIdFromString } from '@libp2p/peer-id'\n * import { ping } from '@libp2p/ping'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * services: {\n * lanDHT: kadDHT({\n * protocol: '/ipfs/lan/kad/1.0.0',\n * peerInfoMapper: removePublicAddressesMapper,\n * clientMode: false,\n * logPrefix: 'libp2p:dht-lan',\n * datastorePrefix: '/dht-lan',\n * metricsPrefix: 'libp2p_dht_lan'\n * }),\n * aminoDHT: kadDHT({\n * protocol: '/ipfs/kad/1.0.0',\n * peerInfoMapper: removePrivateAddressesMapper,\n * logPrefix: 'libp2p:dht-amino',\n * datastorePrefix: '/dht-amino',\n * metricsPrefix: 'libp2p_dht_amino'\n * }),\n * ping: ping(),\n * identify: identify()\n * }\n * })\n *\n * const peerId = peerIdFromString('QmFoo')\n * const peerInfo = await node.peerRouting.findPeer(peerId)\n *\n * console.info(peerInfo) // peer id, multiaddrs\n * ```\n */\n\nimport { KadDHT as KadDHTClass } from './kad-dht.js'\nimport { MessageType } from './message/dht.js'\nimport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper } from './utils.js'\nimport type { Libp2pEvents, ComponentLogger, TypedEventTarget, Metrics, PeerId, PeerInfo, PeerStore, RoutingOptions, PrivateKey } from '@libp2p/interface'\nimport type { AddressManager, ConnectionManager, Registrar } from '@libp2p/interface-internal'\nimport type { Ping } from '@libp2p/ping'\nimport type { AdaptiveTimeoutInit } from '@libp2p/utils/src/adaptive-timeout.js'\nimport type { Datastore } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\nimport type { ProgressEvent } from 'progress-events'\n\nexport { Libp2pRecord as Record } from '@libp2p/record'\nexport { removePrivateAddressesMapper, removePublicAddressesMapper, passthroughMapper }\n\n/**\n * The types of events emitted during DHT queries\n */\nexport enum EventTypes {\n SEND_QUERY = 0,\n PEER_RESPONSE,\n FINAL_PEER,\n QUERY_ERROR,\n PROVIDER,\n VALUE,\n ADD_PEER,\n DIAL_PEER\n}\n\n/**\n * The types of messages sent to peers during DHT queries\n */\nexport { MessageType }\n\nexport type MessageName = keyof typeof MessageType\n\nexport interface DHTRecord {\n key: Uint8Array\n value: Uint8Array\n timeReceived?: Date\n}\n\nexport type DHTProgressEvents =\n ProgressEvent<'kad-dht:query:send-query', SendQueryEvent> |\n ProgressEvent<'kad-dht:query:peer-response', PeerResponseEvent> |\n ProgressEvent<'kad-dht:query:final-peer', FinalPeerEvent> |\n ProgressEvent<'kad-dht:query:query-error', QueryErrorEvent> |\n ProgressEvent<'kad-dht:query:provider', ProviderEvent> |\n ProgressEvent<'kad-dht:query:value', ValueEvent> |\n ProgressEvent<'kad-dht:query:add-peer', AddPeerEvent> |\n ProgressEvent<'kad-dht:query:dial-peer', DialPeerEvent>\n\n/**\n * Emitted when sending queries to remote peers\n */\nexport interface SendQueryEvent {\n to: PeerId\n type: EventTypes.SEND_QUERY\n name: 'SEND_QUERY'\n messageName: keyof typeof MessageType\n messageType: MessageType\n}\n\n/**\n * Emitted when query responses are received form remote peers. Depending on the query\n * these events may be followed by a `FinalPeerEvent`, a `ValueEvent` or a `ProviderEvent`.\n */\nexport interface PeerResponseEvent {\n from: PeerId\n type: EventTypes.PEER_RESPONSE\n name: 'PEER_RESPONSE'\n messageName: keyof typeof MessageType\n messageType: MessageType\n closer: PeerInfo[]\n providers: PeerInfo[]\n record?: DHTRecord\n}\n\n/**\n * Emitted at the end of a `findPeer` query\n */\nexport interface FinalPeerEvent {\n from: PeerId\n peer: PeerInfo\n type: EventTypes.FINAL_PEER\n name: 'FINAL_PEER'\n}\n\n/**\n * Something went wrong with the query\n */\nexport interface QueryErrorEvent {\n from: PeerId\n type: EventTypes.QUERY_ERROR\n name: 'QUERY_ERROR'\n error: Error\n}\n\n/**\n * Emitted when providers are found\n */\nexport interface ProviderEvent {\n from: PeerId\n type: EventTypes.PROVIDER\n name: 'PROVIDER'\n providers: PeerInfo[]\n}\n\n/**\n * Emitted when values are found\n */\nexport interface ValueEvent {\n from: PeerId\n type: EventTypes.VALUE\n name: 'VALUE'\n value: Uint8Array\n}\n\n/**\n * Emitted when peers are added to a query\n */\nexport interface AddPeerEvent {\n type: EventTypes.ADD_PEER\n name: 'ADD_PEER'\n peer: PeerId\n}\n\n/**\n * Emitted when peers are dialled as part of a query\n */\nexport interface DialPeerEvent {\n peer: PeerId\n type: EventTypes.DIAL_PEER\n name: 'DIAL_PEER'\n}\n\nexport type QueryEvent = SendQueryEvent | PeerResponseEvent | FinalPeerEvent | QueryErrorEvent | ProviderEvent | ValueEvent | AddPeerEvent | DialPeerEvent\n\nexport interface RoutingTable {\n size: number\n}\n\nexport interface PeerInfoMapper {\n (peer: PeerInfo): PeerInfo\n}\n\nexport interface KadDHT {\n /**\n * Get a value from the DHT, the final ValueEvent will be the best value\n */\n get(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find providers of a given CID\n */\n findProviders(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find a peer on the DHT\n */\n findPeer(id: PeerId, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Find the closest peers to the passed key\n */\n getClosestPeers(key: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Store provider records for the passed CID on the DHT pointing to us\n */\n provide(key: CID, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Provider records must be re-published every 24 hours - pass a previously\n * provided CID here to not re-publish a record for it any more\n */\n cancelReprovide(key: CID): Promise<void>\n\n /**\n * Store the passed value under the passed key on the DHT\n */\n put(key: Uint8Array, value: Uint8Array, options?: RoutingOptions): AsyncIterable<QueryEvent>\n\n /**\n * Returns the mode this node is in\n */\n getMode(): 'client' | 'server'\n\n /**\n * If 'server' this node will respond to DHT queries, if 'client' this node\n * will not.\n */\n setMode(mode: 'client' | 'server'): Promise<void>\n\n /**\n * Force a routing table refresh\n */\n refreshRoutingTable(): Promise<void>\n}\n\nexport interface SingleKadDHT extends KadDHT {\n routingTable: RoutingTable\n}\n\n/**\n * A selector function takes a DHT key and a list of records and returns the\n * index of the best record in the list\n */\nexport interface SelectFn { (key: Uint8Array, records: Uint8Array[]): number }\n\n/**\n * A validator function takes a DHT key and the value of the record for that key\n * and throws if the record is invalid\n */\nexport interface ValidateFn { (key: Uint8Array, value: Uint8Array): Promise<void> }\n\n/**\n * Selectors are a map of key prefixes to selector functions\n */\nexport type Selectors = Record<string, SelectFn>\n\n/**\n * Validators are a map of key prefixes to validator functions\n */\nexport type Validators = Record<string, ValidateFn>\n\nexport interface ProvidersInit {\n /**\n * @default 256\n */\n cacheSize?: number\n /**\n * How often invalid records are cleaned in seconds\n *\n * @default 5_400\n */\n cleanupInterval?: number\n /**\n * How long is a provider valid for in seconds\n *\n * @default 86_400\n */\n provideValidity?: number\n}\n\nexport interface ReProvideInit {\n /**\n * How many re-provide operations to run simultaneously\n *\n * @default 10\n */\n concurrency?: number\n\n /**\n * How long to let the re-provide queue grow\n *\n * @default 16_384\n */\n maxQueueSize?: number\n\n /**\n * How long before the record expiry to re-provide in ms\n *\n * @default 86_400_000 (24 hours)\n */\n threshold?: number\n\n /**\n * How often to check which records need re-providing in ms\n *\n * @default 3_600_000 (1 hour)\n */\n interval?: number\n\n /**\n * How long provider records are valid for in ms\n *\n * @default 172_800_000 (48 hours)\n */\n validity?: number\n}\n\nexport interface KadDHTInit {\n /**\n * How many peers to store in each kBucket. Once there are more than this\n * number of peers for a given prefix in a kBucket, the node will start to\n * ping existing peers to see if they are still online - if they are offline\n * they will be evicted and the new peer added.\n *\n * @default 20\n */\n kBucketSize?: number\n\n /**\n * The threshold at which a kBucket will be split into two smaller kBuckets.\n *\n * KBuckets will not be split once the maximum trie depth is reached\n * (controlled by the `prefixLength` option) so one can replicate go-libp2p's\n * accelerated DHT client by (for example) setting `kBucketSize` to `Infinity`\n * and `kBucketSplitThreshold` to 20.\n *\n * @default kBucketSize\n */\n kBucketSplitThreshold?: number\n\n /**\n * How many bits of the KAD-ID of peers to use when creating the routing\n * table.\n *\n * The routing table is a binary trie with peers stored in the leaf nodes. The\n * larger this number gets, the taller the trie can grow and the more peers\n * can be stored.\n *\n * Storing more peers means fewer lookups (and network operations) are needed\n * to locate a certain peer, but also that more memory is consumed and more\n * CPU while responding to queries (e.g. with more peers in the table sorting\n * the closest peers becomes more expensive) and CPU/network during table\n * maintenance (e.g. checking peers are still online).\n *\n * The larger this value, the more prefix bits must be the same for a peer to\n * be stored in a KAD bucket, so the fewer nodes that bucket is likely to\n * contain.\n *\n * The total number of peers in the table is a factor of `prefixLength` and\n * `kBucketSize`:\n *\n * ```\n * (2 ^ prefixLength) * kBucketSize\n * ```\n *\n * @default 6\n */\n prefixLength?: number\n\n /**\n * If true, only ever be a DHT client. If false, be a DHT client until told\n * to be a DHT server via `setMode`.\n *\n * In general this should be left as the default because server mode will be\n * selected automatically when libp2p establishes that the current node has\n * a publicly dialable address.\n *\n * The exception to this is LAN-only DHT (e.g. for testing purposes) where it\n * is safe to assume that the current node is dialable.\n *\n * @default false\n */\n clientMode?: boolean\n\n /**\n * Record selectors\n */\n selectors?: Selectors\n\n /**\n * Record validators\n */\n validators?: Validators\n\n /**\n * How often to query our own PeerId in order to ensure we have a\n * good view on the KAD address space local to our PeerId\n */\n querySelfInterval?: number\n\n /**\n * During startup we run the self-query at a shorter interval to ensure\n * the containing node can respond to queries quickly. Set this interval\n * here in ms.\n *\n * @default 1000\n */\n initialQuerySelfInterval?: number\n\n /**\n * After startup by default all queries will be paused until the initial\n * self-query has run and there are some peers in the routing table.\n *\n * Pass true here to disable this behavior.\n *\n * @default false\n */\n allowQueryWithZeroPeers?: boolean\n\n /**\n * The network protocol to use\n *\n * @default \"/ipfs/kad/1.0.0\"\n */\n protocol?: string\n\n /**\n * The logging prefix to use\n *\n * @default \"libp2p:kad-dht\"\n */\n logPrefix?: string\n\n /**\n * The datastore prefix to use\n *\n * @default \"/dht\"\n */\n datastorePrefix?: string\n\n /**\n * The metrics prefix to use\n *\n * @default \"libp2p_kad_dht\"\n */\n metricsPrefix?: string\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be evicted from the routing table or not.\n */\n pingOldContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should\n * be evicted from the routing table or not\n *\n * @default 10\n */\n pingOldContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingOldContactMaxQueueSize?: number\n\n /**\n * Settings for how long to wait in ms when pinging DHT peers to decide if\n * they should be added to the routing table or not.\n */\n pingNewContactTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n\n /**\n * How many peers to ping in parallel when deciding if they should be added to\n * the routing table or not\n *\n * @default 10\n */\n pingNewContactConcurrency?: number\n\n /**\n * How long the queue to ping peers is allowed to grow\n *\n * @default 100\n */\n pingNewContactMaxQueueSize?: number\n\n /**\n * How many parallel incoming streams to allow on the DHT protocol per\n * connection\n *\n * @default 32\n */\n maxInboundStreams?: number\n\n /**\n * How many parallel outgoing streams to allow on the DHT protocol per\n * connection\n *\n * @default 64\n */\n maxOutboundStreams?: number\n\n /**\n * Initialization options for the Providers component\n */\n providers?: ProvidersInit\n\n /**\n * Initialization options for the Reprovider component\n */\n reprovide?: ReProvideInit\n\n /**\n * For every incoming and outgoing PeerInfo, override address configuration\n * with this filter.\n */\n peerInfoMapper?(peer: PeerInfo): PeerInfo\n\n /**\n * Dynamic network timeout settings for sending messages to peers\n */\n networkDialTimeout?: Omit<AdaptiveTimeoutInit, 'metricsName' | 'metrics'>\n}\n\nexport interface KadDHTComponents {\n peerId: PeerId\n privateKey: PrivateKey\n registrar: Registrar\n addressManager: AddressManager\n peerStore: PeerStore\n metrics?: Metrics\n connectionManager: ConnectionManager\n datastore: Datastore\n events: TypedEventTarget<Libp2pEvents>\n logger: ComponentLogger\n ping: Ping\n}\n\n/**\n * Creates a custom DHT implementation, please ensure you pass a `protocol`\n * string as an option.\n */\nexport function kadDHT (init: KadDHTInit = {}): (components: KadDHTComponents) => KadDHT {\n return (components: KadDHTComponents) => new KadDHTClass(components, init)\n}\n", "import { Record } from '@libp2p/kad-dht'\nimport { Key } from 'interface-datastore'\nimport { CustomProgressEvent } from 'progress-events'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport type { GetOptions, PutOptions } from '../routing'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Datastore } from 'interface-datastore'\nimport type { ProgressEvent } from 'progress-events'\n\nfunction dhtRoutingKey (key: Uint8Array): Key {\n return new Key('/dht/record/' + uint8ArrayToString(key, 'base32'), false)\n}\n\nexport type DatastoreProgressEvents =\n ProgressEvent<'ipns:routing:datastore:put'> |\n ProgressEvent<'ipns:routing:datastore:get'> |\n ProgressEvent<'ipns:routing:datastore:error', Error>\n\nexport interface GetResult {\n record: Uint8Array\n created: Date\n}\n\nexport interface LocalStore {\n put(routingKey: Uint8Array, marshaledRecord: Uint8Array, options?: PutOptions): Promise<void>\n get(routingKey: Uint8Array, options?: GetOptions): Promise<GetResult>\n has(routingKey: Uint8Array, options?: AbortOptions): Promise<boolean>\n delete(routingKey: Uint8Array, options?: AbortOptions): Promise<void>\n}\n\n/**\n * Returns an IPNSRouting implementation that reads/writes IPNS records to the\n * datastore as DHT records. This lets us publish IPNS records offline then\n * serve them to the network later in response to DHT queries.\n */\nexport function localStore (datastore: Datastore): LocalStore {\n return {\n async put (routingKey: Uint8Array, marshalledRecord: Uint8Array, options: PutOptions = {}) {\n try {\n const key = dhtRoutingKey(routingKey)\n\n // don't overwrite existing, identical records as this will affect the\n // TTL\n try {\n const existingBuf = await datastore.get(key)\n const existingRecord = Record.deserialize(existingBuf)\n\n if (uint8ArrayEquals(existingRecord.value, marshalledRecord)) {\n return\n }\n } catch (err: any) {\n if (err.name !== 'NotFoundError') {\n throw err\n }\n }\n\n // Marshal to libp2p record as the DHT does\n const record = new Record(routingKey, marshalledRecord, new Date())\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:put'))\n await datastore.put(key, record.serialize(), options)\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async get (routingKey: Uint8Array, options: GetOptions = {}): Promise<GetResult> {\n try {\n const key = dhtRoutingKey(routingKey)\n\n options.onProgress?.(new CustomProgressEvent('ipns:routing:datastore:get'))\n const buf = await datastore.get(key, options)\n\n // Unmarshal libp2p record as the DHT does\n const record = Record.deserialize(buf)\n\n return {\n record: record.value,\n created: record.timeReceived\n }\n } catch (err: any) {\n options.onProgress?.(new CustomProgressEvent<Error>('ipns:routing:datastore:error', err))\n throw err\n }\n },\n async has (routingKey: Uint8Array, options: AbortOptions = {}): Promise<boolean> {\n const key = dhtRoutingKey(routingKey)\n return datastore.has(key, options)\n },\n async delete (routingKey, options): Promise<void> {\n const key = dhtRoutingKey(routingKey)\n return datastore.delete(key, options)\n }\n }\n}\n", "import type { MultihashDigest } from 'multiformats/hashes/interface'\n\nexport const IDENTITY_CODEC = 0x0\nexport const SHA2_256_CODEC = 0x12\n\nexport const IPNS_STRING_PREFIX = '/ipns/'\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDig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OAAA5C,EAAQ,IAAAO,CAAG,CAAE,CAAC,EACxFA,CACR,CACF,GAOI,SAAUyC,GAAM1D,EAA4B,CAAE,QAAAC,EAAU,CAAA,CAAE,EAAkB,CAAA,EAAE,CAClF,OAAO,IAAIF,GAAYC,EAAYC,CAAO,CAC5C",
|
|
6
6
|
"names": ["require_timestamp_min", "__commonJSMin", "exports", "module", "Timestamp", "d", "l", "s", "T", "e", "f", "c", "g", "h", "u", "m", "n", "t", "o", "r", "p", "y", "M", "C", "D", "a", "i", "w", "require_hashlru", "__commonJSMin", "exports", "module", "max", "size", "cache", "_cache", "update", "key", "value", "v", "index_exports", "__export", "ipns", "ipnsSelector", "ipnsValidator", "isPublicKey", "key", "peerIdSymbol", "InvalidParametersError", "message", "InvalidPublicKeyError", "NotFoundError", "message", "InvalidCIDError", "message", "InvalidMultihashError", "UnsupportedKeyTypeError", "message", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "fromString", "str", "toString", "b", "base", "ALPHABET", "name", "BASE_MAP", "j", "i", "x", "xc", "BASE", "LEADER", "FACTOR", "iFACTOR", "encode", "source", "zeroes", "length", "pbegin", "pend", "size", "b58", "carry", "it1", "it2", "str", "decodeUnsafe", "psz", "b256", "it3", "it4", "vch", "decode", "string", "buffer", "src", "_brrp__multiformats_scope_baseX", "base_x_default", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "prefixCodePoint", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "base58_exports", "__export", "base58btc", "base58flickr", "base58btc", "baseX", "base58flickr", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "ms", "value", "options", "parse", "fmtLong", "fmtShort", "error", "message", "isError", "str", "match", "n", "type", "dist_default", "msAbs", "plural", "name", "isPlural", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "dist_default", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "len", "toNamespace", "name", "regexp", "storage", "localstorage", "colors", "useColors", "formatArgs", "args", "dist_default", "c", "index", "lastC", "match", "log", "save", "namespaces", "load", "r", "setupFormatters", "formatters", "v", "error", "browser_default", "setup", "src_default", "browser_default", "src_default", "v", "base58btc", "base32", "base64", "notEmpty", "createDisabledLogger", "namespace", "logger", "logger", "name", "trace", "createDisabledLogger", "src_default", "n", "notEmpty", "str", "base36_exports", "__export", "base36", "base36upper", "base36", "baseX", "base36upper", "encode_1", "encode", "MSB", "REST", "MSBALL", "INT", "num", "out", "offset", "oldOffset", "decode", "read", "MSB$1", "REST$1", "buf", "res", "shift", "counter", "b", "l", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "length", "value", "varint", "_brrp_varint", "varint_default", "decode", "data", "offset", "varint_default", "encodeTo", "int", "target", "encodingLength", "create", "code", "digest", "size", "sizeOffset", "encodingLength", "digestOffset", "bytes", "encodeTo", "Digest", "decode", "multihash", "coerce", "equals", "a", "b", "data", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "base36", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "identity_exports", "__export", "identity", "code", "name", "encode", "coerce", "digest", "input", "create", "identity", "equals", "a", "b", "i", "alloc", "size", "allocUnsafe", "concat", "arrays", "length", "acc", "curr", "output", "allocUnsafe", "offset", "arr", "symbol", "findBufAndOffset", "bufs", "index", "offset", "buf", "bufEnd", "isUint8ArrayList", "value", "Uint8ArrayList", "_Uint8ArrayList", "data", "length", "res", "i", "bytes", "beginInclusive", "endExclusive", "concat", "list", "bufStart", "sliceStartInBuf", "sliceEndsInBuf", "start", "search", "needle", "M", "radix", "rightmostPositions", "c", "j", "right", "lastIndex", "lastPatIndex", "skip", "char", "byteOffset", "allocUnsafe", "littleEndian", "alloc", "other", "equals", "acc", "curr", "base10_exports", "__export", "base10", "base10", "baseX", "base16_exports", "__export", "base16", "base16upper", "base16", "rfc4648", "base16upper", "base2_exports", "__export", "base2", "base2", "rfc4648", "base256emoji_exports", "__export", "base256emoji", "alphabet", "alphabetBytesToChars", "p", "c", "i", "alphabetCharsToBytes", "codePoint", "encode", "data", "decode", "str", "byts", "char", "byt", "base256emoji", "from", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "sha2_browser_exports", "__export", "sha256", "sha512", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "bases", "identity_exports", "base2_exports", "base8_exports", "base10_exports", "base16_exports", "base32_exports", "base36_exports", "base58_exports", "base64_exports", "base256emoji_exports", "hashes", "sha2_browser_exports", "createCodec", "name", "prefix", "encode", "decode", "string", "buf", "str", "ascii", "i", "allocUnsafe", "BASES", "bases", "bases_default", "fromString", "string", "encoding", "base", "bases_default", "toString", "array", "encoding", "base", "bases_default", "TAG_MASK", "LONG_LENGTH_MASK", "LONG_LENGTH_BYTES_MASK", "decoders", "readSequence", "readInteger", "readBitString", "readOctetString", "readNull", "readObjectIdentifier", "decodeDer", "buf", "context", "tag", "readLength", "length", "count", "str", "entries", "result", "start", "end", "vals", "i", "finalOffset", "byte", "val1", "val2", "oid", "num", "val", "unusedBits", "bytes", "encodeNumber", "value", "number", "array", "Uint8ArrayList", "encodeLength", "encodeInteger", "contents", "mask", "encodeBitString", "encodeSequence", "values", "tag", "output", "Uint8ArrayList", "buf", "encodeLength", "hashAndVerify", "key", "sig", "msg", "publicKey", "OID_256", "OID_384", "OID_521", "P_256_KEY_JWK", "P_384_KEY_JWK", "P_521_KEY_JWK", "P_256_KEY_LENGTH", "P_384_KEY_LENGTH", "P_521_KEY_LENGTH", "unmarshalECDSAPublicKey", "bytes", "message", "decodeDer", "pkiMessageToECDSAPublicKey", "coordinates", "offset", "x", "y", "P_256_KEY_LENGTH", "toString", "ECDSAPublicKey", "P_256_KEY_JWK", "P_384_KEY_LENGTH", "P_384_KEY_JWK", "P_521_KEY_LENGTH", "P_521_KEY_JWK", "InvalidParametersError", "publicKeyToPKIMessage", "publicKey", "encodeSequence", "encodeInteger", "getOID", "encodeBitString", "Uint8ArrayList", "fromString", "curve", "OID_256", "OID_384", "OID_521", "InvalidParametersError", "ECDSAPublicKey", "jwk", "publicKeyToPKIMessage", "identity", "publicKeyToProtobuf", "CID", "base58btc", "key", "equals", "data", "sig", "hashAndVerify", "crypto", "isBytes", "a", "anumber", "n", "abytes", "b", "lengths", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "utf8ToBytes", "str", "toBytes", "data", "utf8ToBytes", "abytes", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "Hash", "createHasher", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "aexists", "toBytes", "abytes", "buffer", "len", "pos", "take", "dataView", "out", "aoutput", "clean", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA512_IV", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "len", "Ah", "Al", "h", "l", "shrSH", "h", "_l", "s", "shrSL", "l", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add", "Ah", "Al", "Bh", "Bl", "l", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "SHA256_K", "SHA256_W", "SHA256", "HashMD", "outputLen", "SHA256_IV", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA512", "HashMD", "outputLen", "SHA512_IV", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "clean", "sha256", "createHasher", "SHA256", "sha512", "createHasher", "SHA512", "_0n", "_1n", "isBytes", "a", "abytes", "item", "abool", "title", "value", "numberToHexUnpadded", "num", "hex", "hexToNumber", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "bytesToNumberBE", "bytesToNumberLE", "numberToBytesBE", "n", "len", "numberToBytesLE", "ensureBytes", "title", "hex", "expectedLength", "res", "hexToBytes", "e", "isBytes", "len", "concatBytes", "arrays", "sum", "i", "a", "abytes", "pad", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "u8n", "len", "u8fr", "arr", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "v", "k", "reset", "h", "b", "reseed", "seed", "gen", "out", "sl", "concatBytes", "pred", "res", "validatorFns", "val", "isBytes", "object", "validateObject", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "memoized", "fn", "map", "arg", "args", "val", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "res", "_0n", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "tonelliShanks", "P", "Q", "S", "_2n", "Z", "_Fp", "Field", "FpIsSquare", "p1div4", "_4n", "Fp", "root", "Q1div2", "g", "t2", "ge", "FpSqrt", "_3n", "_8n", "_5n", "n2", "c1", "nv", "i", "_16n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "legc", "_1n", "_2n", "powered", "yes", "zero", "no", "FpIsSquare", "l", "nLength", "nBitLength", "anumber", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "f", "bitMask", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "c", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "constTimeNegate", "condition", "item", "neg", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "validateMSMPoints", "points", "c", "p", "i", "validateMSMScalars", "scalars", "field", "s", "pointPrecomputes", "pointWindowSizes", "getW", "P", "wNAF", "elm", "d", "base", "precomputes", "f", "wo", "offsetF", "acc", "transform", "comp", "prev", "pippenger", "fieldN", "zero", "bitLen", "MASK", "buckets", "lastBits", "sum", "j", "scalar", "resI", "sumI", "validateBasic", "curve", "validateField", "validateObject", "nLength", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "Fn", "Field", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "aCoordinate", "title", "n", "banZero", "min", "aInRange", "aextpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "x", "y", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "ex", "ey", "ez", "et", "points", "toInv", "FpInvertBatch", "i", "scalars", "pippenger", "windowSize", "wnaf", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "scalar", "f", "acc", "I", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "max", "y2", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getPrivateScalar", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "getExtendedPublicKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "_8n", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "PUBLIC_KEY_BYTE_LENGTH", "hashAndVerify", "publicKey", "sig", "msg", "ed25519", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "hashAndVerify", "unmarshalEd25519PublicKey", "bytes", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "Ed25519PublicKey", "ensureEd25519Key", "key", "length", "InvalidParametersError", "N1", "N2", "N3", "N4", "N5", "N6", "N7", "MSB", "REST", "encodingLength", "value", "encodeUint8Array", "buf", "offset", "decodeUint8Array", "buf", "offset", "b", "res", "REST", "MSB", "N4", "N5", "N6", "N7", "f32", "f8b", "writeFloatLE", "val", "buf", "pos", "readFloatLE", "buf", "pos", "f8b", "f32", "f64", "d8b", "writeDoubleLE", "val", "buf", "pos", "readDoubleLE", "buf", "pos", "d8b", "f64", "MAX_SAFE_NUMBER_INTEGER", "MIN_SAFE_NUMBER_INTEGER", "LongBits", "_LongBits", "lo", "hi", "unsigned", "mask", "part0", "part1", "part2", "value", "zero", "negative", "TWO_32", "sign", "length", "string", "len", "c", "i", "read", "buffer", "start", "end", "parts", "chunk", "t", "write", "offset", "c1", "c2", "indexOutOfRange", "reader", "writeLength", "readFixed32End", "buf", "end", "Uint8ArrayReader", "buffer", "value", "readFloatLE", "readDoubleLE", "length", "start", "bytes", "read", "wireType", "bits", "LongBits", "i", "lo", "hi", "decodeUint8Array", "encodingLength", "createReader", "decodeMessage", "buf", "codec", "opts", "reader", "createReader", "pool", "size", "SIZE", "MAX", "slab", "offset", "allocUnsafe", "buf", "Op", "fn", "len", "val", "noop", "State", "writer", "bufferPool", "pool", "alloc", "size", "allocUnsafe", "Uint8ArrayWriter", "value", "VarintOp", "writeVarint64", "LongBits", "bits", "encodeUint8Array", "encodingLength", "writeByte", "writeFixed32", "writeFloatLE", "writeDoubleLE", "writeBytes", "length", "write", "head", "tail", "buf", "pos", "writeVarint32", "writeBytesBuffer", "writeStringBuffer", "fromString", "createWriter", "encodeMessage", "message", "codec", "w", "createWriter", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "PrivateKey", "VerificationError", "message", "WebCryptoMissingError", "webcrypto_browser_default", "win", "nativeCrypto", "WebCryptoMissingError", "webcrypto_default", "webcrypto_browser_default", "utils_exports", "__export", "MAX_RSA_KEY_SIZE", "generateRSAKeyPair", "jwkToJWKKeyPair", "jwkToPkcs1", "jwkToPkix", "jwkToRSAPrivateKey", "pkcs1MessageToJwk", "pkcs1MessageToRSAPrivateKey", "pkcs1ToJwk", "pkcs1ToRSAPrivateKey", "pkixMessageToJwk", "pkixMessageToRSAPublicKey", "pkixToJwk", "pkixToRSAPublicKey", "sha256", "RSAPublicKey", "jwk", "digest", "utils_exports", "CID", "base58btc", "key", "equals", "data", "sig", "hashAndVerify", "RSAPrivateKey", "publicKey", "message", "hashAndSign", "MAX_RSA_KEY_SIZE", "SHA2_256_CODE", "MAX_RSA_JWK_SIZE", "RSA_ALGORITHM_IDENTIFIER", "pkcs1ToJwk", "bytes", "message", "decodeDer", "pkcs1MessageToJwk", "toString", "jwkToPkcs1", "jwk", "InvalidParametersError", "encodeSequence", "encodeInteger", "fromString", "pkixToJwk", "pkixMessageToJwk", "keys", "jwkToPkix", "encodeBitString", "pkcs1ToRSAPrivateKey", "pkcs1MessageToRSAPrivateKey", "jwkToRSAPrivateKey", "pkixToRSAPublicKey", "digest", "InvalidPublicKeyError", "pkixMessageToRSAPublicKey", "hash", "sha256", "PublicKey", "KeyType", "create", "RSAPublicKey", "rsaKeySize", "jwkToJWKKeyPair", "RSAPrivateKey", "generateRSAKeyPair", "bits", "generateRSAKey", "key", "generateRSAKey", "bits", "pair", "webcrypto_default", "keys", "exportKey", "hashAndSign", "key", "msg", "privateKey", "webcrypto_default", "sig", "hashAndVerify", "publicKey", "exportKey", "pair", "InvalidParametersError", "rsaKeySize", "jwk", "fromString", "HMAC", "Hash", "hash", "_key", "ahash", "key", "toBytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "abytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "validateSigVerOpts", "opts", "abool", "validatePointOpts", "curve", "validateBasic", "validateObject", "endo", "Fp", "a", "DERErr", "m", "DER", "tag", "data", "E", "dataLen", "len", "numberToHexUnpadded", "lenLen", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "num", "_0n", "hex", "bytesToNumberBE", "int", "tlv", "ensureBytes", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "_1n", "_2n", "_3n", "_4n", "weierstrassPoints", "CURVE", "Fn", "Field", "toBytes", "_c", "point", "_isCompressed", "concatBytes", "fromBytes", "bytes", "tail", "x", "y", "weierstrassEquation", "x2", "x3", "isWithinCurveOrder", "inRange", "normPrivateKeyToScalar", "key", "lengths", "nByteLength", "wrapPrivateKey", "N", "isBytes", "bytesToHex", "mod", "aInRange", "aprjpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "left", "right", "px", "py", "pz", "i", "points", "toInv", "FpInvertBatch", "P", "privateKey", "scalars", "pippenger", "windowSize", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "n", "sc", "I", "k1neg", "k1", "k2neg", "k2", "k1p", "k2p", "d", "scalar", "fake", "f1p", "f2p", "f", "Q", "G", "mul", "sum", "cofactor", "isTorsionFree", "clearCofactor", "isCompressed", "_bits", "wNAF", "validateOpts", "weierstrass", "curveDef", "CURVE_ORDER", "compressedLen", "uncompressedLen", "modN", "invN", "invert", "cat", "head", "y2", "sqrtError", "suffix", "isYOdd", "cl", "ul", "numToNByteHex", "numberToBytesBE", "isBiggerThanHalfOrder", "number", "HALF", "normalizeS", "s", "slcNum", "from", "to", "Signature", "r", "recovery", "l", "msgHash", "rec", "h", "bits2int_modN", "radj", "prefix", "R", "ir", "u1", "u2", "hexToBytes", "utils", "getMinHashLength", "mapHashToField", "getPublicKey", "isProbPub", "item", "arr", "str", "getSharedSecret", "privateA", "publicB", "bits2int", "delta", "ORDER_MASK", "bitMask", "int2octets", "prepSig", "defaultSigOpts", "k", "hash", "randomBytes", "lowS", "prehash", "ent", "h1int", "seedArgs", "e", "seed", "k2sig", "kBytes", "ik", "q", "normS", "defaultVerOpts", "sign", "privKey", "createHmacDrbg", "verify", "signature", "publicKey", "sg", "format", "isHex", "isObj", "_sig", "derError", "is", "getHash", "hash", "key", "msgs", "hmac", "concatBytes", "randomBytes", "createCurve", "curveDef", "defHash", "create", "weierstrass", "secp256k1P", "secp256k1N", "_1n", "_2n", "divNearest", "a", "b", "sqrtMod", "y", "P", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "secp256k1", "createCurve", "k", "n", "a1", "b1", "a2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "sha256", "_0n", "Point", "secp256k1", "isPromise", "thing", "hashAndVerify", "key", "sig", "msg", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "hashAndVerify", "unmarshalSecp256k1PublicKey", "bytes", "Secp256k1PublicKey", "compressSecp256k1PublicKey", "key", "secp256k1", "validateSecp256k1PublicKey", "key", "secp256k1", "err", "InvalidPublicKeyError", "publicKeyFromProtobuf", "buf", "digest", "Type", "Data", "PublicKey", "data", "KeyType", "pkixToRSAPublicKey", "unmarshalEd25519PublicKey", "unmarshalSecp256k1PublicKey", "unmarshalECDSAPublicKey", "UnsupportedKeyTypeError", "publicKeyFromMultihash", "digest", "Type", "Data", "PublicKey", "data", "KeyType", "unmarshalEd25519PublicKey", "unmarshalSecp256k1PublicKey", "unmarshalECDSAPublicKey", "UnsupportedKeyTypeError", "publicKeyToProtobuf", "key", "inspect", "LIBP2P_KEY_CODE", "PeerIdImpl", "init", "peerIdSymbol", "base58btc", "CID", "id", "equals", "RSAPeerId", "Ed25519PeerId", "Secp256k1PeerId", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "URLPeerId", "url", "identity", "fromString", "other", "toString", "LIBP2P_KEY_CODE", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "peerIdFromString", "str", "decoder", "multihash", "decode", "base58btc", "peerIdFromCID", "CID", "InvalidParametersError", "peerIdFromMultihash", "peerIdFromMultihash", "multihash", "isSha256Multihash", "RSAPeerId", "isIdentityMultihash", "publicKey", "publicKeyFromMultihash", "Ed25519PeerId", "Secp256k1PeerId", "url", "toString", "URLPeerId", "InvalidMultihashError", "peerIdFromCID", "cid", "LIBP2P_KEY_CODE", "TRANSPORT_IPFS_GATEWAY_HTTP_CODE", "InvalidCIDError", "identity", "sha256", "pathSepS", "pathSepB", "pathSep", "Key", "_Key", "s", "clean", "fromString", "encoding", "toString", "list", "other", "bytes", "key", "list1", "list2", "i", "c1", "c2", "ns", "namespaceType", "namespaceValue", "p", "keys", "flatten", "parts", "arr", "import_timestamp_nano", "SignatureCreationError", "message", "SignatureVerificationError", "RecordExpiredError", "UnsupportedValidityError", "RecordTooLargeError", "InvalidValueError", "InvalidRecordDataError", "InvalidEmbeddedPublicKeyError", "IpnsEntry", "ValidityType", "__ValidityTypeValues", "enumeration", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "encodeMessage", "buf", "decodeMessage", "typeofs", "objectTypeNames", "is", "value", "typeOf", "isBuffer", "objectType", "getObjectType", "objectTypeName", "Type", "major", "name", "terminal", "typ", "Token", "type", "value", "encodedLength", "useBuffer", "textDecoder", "textEncoder", "isBuffer", "buf", "asU8A", "toString", "bytes", "start", "end", "utf8Slice", "fromString", "string", "utf8ToBytes", "fromArray", "arr", "slice", "concat", "chunks", "length", "c", "out", "off", "b", "alloc", "size", "compare", "b1", "b2", "isBuffer", "i", "utf8ToBytes", "str", "out", "p", "c", "utf8Slice", "buf", "offset", "end", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "len", "defaultChunkSize", "Bl", "chunkSize", "bytes", "topChunk", "chunkPos", "alloc", "reset", "byts", "chunk", "slice", "concat", "decodeErrPrefix", "encodeErrPrefix", "uintMinorPrefixBytes", "assertEnoughData", "data", "pos", "need", "uintBoundaries", "readUint8", "data", "offset", "options", "assertEnoughData", "value", "decodeErrPrefix", "readUint16", "readUint32", "readUint64", "hi", "lo", "decodeUint8", "pos", "_minor", "Token", "Type", "decodeUint16", "decodeUint32", "decodeUint64", "encodeUint", "buf", "token", "encodeUintValue", "major", "uint", "nuint", "buint", "set", "tok1", "tok2", "decodeNegint8", "data", "pos", "_minor", "options", "Token", "Type", "readUint8", "decodeNegint16", "readUint16", "decodeNegint32", "readUint32", "neg1b", "pos1b", "decodeNegint64", "int", "readUint64", "value", "decodeErrPrefix", "encodeNegint", "buf", "token", "negint", "unsigned", "encodeUintValue", "uintBoundaries", "tok1", "tok2", "toToken", "data", "pos", "prefix", "length", "assertEnoughData", "buf", "slice", "Token", "Type", "decodeBytesCompact", "minor", "_options", "decodeBytes8", "_minor", "options", "readUint8", "decodeBytes16", "readUint16", "decodeBytes32", "readUint32", "decodeBytes64", "l", "readUint64", "decodeErrPrefix", "tokenBytes", "token", "fromString", "encodeBytes", "bytes", "encodeUintValue", "tok1", "tok2", "compareBytes", "b1", "b2", "compare", "toToken", "data", "pos", "prefix", "length", "options", "totLength", "assertEnoughData", "tok", "Token", "Type", "toString", "slice", "decodeStringCompact", "minor", "decodeString8", "_minor", "readUint8", "decodeString16", "readUint16", "decodeString32", "readUint32", "decodeString64", "l", "readUint64", "decodeErrPrefix", "encodeString", "encodeBytes", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeArrayCompact", "data", "pos", "minor", "_options", "decodeArray8", "_minor", "options", "readUint8", "decodeArray16", "readUint16", "decodeArray32", "readUint32", "decodeArray64", "l", "readUint64", "decodeErrPrefix", "decodeArrayIndefinite", "encodeArray", "buf", "token", "encodeUintValue", "encodeUint", "toToken", "_data", "_pos", "prefix", "length", "Token", "Type", "decodeMapCompact", "data", "pos", "minor", "_options", "decodeMap8", "_minor", "options", "readUint8", "decodeMap16", "readUint16", "decodeMap32", "readUint32", "decodeMap64", "l", "readUint64", "decodeErrPrefix", "decodeMapIndefinite", "encodeMap", "buf", "token", "encodeUintValue", "encodeUint", "decodeTagCompact", "_data", "_pos", "minor", "_options", "Token", "Type", "decodeTag8", "data", "pos", "_minor", "options", "readUint8", "decodeTag16", "readUint16", "decodeTag32", "readUint32", "decodeTag64", "readUint64", "encodeTag", "buf", "token", "encodeUintValue", "encodeUint", "MINOR_FALSE", "MINOR_TRUE", "MINOR_NULL", "MINOR_UNDEFINED", "decodeUndefined", "_data", "_pos", "_minor", "options", "decodeErrPrefix", "Token", "Type", "decodeBreak", "createToken", "value", "bytes", "decodeFloat16", "data", "pos", "readFloat16", "decodeFloat32", "readFloat32", "decodeFloat64", "readFloat64", "encodeFloat", "buf", "token", "float", "decoded", "success", "encodeFloat16", "ui8a", "encodeFloat32", "encodeFloat64", "buffer", "dataView", "inp", "valu32", "exponent", "mantissa", "logicalExponent", "half", "exp", "mant", "val", "offset", "encodeUint", "invalidMinor", "data", "pos", "minor", "decodeErrPrefix", "errorer", "msg", "jump", "i", "decodeUint8", "decodeUint16", "decodeUint32", "decodeUint64", "decodeNegint8", "decodeNegint16", "decodeNegint32", "decodeNegint64", "decodeBytesCompact", "decodeBytes8", "decodeBytes16", "decodeBytes32", "decodeBytes64", "decodeStringCompact", "decodeString8", "decodeString16", "decodeString32", "decodeString64", "decodeArrayCompact", "decodeArray8", "decodeArray16", "decodeArray32", "decodeArray64", "decodeArrayIndefinite", "decodeMapCompact", "decodeMap8", "decodeMap16", "decodeMap32", "decodeMap64", "decodeMapIndefinite", "decodeTagCompact", "decodeTag8", "decodeTag16", "decodeTag32", "decodeTag64", "decodeUndefined", "decodeFloat16", "decodeFloat32", "decodeFloat64", "decodeBreak", "quick", "Token", "Type", "quickEncodeToken", "token", "fromArray", "defaultEncodeOptions", "mapSorter", "quickEncodeToken", "makeCborEncoders", "encoders", "Type", "encodeUint", "encodeNegint", "encodeBytes", "encodeString", "encodeArray", "encodeMap", "encodeTag", "encodeFloat", "cborEncoders", "buf", "Bl", "Ref", "_Ref", "obj", "parent", "p", "stack", "encodeErrPrefix", "simpleTokens", "Token", "typeEncoders", "_typ", "_options", "_refStack", "_obj", "options", "refStack", "entries", "e", "objectToTokens", "typ", "isMap", "keys", "length", "i", "key", "sortMapEntries", "is", "customTypeEncoder", "tokens", "typeEncoder", "e1", "e2", "keyToken1", "keyToken2", "major", "tcmp", "tokensToEncoded", "token", "encodeCustom", "data", "quickBytes", "encoder", "size", "asU8A", "encode", "defaultDecodeOptions", "Tokeniser", "data", "options", "byt", "token", "quick", "decoder", "jump", "decodeErrPrefix", "minor", "DONE", "BREAK", "tokenToArray", "tokeniser", "arr", "i", "value", "tokensToObject", "tokenToMap", "useMaps", "obj", "m", "key", "Type", "tagged", "decodeFirst", "decoded", "decode", "remainder", "log", "logger", "IPNS_PREFIX", "fromString", "LIBP2P_CID_CODEC", "IDENTITY_CODEC", "SHA2_256_CODEC", "extractPublicKeyFromIPNSRecord", "record", "pubKey", "publicKeyFromProtobuf", "err", "ipnsRecordDataForV1Sig", "value", "validityType", "validity", "validityTypeBuffer", "concat", "ipnsRecordDataForV2Sig", "data", "entryData", "marshalIPNSRecord", "obj", "IpnsEntry", "unmarshalIPNSRecord", "buf", "message", "SignatureVerificationError", "parseCborData", "normalizeByteValue", "toString", "validateCborDataMatchesPbData", "multihashToIPNSRoutingKey", "digest", "multihashFromIPNSRoutingKey", "key", "decode", "isCodec", "InvalidMultihashError", "createCborData", "sequence", "ttl", "ValidityType", "UnsupportedValidityError", "encode", "string", "CID", "InvalidValueError", "normalizeValue", "cid", "asCID", "base36", "hasBytes", "entry", "InvalidRecordDataError", "equals", "hasToCID", "codec", "log", "logger", "DEFAULT_TTL_NS", "namespace", "namespaceLength", "defaultCreateOptions", "createIPNSRecord", "privateKey", "value", "seq", "lifetime", "options", "expirationDate", "NanoDate", "validityType", "IpnsEntry", "ttlNs", "_create", "_create", "privateKey", "value", "seq", "validityType", "validity", "ttl", "options", "defaultCreateOptions", "isoValidity", "fromString", "normalizedValue", "normalizeValue", "encodedValue", "data", "createCborData", "sigData", "ipnsRecordDataForV2Sig", "signatureV2", "pubKey", "publicKeyToProtobuf", "signatureV1", "signLegacyV1", "record", "dataForSignature", "ipnsRecordDataForV1Sig", "error", "log", "SignatureCreationError", "import_timestamp_nano", "ipnsSelector", "key", "data", "entries", "buf", "index", "unmarshalIPNSRecord", "a", "b", "aSeq", "bSeq", "IpnsEntry", "recordAValidityDate", "NanoDate", "recordBValidityDate", "import_timestamp_nano", "log", "logger", "MAX_RECORD_SIZE", "validate", "publicKey", "marshalledRecord", "record", "unmarshalIPNSRecord", "isValid", "dataForSignature", "ipnsRecordDataForV2Sig", "SignatureVerificationError", "IpnsEntry", "NanoDate", "RecordExpiredError", "UnsupportedValidityError", "ipnsValidator", "routingKey", "RecordTooLargeError", "routingMultihash", "multihashFromIPNSRoutingKey", "routingPubKey", "isCodec", "publicKeyFromMultihash", "receivedRecord", "recordPubKey", "extractPublicKeyFromIPNSRecord", "InvalidEmbeddedPublicKeyError", "expectedRoutingKey", "multihashToIPNSRoutingKey", "equals", "CustomProgressEvent", "type", "detail", "import_hashlru", "RecordType", "DNSLinkNotFoundError", "message", "RecordsFailedValidationError", "UnsupportedMultibasePrefixError", "UnsupportedMultihashCodecError", "InvalidValueError", "MAX_RECURSIVE_DEPTH", "recursiveResolveDnslink", "domain", "depth", "dns", "log", "options", "txtRecords", "RecordType", "a", "b", "answer", "result", "protocol", "domainOrCID", "rest", "CID", "peerId", "peerIdFromString", "peerIdFromCID", "recursiveResolveDomain", "err", "cnameRecords", "cname", "DNSLinkNotFoundError", "resolveDNSLink", "HeliaRouting", "routing", "routingKey", "marshaledRecord", "options", "err", "CustomProgressEvent", "helia", "Record", "_codec", "message", "obj", "w", "opts", "reader", "length", "alloc", "end", "tag", "encodeMessage", "buf", "decodeMessage", "toRFC3339", "time", "year", "month", "day", "hour", "minute", "seconds", "milliseconds", "nanoseconds", "parseRFC3339", "rfc3339Matcher", "m", "date", "second", "millisecond", "Libp2pRecord", "_Libp2pRecord", "key", "value", "timeReceived", "Record", "toRFC3339", "raw", "rec", "obj", "receivedTime", "parseRFC3339", "EventTypes", "dhtRoutingKey", "key", "Key", "toString", "localStore", "datastore", "routingKey", "marshalledRecord", "options", "existingBuf", "existingRecord", "Libp2pRecord", "equals", "err", "record", "CustomProgressEvent", "buf", "IPNS_STRING_PREFIX", "isCodec", "digest", "codec", "log", "logger", "MINUTE", "HOUR", "DEFAULT_LIFETIME_MS", "DEFAULT_REPUBLISH_INTERVAL_MS", "DEFAULT_TTL_NS", "bases", "base36", "base58btc", "DefaultIPNS", "components", "routers", "helia", "localStore", "key", "value", "options", "sequenceNumber", "routingKey", "multihashToIPNSRoutingKey", "record", "unmarshalIPNSRecord", "ttlNs", "createIPNSRecord", "marshaledRecord", "marshalIPNSRecord", "r", "err", "CustomProgressEvent", "digest", "isPublicKey", "#findIpnsRecord", "#resolve", "domain", "dnslink", "resolveDNSLink", "republish", "startTime", "timeTaken", "nextInterval", "ipfsPath", "parts", "scheme", "str", "prefix", "buf", "UnsupportedMultibasePrefixError", "decode", "CID", "isCodec", "UnsupportedMultihashCodecError", "cid", "path", "InvalidValueError", "records", "created", "ipnsValidator", "ipnsRecord", "ttlMs", "NotFoundError", "foundInvalid", "router", "RecordsFailedValidationError", "ipnsSelector", "mh", "extractPublicKeyFromIPNSRecord", "IPNS_STRING_PREFIX", "peerIdFromString", "ipns"]
|
|
7
7
|
}
|