@libp2p/bootstrap 12.0.15 → 12.0.16-811a29f8a
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 +1 -4
- package/dist/index.min.js.map +4 -4
- package/package.json +8 -7
- package/dist/typedoc-urls.json +0 -8
package/dist/index.min.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/peer-discovery.ts", "../../interface/src/peer-id.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bases/base58.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/base32.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/base64.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", "../../crypto/src/keys/rsa/der.ts", "../../crypto/src/keys/ecdsa/index.ts", "../../crypto/src/keys/ecdsa/utils.ts", "../../crypto/src/keys/ecdsa/ecdsa.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/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", "../../crypto/src/errors.ts", "../../crypto/src/webcrypto/webcrypto.browser.ts", "../../crypto/src/webcrypto/index.ts", "../../crypto/src/keys/ed25519/index.browser.ts", "../../crypto/src/util.ts", "../../crypto/src/keys/ed25519/ed25519.ts", "../../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/stream.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../crypto/src/keys/keys.ts", "../../../node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/@noble/curves/src/secp256k1.ts", "../../crypto/src/keys/secp256k1/index.browser.ts", "../../crypto/src/keys/secp256k1/secp256k1.ts", "../../crypto/src/keys/secp256k1/utils.ts", "../../crypto/src/keys/index.ts", "../../peer-id/src/peer-id.ts", "../../peer-id/src/index.ts", "../../../node_modules/@multiformats/multiaddr/src/errors.ts", "../../../node_modules/@chainsafe/is-ip/src/parser.ts", "../../../node_modules/@chainsafe/is-ip/src/parse.ts", "../../../node_modules/@chainsafe/is-ip/src/is-ip.ts", "../../../node_modules/@multiformats/multiaddr/src/utils.ts", "../../../node_modules/@multiformats/multiaddr/src/validation.ts", "../../../node_modules/@multiformats/multiaddr/src/registry.ts", "../../../node_modules/@multiformats/multiaddr/src/components.ts", "../../../node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../../../node_modules/@multiformats/multiaddr/src/index.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/utils.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\n\nimport { peerDiscoverySymbol, serviceCapabilities } from '@libp2p/interface'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { CODE_P2P, multiaddr } from '@multiformats/multiaddr'\nimport { P2P } from '@multiformats/multiaddr-matcher'\nimport { TypedEventEmitter } from 'main-event'\nimport type { ComponentLogger, Logger, PeerDiscovery, PeerDiscoveryEvents, PeerInfo, PeerStore, Startable } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\n\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap'\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000\n\nexport interface BootstrapInit {\n /**\n * The list of peer addresses in multi-address format\n */\n list: string[]\n\n /**\n * How long to wait before discovering bootstrap nodes\n */\n timeout?: number\n\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it\n *\n * @default 'bootstrap'\n */\n tagName?: string\n\n /**\n * The bootstrap peer tag will have this value\n *\n * @default 50\n */\n tagValue?: number\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms\n */\n tagTTL?: number\n}\n\nexport interface BootstrapComponents {\n peerStore: PeerStore\n logger: ComponentLogger\n connectionManager: ConnectionManager\n}\n\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter<PeerDiscoveryEvents> implements PeerDiscovery, Startable {\n static tag = 'bootstrap'\n\n private readonly log: Logger\n private timer?: ReturnType<typeof setTimeout>\n private readonly list: PeerInfo[]\n private readonly timeout: number\n private readonly components: BootstrapComponents\n private readonly _init: BootstrapInit\n\n constructor (components: BootstrapComponents, options: BootstrapInit = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses')\n }\n super()\n\n this.components = components\n this.log = components.logger.forComponent('libp2p:bootstrap')\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT\n this.list = options.list\n .map(str => multiaddr(str))\n .filter(ma => {\n if (!P2P.matches(ma)) {\n this.log.error('invalid multiaddr %a', ma)\n return false\n }\n\n const peerIdStr = ma.getComponents().findLast(c => c.code === CODE_P2P)?.value\n\n if (peerIdStr == null) {\n this.log.error('invalid bootstrap multiaddr without peer id')\n return false\n }\n\n return true\n })\n .map(ma => {\n return {\n id: peerIdFromString(ma.getComponents().findLast(c => c.code === CODE_P2P)?.value ?? ''),\n multiaddrs: [ma]\n }\n })\n\n this._init = options\n }\n\n readonly [peerDiscoverySymbol] = this\n\n readonly [Symbol.toStringTag] = '@libp2p/bootstrap'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/peer-discovery'\n ]\n\n isStarted (): boolean {\n return Boolean(this.timer)\n }\n\n /**\n * Start emitting events\n */\n start (): void {\n if (this.isStarted()) {\n return\n }\n\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout)\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error('failed to discover bootstrap peers - %e', err)\n })\n }, this.timeout)\n }\n\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers (): Promise<void> {\n if (this.timer == null) {\n return\n }\n\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL\n }\n },\n multiaddrs: peerData.multiaddrs\n })\n\n // check we are still running\n if (this.timer == null) {\n return\n }\n\n this.safeDispatchEvent('peer', { detail: peerData })\n this.components.connectionManager.openConnection(peerData.id)\n .catch(err => {\n this.log.error('could not dial bootstrap peer %p - %e', peerData.id, err)\n })\n }\n }\n\n /**\n * Stop emitting events\n */\n stop (): void {\n if (this.timer != null) {\n clearTimeout(this.timer)\n }\n\n this.timer = undefined\n }\n}\n\nexport function bootstrap (init: BootstrapInit): (components: BootstrapComponents) => PeerDiscovery {\n return (components: BootstrapComponents) => new Bootstrap(components, init)\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 protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\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 stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\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 an 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\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "import type { PeerInfo } from './peer-info.js'\nimport type { TypedEventTarget } from 'main-event'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery')\n\n/**\n * Implementers of this interface can provide a PeerDiscovery implementation to\n * interested callers.\n */\nexport interface PeerDiscoveryProvider {\n [peerDiscoverySymbol]: PeerDiscovery\n}\n\nexport interface PeerDiscoveryEvents {\n peer: CustomEvent<PeerInfo>\n}\n\n/**\n * A class that implements the `PeerDiscovery` interface uses an\n * implementation-specific method to discover peers. These peers are then added\n * to the peer store for use by other system components and services.\n */\nexport interface PeerDiscovery extends TypedEventTarget<PeerDiscoveryEvents> {}\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 * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.js'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n super.addEventListener(type, listener, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n dispatchEvent (event: Event): boolean {\n const result = super.dispatchEvent(event)\n\n let list = this.#listeners.get(event.type)\n\n if (list == null) {\n return result\n }\n\n list = list.filter(({ once }) => !once)\n this.#listeners.set(event.type, list)\n\n return result\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends NewStreamOptions {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: PeerId | Multiaddr | Multiaddr[], options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: PeerId | Multiaddr | Multiaddr[], protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\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", "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 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, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\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 = alphabetIdx[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\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\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 const alphabetIdx = createAlphabetIdx(alphabet)\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, alphabetIdx, bitsPerChar, name)\n }\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", "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'\nimport type { DigestOptions } from './hasher.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\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 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", "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\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): Hasher<Name, Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\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 readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\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 { AbortOptions } from '@libp2p/interface'\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, options?: AbortOptions): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n options?.signal?.throwIfAborted()\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n options?.signal?.throwIfAborted()\n\n const result = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return result\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, AbortOptions } 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, options?: AbortOptions): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data, options)\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, options?: AbortOptions): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message, options)\n }\n}\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\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, title: string = ''): void {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(value: Uint8Array, length?: number, title: string = ''): Uint8Array {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n}\n\n/** Asserts something is hash */\nexport function ahash(h: CHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash must 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, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + 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/** 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;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\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/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\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, errorTitle = ''): Uint8Array {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\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 = {};\n/** Merges default options and passed options. */\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 must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hashes. */\nexport interface Hash<T> {\n blockLen: number; // Bytes per block\n outputLen: number; // Bytes in output\n update(buf: Uint8Array): this;\n digestInto(buf: Uint8Array): void;\n digest(): Uint8Array;\n destroy(): void;\n _cloneInto(to?: T): T;\n clone(): T;\n}\n\n/** PseudoRandom (number) Generator */\nexport interface PRG {\n addEntropy(seed: Uint8Array): void;\n randomBytes(length: number): Uint8Array;\n clean(): void;\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 constructor */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash params. */\nexport type HashInfo = {\n oid?: Uint8Array; // DER encoded OID in bytes\n};\n/** Hash function */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n outputLen: number;\n blockLen: number;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: Uint8Array): Uint8Array;\n create(): T;\n }\n : {\n (msg: Uint8Array, opts?: Opts): Uint8Array;\n create(opts?: Opts): T;\n });\n/** XOF with output */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/** Creates function with outputLen, blockLen, create properties from a class constructor. */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: HashInfo = {}\n): CHash<T, Opts> {\n const hashC: any = (msg: Uint8Array, opts?: Opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */\nexport const oidNist = (suffix: number): Required<HashInfo> => ({\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, createView, type Hash } from './utils.ts';\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>> implements 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 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: Uint8Array): this {\n aexists(this);\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 view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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 as unknown as any;\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://www.rfc-editor.org/rfc/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, oidNist, 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);\n\n/** Internal 32-byte base SHA2 hash class. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\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\n/** Internal SHA2-256 hash class. */\nexport class _SHA256 extends SHA2_32B<_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 constructor() {\n super(32);\n }\n}\n\n/** Internal SHA2-224 hash class. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\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\n/** Internal 64-byte base SHA2 hash class. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\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 abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\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\n/** Internal SHA2-512 hash class. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\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() {\n super(64);\n }\n}\n\n/** Internal SHA2-384 hash class. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\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\n/** Internal SHA2-512/224 hash class. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\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\n/** Internal SHA2-512/256 hash class. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\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. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n */\nexport const sha256: CHash<_SHA256> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224: CHash<_SHA224> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512: CHash<_SHA512> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384: CHash<_SHA384> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\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<_SHA512_256> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\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<_SHA512_224> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n} from '@noble/hashes/utils.js';\nexport {\n abytes,\n anumber,\n bytesToHex,\n concatBytes,\n hexToBytes,\n isBytes,\n randomBytes,\n} from '@noble/hashes/utils.js';\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type CHash = {\n (message: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array) => Uint8Array;\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n// Used in weierstrass, der\nfunction abignumber(n: number | bigint) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new Error('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\nexport function asafenumber(value: number, title: string = ''): void {\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new Error(prefix + 'expected safe integer, got type=' + typeof value);\n }\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(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// 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 return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n anumber(len);\n n = abignumber(n);\n const res = hexToBytes_(n.toString(16).padStart(len * 2, '0'));\n if (res.length !== len) throw new Error('number too large');\n return res;\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(abignumber(n)));\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes: Uint8Array): Uint8Array {\n return Uint8Array.from(bytes);\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n */\nexport function asciiToBytes(ascii: string): Uint8Array {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n });\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\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, message: Uint8Array) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n anumber(hashLen, 'hashLen');\n anumber(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n const u8n = (len: number): Uint8Array => new Uint8Array(len); // creates Uint8Array\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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 = (...msgs: Uint8Array[]) => hmacFn(k, concatBytes_(v, ...msgs)); // hmac(k)(v, ...values)\n const reseed = (seed: Uint8Array = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (!object || typeof object !== 'object') throw new Error('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\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\nexport interface CryptoKeys {\n lengths: { seed?: number; public?: number; secret?: number };\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field 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 {\n abytes,\n anumber,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _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 * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\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\nfunction assertIsSquare<T>(Fp: IField<T>, root: T, n: T): void {\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const p1div4 = (Fp.ORDER + _1n) / _4n;\n const root = Fp.pow(n, p1div4);\n assertIsSquare(Fp, root, n);\n return root;\n}\n\nfunction sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const p5div8 = (Fp.ORDER - _5n) / _8n;\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, p5div8);\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 assertIsSquare(Fp, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): <T>(Fp: IField<T>, n: T) => T {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return <T>(Fp: IField<T>, n: T) => {\n let tv1 = Fp.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = Fp.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = Fp.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = Fp.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = Fp.eql(Fp.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = Fp.eql(Fp.sqr(tv3), n); // 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.eql(Fp.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = Fp.cmov(tv1, tv2, e3);// 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(Fp, root, n);\n return root;\n };\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 // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n if (Fp.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(Fp, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!Fp.eql(t, Fp.ONE)) {\n if (Fp.is0(t)) return Fp.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = Fp.sqr(t); // t^(2^1)\n while (!Fp.eql(t_tmp, Fp.ONE)) {\n i++;\n t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = Fp.sqr(b); // c = b^2\n t = Fp.mul(t, c); // t = (t * b^2)\n R = Fp.mul(R, b); // R = R*b\n }\n return R;\n };\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\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) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // 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 BYTES: number;\n BITS: number;\n isLE: boolean;\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 isValidNot0: (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 invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): 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 BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // const max = 16384;\n // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');\n // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');\n return field;\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 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): -1 | 0 | 1 {\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (Fp.ORDER - _1n) / _2n;\n const powered = Fp.pow(n, p1mod2);\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('invalid Legendre symbol result');\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 === 1;\n}\n\nexport type NLength = { nByteLength: number; nBitLength: number };\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number): NLength {\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'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes)\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: number[];\n private _sqrt: ReturnType<typeof FpSqrt> | undefined; // cached sqrt\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n if (ORDER <= _0n) throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function') this.sqrt = opts.sqrt;\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n this._sqrt = undefined;\n Object.preventExtensions(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching _sqrt speeds up sqrt9mod16 by 5x and tonneli-shanks by 10%\n if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);\n return this._sqrt(this, num);\n }\n toBytes(num: bigint) {\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // NOTE: we don't validate scalar here, please use isValid. This done such way because some\n // protocol may allow non-reduced scalar that reduced later or changed some other way.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\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: bigint, b: bigint, condition: boolean) {\n return condition ? b : a;\n }\n}\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. `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 *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER field order, probably prime, or could be composite\n * @param bitLen how many bits the field consumes\n * @param isLE (default: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): Readonly<FpField> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\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 * 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.Point.Fn.ORDER)\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 abytes(key);\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 { bitLen, bitMask, type Signer } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic curve Points. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n Z?: F;\n double(): P;\n negate(): P;\n add(other: P): P;\n subtract(other: P): P;\n equals(other: P): boolean;\n multiply(scalar: bigint): P;\n assertValidity(): void;\n clearCofactor(): P;\n is0(): boolean;\n isTorsionFree(): boolean;\n isSmallOrder(): boolean;\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * @param isLazy calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /** Converts point to 2D xy affine coordinates */\n toAffine(invertedZ?: F): AffinePoint<F>;\n toBytes(): Uint8Array;\n toHex(): string;\n}\n\n/** Base interface for all elliptic curve Point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n [Symbol.hasInstance]: (item: unknown) => boolean;\n BASE: P;\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /** Creates point from x, y. Does NOT validate if the point is valid. Use `.assertValidity()`. */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n fromBytes(bytes: Uint8Array): P;\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns Fp type from Point (P_F<P> == P.F) */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns Fp type from PointCons (PC_F<PC> == PC.P.F) */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns Point type from PointCons (PC_P<PC> == PC.P) */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\nexport interface CurveLengths {\n secretKey?: number;\n publicKey?: number;\n publicKeyUncompressed?: number;\n publicKeyHasPrefix?: boolean;\n signature?: number;\n seed?: number;\n}\n\nexport type Mapper<T> = (i: T[]) => T[];\n\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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 */\ntype 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 // To disable precomputes:\n // return 1;\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = 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 point Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.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, this.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(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(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 acc accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.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 assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 secret keys / bigints)\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\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 < slength; 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 P;\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<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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: P) => {\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[]): P => {\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\nexport type ValidCurveParams<T> = {\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b?: T;\n d?: T;\n Gx: T;\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: IField<T>, isLE?: boolean): IField<T> {\n if (field) {\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n } else {\n return Field(order, { isLE }) as unknown as IField<T>;\n }\n}\nexport type FpFn<T> = { Fp: IField<T>; Fn: IField<bigint> };\n\n/** Validates CURVE opts and creates fields */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: Partial<FpFn<T>> = {},\n FpFnLE?: boolean\n): FpFn<T> & { CURVE: ValidCurveParams<T> } {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: Signer['getPublicKey']\n): KeygenFn {\n return function keygen(seed?: Uint8Array) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\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 * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n aInRange,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n hexToBytes,\n isBytes,\n memoized,\n notImplemented,\n validateObject,\n randomBytes as wcRandomBytes,\n type FHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.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/** Instance of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n}\n/** Static methods of Extended Point with coordinates in X, Y, Z, T. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n CURVE(): EdwardsOpts;\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: bigint;\n d: bigint;\n Gx: bigint;\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n Fp: IField<bigint>;\n Fn: IField<bigint>;\n FpFnLE: boolean;\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n adjustScalarBytes: (bytes: Uint8Array) => Uint8Array;\n domain: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n prehash: FHash;\n randomBytes: (bytesLength?: number) => Uint8Array;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) interface.\n *\n * Allows to create and verify signatures, create public and secret keys.\n */\nexport interface EdDSA {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n sign: (\n message: Uint8Array,\n secretKey: Uint8Array,\n options?: { context?: Uint8Array }\n ) => Uint8Array;\n verify: (\n sig: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n options?: { context?: Uint8Array; zip215: boolean }\n ) => boolean;\n Point: EdwardsPointCons;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * ```js\n * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n * const aPriv = x25519.utils.randomSecretKey();\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomery: (publicKey: Uint8Array) => Uint8Array;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv_ed = ed25519.utils.randomSecretKey();\n * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomerySecret: (secretKey: Uint8Array) => Uint8Array;\n getExtendedPublicKey: (key: Uint8Array) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: Uint8Array;\n };\n };\n lengths: CurveLengths;\n}\n\nfunction isEdValidXY(Fp: IField<bigint>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\nexport function edwards(params: EdwardsOpts, extraOpts: EdwardsExtraOpts = {}): EdwardsPointCons {\n const validated = createCurveFields('edwards', params, extraOpts, extraOpts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n validateObject(extraOpts, {}, { uvRatio: 'function' });\n\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(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n extraOpts.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aedpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('EdwardsPoint 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 { X, Y, 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 x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\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 { X, Y, Z, 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 EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\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 acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[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('point.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('bad point: 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('bad point: 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\n static fromHex(hex: string, zip215 = false): Point {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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.X), this.Y, this.Z, modP(-this.T));\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 { X: X1, Y: Y1, Z: 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 aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: 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 // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [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 // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new Error('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), 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.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, invertedZ);\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points.\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: string): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for prime-order groups\n return this as any;\n }\n\n assertValidity(): void {\n this.ep.assertValidity();\n }\n\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n return this.init(this.ep.precompute(windowSize, isLazy));\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n */\nexport function eddsa(Point: EdwardsPointCons, cHash: FHash, eddsaOpts: EdDSAOpts = {}): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n validateObject(\n eddsaOpts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = eddsaOpts;\n const { BASE, Fp, Fn } = Point;\n\n const randomBytes = eddsaOpts.randomBytes || wcRandomBytes;\n const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const domain =\n eddsaOpts.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\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: Uint8Array) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\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 = abytes(cHash(key), 2 * len, 'hashedSecretKey');\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(secretKey: Uint8Array) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: Uint8Array): Uint8Array {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Uint8Array = Uint8Array.of(), ...msgs: Uint8Array[]) {\n const msg = concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(\n msg: Uint8Array,\n secretKey: Uint8Array,\n options: { context?: Uint8Array } = {}\n ): Uint8Array {\n msg = abytes(msg, undefined, 'message');\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n\n // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\n const verifyOpts: { context?: Uint8Array; zip215?: boolean } = { zip215: true };\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(\n sig: Uint8Array,\n msg: Uint8Array,\n publicKey: Uint8Array,\n options = verifyOpts\n ): boolean {\n const { context, zip215 } = options;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, 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.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false; // zip215 allows public keys of small order\n\n const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), 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().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed = randomBytes(lengths.seed)): Uint8Array {\n return abytes(seed, lengths.seed, 'seed');\n }\n\n function isValidSecretKey(key: Uint8Array): boolean {\n return isBytes(key) && key.length === Fn.BYTES;\n }\n\n function isValidPublicKey(key: Uint8Array, zip215?: boolean): boolean {\n try {\n return !!Point.fromBytes(key, zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: Uint8Array): Uint8Array {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey: Uint8Array): Uint8Array {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = cHash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n }) satisfies Signer;\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.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n eddsa,\n edwards,\n PrimeEdwardsPoint,\n type EdDSA,\n type EdDSAOpts,\n type EdwardsOpts,\n type EdwardsPoint,\n type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CDSTOpts,\n type H2CHasher,\n type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createORPF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\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_CURVE_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// \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// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_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\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\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 asciiToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nfunction ed(opts: EdDSAOpts) {\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, pub); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/** Context version of ed25519 (ctx for domain separation). See {@link ed25519} */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/** Prehashed version of ed25519. See {@link ed25519} */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: MontgomeryECDH = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\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 });\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\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _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/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n const ELL2_C4 = (ed25519_CURVE_p - _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\n/** Hashing to ed25519 points / field. RFC 9380 methods. */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519_Point,\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: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\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) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on\n * the [website](https://ristretto.group/formulas/elligator.html).\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\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_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint 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 EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: EdwardsPoint) {\n super(ep);\n }\n\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n static fromBytes(bytes: Uint8Array): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\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(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\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)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: string): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): Uint8Array {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\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 Fp.toBytes(s); // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\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 is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = { Point: _RistrettoPoint };\n\n/** Hashing to ristretto255 points / field. RFC 9380 methods. */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = {\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, we are using version from OPRF here, using bytes255ToNumblerLE will create different result if we use bytes255ToNumberLE as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg: Uint8Array, options?: H2CDSTOpts): _RistrettoPoint {\n // == 'hash_to_ristretto255'\n const DST = options?.DST || 'ristretto255_XMD:SHA-512_R255MAP_RO_';\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function 'ristretto255_map', in RFC 9496 map was function inside (per point)\n // That also lead to confustion that ristretto255_map is mapToCurve (it is not! it is old hashToCurve)\n return ristretto255_hasher.deriveToCurve!(xmd);\n },\n hashToScalar(msg: Uint8Array, options: H2CDSTOpts = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction, preceding the finalization of RFC 9380.\n * It was later reused as a component in the newer `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes: Uint8Array): _RistrettoPoint {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n};\n\n/** ristretto255 OPRF, defined in RFC 9497. */\nexport const ristretto255_oprf: OPRF = /* @__PURE__ */ (() =>\n createORPF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * \u27E8T\u27E9 = { O, T, 2T, 3T, 4T, 5T, 6T, 7T }\n */\nexport const ED25519_TORSION_SUBGROUP: string[] = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\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 { ed25519 as ed } from '@noble/curves/ed25519.js'\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string'\nimport crypto from '../../webcrypto/index.js'\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\n// memoize support result to skip additional awaits every time we use an ed key\nlet ed25519Supported: boolean | undefined\nconst webCryptoEd25519SupportedPromise = (async () => {\n try {\n await crypto.get().subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])\n return true\n } catch {\n return false\n }\n})()\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomSecretKey()\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\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\nasync function hashAndSignWebCrypto (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n let privateKeyRaw: Uint8Array\n if (privateKey.length === PRIVATE_KEY_BYTE_LENGTH) {\n privateKeyRaw = privateKey.subarray(0, 32)\n } else {\n privateKeyRaw = privateKey\n }\n\n const jwk: JsonWebKey = {\n crv: 'Ed25519',\n kty: 'OKP',\n x: uint8arrayToString(privateKey.subarray(32), 'base64url'),\n d: uint8arrayToString(privateKeyRaw, 'base64url'),\n ext: true,\n key_ops: ['sign']\n }\n\n const key = await crypto.get().subtle.importKey('jwk', jwk, { name: 'Ed25519' }, true, ['sign'])\n const sig = await crypto.get().subtle.sign({ name: 'Ed25519' }, key, msg instanceof Uint8Array ? msg : msg.subarray())\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport function hashAndSignNoble (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 async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndSignWebCrypto(privateKey, msg)\n }\n\n return hashAndSignNoble(privateKey, msg)\n}\n\nasync function hashAndVerifyWebCrypto (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (publicKey.buffer instanceof ArrayBuffer) {\n const key = await crypto.get().subtle.importKey('raw', publicKey.buffer, { name: 'Ed25519' }, false, ['verify'])\n const isValid = await crypto.get().subtle.verify({ name: 'Ed25519' }, key, sig, msg instanceof Uint8Array ? msg : msg.subarray())\n return isValid\n }\n\n throw new TypeError('WebCrypto does not support SharedArrayBuffer for Ed25519 keys')\n}\n\nexport function hashAndVerifyNoble (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndVerifyWebCrypto(publicKey, sig, msg)\n }\n\n return hashAndVerifyNoble(publicKey, sig, msg)\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 { 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) {\n throw new Error('byte array longer than desired length')\n }\n\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 { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../../util.ts'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\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, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n const result = crypto.hashAndVerify(this.raw, sig, data)\n\n if (isPromise<boolean>(result)) {\n return result.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n return result\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n options?.signal?.throwIfAborted()\n const sig = crypto.hashAndSign(this.raw, message)\n\n if (isPromise<Uint8Array>(sig)) {\n return sig.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n options?.signal?.throwIfAborted()\n return sig\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.ts'\nimport { LongBits } from './longbits.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Reader } from '../index.ts'\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.ts'\nimport type { Codec, DecodeOptions } from './codec.ts'\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.ts'\nimport { LongBits } from './longbits.ts'\nimport pool from './pool.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Writer } from '../index.ts'\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 {}\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.ts'\nimport type { Codec } from './codec.ts'\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 { createReader } from './utils/reader.ts'\nimport type { Codec } from './codec.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function * streamMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'stream'>, opts?: any): Generator<any> {\n const reader = createReader(buf)\n\n yield * codec.stream(reader, undefined, '$', opts)\n}\n", "import type { Writer, Reader } from './index.ts'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport const CODEC_TYPES = {\n VARINT: 0,\n BIT64: 1,\n LENGTH_DELIMITED: 2,\n START_GROUP: 3,\n END_GROUP: 4,\n BIT32: 5\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 StreamFunction<T> {\n (reader: Reader, length?: number, prefix?: string, opts?: DecodeOptions<T>): Generator<any>\n}\n\nexport interface Codec<T> {\n name: string\n type: number\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n stream: StreamFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: number, encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode,\n stream\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { DecodeFunction, EncodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: any): 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<T> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<any> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n const stream: StreamFunction<T> = function * enumStream (reader) {\n const val = reader.int32()\n\n yield findValue(val)\n }\n\n return createCodec<T>('enum', CODEC_TYPES.VARINT, encode, decode, stream)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { EncodeFunction, DecodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, stream)\n}\n", "import { decodeMessage, encodeMessage, enumeration, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } 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}\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 }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PublicKeyTypeFieldEvent {\n field: '$.Type'\n value: KeyType\n }\n\n export interface PublicKeyDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PublicKey>): Uint8Array {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): Generator<PublicKeyTypeFieldEvent | PublicKeyDataFieldEvent> {\n return streamMessage(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 }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PrivateKeyTypeFieldEvent {\n field: '$.Type'\n value: KeyType\n }\n\n export interface PrivateKeyDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PrivateKey>): Uint8Array {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): Generator<PrivateKeyTypeFieldEvent | PrivateKeyDataFieldEvent> {\n return streamMessage(buf, PrivateKey.codec(), opts)\n }\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, type CHash, type Hash } from './utils.ts';\n\n/** Internal class for HMAC. */\nexport class _HMAC<T extends Hash<T>> implements 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: Uint8Array) {\n ahash(hash);\n abytes(key, undefined, '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: Uint8Array): 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, 'output');\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: Uint8Array, message: Uint8Array): Uint8Array;\n create(hash: CHash, key: Uint8Array): _HMAC<any>;\n} = (hash: CHash, key: Uint8Array, message: Uint8Array): Uint8Array =>\n new _HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Uint8Array) => new _HMAC<any>(hash, key);\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\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) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abool,\n abytes,\n aInRange,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n memoized,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type Signer,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * [gist](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n */\nexport type EndomorphismOpts = {\n beta: bigint;\n basises?: EndoBasis;\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\nexport type ScalarEndoParts = { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n\n/**\n * Splits scalar for GLV endomorphism.\n */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * https://paulmillr.com/posts/deterministic-signatures/\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures which have (sig.s >= CURVE.n/2n).\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates sigs with increased security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n prehash?: boolean;\n lowS?: boolean;\n format?: ECDSASignatureFormat;\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): Required<ECDSASignOpts> {\n const optsn: ECDSASignOpts = {};\n for (let optName of Object.keys(def)) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn as Required<ECDSASignOpts>;\n}\n\n/** Instance methods for 3D XYZ projective points. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /** Encodes point using IEEE P1363 (DER) encoding. First byte is 2/3/4. Default = isCompressed. */\n toBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n\n/** Static methods for 3D XYZ projective points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n p: bigint;\n n: bigint;\n h: bigint;\n a: T;\n b: T;\n Gx: T;\n Gy: T;\n}>;\n\n// When a cofactor != 1, there can be an effective methods to:\n// 1. Determine whether a point is torsion-free\n// 2. Clear torsion component\nexport type WeierstrassExtraOpts<T> = Partial<{\n Fp: IField<T>;\n Fn: IField<bigint>;\n allowInfinityPoint: boolean;\n endo: EndomorphismOpts;\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n fromBytes: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => Uint8Array;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced / verified signatures occupy low half of ecdsaOpts.p. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves\n */\nexport type ECDSAOpts = Partial<{\n lowS: boolean;\n hmac: (key: Uint8Array, message: Uint8Array) => Uint8Array;\n randomBytes: (bytesLength?: number) => Uint8Array;\n bits2int: (bytes: Uint8Array) => bigint;\n bits2int_modN: (bytes: Uint8Array) => bigint;\n}>;\n\n/**\n * Elliptic Curve Diffie-Hellman interface.\n * Provides keygen, secret-to-public conversion, calculating shared secrets.\n */\nexport interface ECDH {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: (secretKey: Uint8Array, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed?: boolean\n ) => Uint8Array;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n isValidSecretKey: (secretKey: Uint8Array) => boolean;\n isValidPublicKey: (publicKey: Uint8Array, isCompressed?: boolean) => boolean;\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n };\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n sign: (message: Uint8Array, secretKey: Uint8Array, opts?: ECDSASignOpts) => Uint8Array;\n verify: (\n signature: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts?: ECDSAVerifyOpts\n ) => boolean;\n recoverPublicKey(signature: Uint8Array, message: Uint8Array, opts?: ECDSARecoverOpts): Uint8Array;\n Signature: ECDSASignatureCons;\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(bytes: Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n *\n * @example\n```js\nconst opts = {\n p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n};\nconst secp160k1_Point = weierstrass(opts);\n```\n */\nexport function weierstrass<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n const { endo } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): Uint8Array {\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx);\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes: Uint8Array) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes || pointToBytes;\n const decodePoint = extraOpts.fromBytes || pointFromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x\u00B2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\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 { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\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 (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) 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 function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: Uint8Array): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\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) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: Point): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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 { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n if (!Fn.isValidNot0(scalar)) throw new Error('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n if (!Fn.isValid(sc)) throw new Error('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n return toAffineMemo(this, invertedZ);\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n // can we use this.clearCofactor()?\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n toBytes(isCompressed = true): Uint8Array {\n abool(isCompressed, 'isCompressed');\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n return Point;\n}\n\n/** Methods of ECDSA signature instance. */\nexport interface ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n hasHighS(): boolean;\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint<bigint>;\n toBytes(format?: string): Uint8Array;\n toHex(format?: string): string;\n}\n/** Methods of ECDSA signature constructor. */\nexport type ECDSASignatureCons = {\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n fromBytes(bytes: Uint8Array, format?: ECDSASignatureFormat): ECDSASignature;\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): Uint8Array {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\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 const { A, B, Z } = opts;\n if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, Z);\n if (!Fp.isOdd) throw new Error('Field does not have .isOdd()');\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, 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, B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, 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, 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, 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\nfunction getWLengths<T>(Fp: IField<T>, Fn: IField<bigint>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: { randomBytes?: (bytesLength?: number) => Uint8Array } = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes || wcRandomBytes;\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });\n\n function isValidSecretKey(secretKey: Uint8Array) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: Uint8Array, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed = randomBytes_(lengths.seed)): Uint8Array {\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: Uint8Array, isCompressed = true): Uint8Array {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: Uint8Array): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n if (!isBytes(item)) return undefined;\n if (('_lengths' in Fn && Fn._lengths) || secretKey === publicKey) return undefined;\n const l = abytes(item, undefined, 'key').length;\n return l === publicKey || l === publicKeyUncompressed;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(\n secretKeyA: Uint8Array,\n publicKeyB: Uint8Array,\n isCompressed = true\n ): Uint8Array {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point created using {@link weierstrass} function\n * @param hash used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts rarely needed, see {@link ECDSAOpts}\n *\n * @example\n * ```js\n * const p256_Point = weierstrass(...);\n * const p256_sha256 = ecdsa(p256_Point, sha256);\n * const p256_sha224 = ecdsa(p256_Point, sha224);\n * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: CHash,\n ecdsaOpts: ECDSAOpts = {}\n): ECDSA {\n ahash(hash);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes || wcRandomBytes;\n const hmac = ecdsaOpts.hmac || ((key, msg) => nobleHmac(hash, key, msg));\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n const hasLargeCofactor = CURVE_ORDER * _2n < Fp.ORDER; // Won't CURVE().h > 2n be more effective?\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertSmallCofactor(): void {\n // ECDSA recovery is hard for cofactor > 1 curves.\n // In sign, `r = q.x mod n`, and here we recover q.x from r.\n // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.\n // However, for cofactor>1, r+n may not get q.x:\n // r+n*i would need to be done instead where i is unknown.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit non-prime-order signatures (recid > 1).\n if (hasLargeCofactor)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: Uint8Array, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertSmallCofactor();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: Uint8Array,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(messageHash: Uint8Array): WeierstrassPoint<bigint> {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this));\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertSmallCofactor();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);\n }\n return concatBytes(rb, sb);\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\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 ecdsaOpts.bits2int ||\n function bits2int_def(bytes: Uint8Array): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n ecdsaOpts.bits2int_modN ||\n function bits2int_modN_def(bytes: Uint8Array): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // Pads output with zero as per spec\n const ORDER_MASK = bitMask(fnBits);\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): Uint8Array {\n // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n\n function validateMsgAndHash(message: Uint8Array, prehash: boolean) {\n abytes(message, undefined, 'message');\n return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: Uint8Array): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeCofactor ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs message hash with a secret key.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message: Uint8Array, secretKey: Uint8Array, opts: ECDSASignOpts = {}): Uint8Array {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<Signature>(hash.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: Uint8Array,\n message: Uint8Array,\n publicKey: Uint8Array,\n opts: ECDSAVerifyOpts = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: Uint8Array,\n message: Uint8Array,\n opts: ECDSARecoverOpts = {}\n ): Uint8Array {\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash,\n }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes } from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts<bigint> = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\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(asciiToBytes(tag));\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.toBytes(true).slice(1);\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: Uint8Array) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\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 Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(secretKey: Uint8Array): Uint8Array {\n return schnorrGetExtPubKey(secretKey).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: Uint8Array,\n secretKey: Uint8Array,\n auxRand: Uint8Array = randomBytes(32)\n): Uint8Array {\n const { Fn } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n const t = Fn.toBytes(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 // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);\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(Fn.toBytes(Fn.create(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: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!Fn.isValidNot0(s)) return false;\n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport type SecpSchnorr = {\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n getPublicKey: typeof schnorrGetPublicKey;\n sign: typeof schnorrSign;\n verify: typeof schnorrVerify;\n Point: WeierstrassPointCons<bigint>;\n utils: {\n randomSecretKey: (seed?: Uint8Array) => Uint8Array;\n pointToBytes: (point: PointType<bigint>) => Uint8Array;\n lift_x: typeof lift_x;\n taggedHash: typeof taggedHash;\n };\n lengths: CurveLengths;\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.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed = randomBytes(seedLength)): Uint8Array => {\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return {\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: {\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n },\n lengths: {\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n },\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\n/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */\nexport const secp256k1_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\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 }\n ))();\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1.js'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\nimport type { AbortOptions } from '@libp2p/interface'\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.sign(digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key, {\n prehash: false,\n format: 'der'\n })\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, options?: AbortOptions): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new VerificationError(String(err))\n })\n }\n\n try {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, p.digest, key, {\n prehash: false,\n format: 'der'\n })\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, AbortOptions } 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, options?: AbortOptions): boolean {\n return hashAndVerify(this._key, sig, data, options)\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message, options)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js'\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 return secp.Point.fromBytes(key).toBytes()\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n return secp.Point.fromBytes(key).toBytes(false)\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.Point.fromBytes(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.randomSecretKey()\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 } 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 { MultibaseDecoder } from 'multiformats/cid'\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", "/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n name = 'InvalidMultiaddrError'\n}\n\nexport class ValidationError extends Error {\n static name = 'ValidationError'\n name = 'ValidationError'\n}\n\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n\nexport class UnknownProtocolError extends Error {\n static name = 'UnknownProtocolError'\n name = 'UnknownProtocolError'\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-return */\n\n// Heavily inspired by https://doc.rust-lang.org/src/std/net/parser.rs.html\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn = (...foo: any) => any;\n\nexport class Parser {\n private index = 0;\n private input = \"\";\n\n new(input: string): this {\n this.index = 0;\n this.input = input;\n return this;\n }\n\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically<T extends Fn>(fn: T): ReturnType<T> {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith<T extends Fn>(fn: T): ReturnType<T> | undefined {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n\n /** Peek the next character from the input */\n peekChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n\n /** Read the next character from the input */\n readChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target: string): string | undefined {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator<T extends Fn>(sep: string, index: number, inner: T): ReturnType<T> {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(\n radix: number,\n maxDigits: number | undefined,\n allowZeroPrefix: boolean,\n maxBytes: number\n ): number | undefined {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n\n if (digitCount === 0) {\n return undefined;\n } else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n } else {\n return result;\n }\n });\n }\n\n /** Read an IPv4 address. */\n readIPv4Addr(): Uint8Array | undefined {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n\n return out;\n });\n }\n\n /** Read an IPv6 Address. */\n readIPv6Addr(): Uint8Array | undefined {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups: Uint8Array): [number, boolean] => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n\n return [ix + 4, true];\n }\n }\n\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n\n if (headSize === 16) {\n return head;\n }\n\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n\n return head;\n });\n }\n\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr(): Uint8Array | undefined {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n", "import { Parser } from \"./parser.js\";\n\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\n\nconst parser = new Parser();\n\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n\n/** Parse IPv4 `input` into IPv6 with IPv4-mapped bytes, eg ::ffff:1.2.3.4 */\nexport function parseIPv4Mapped(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n\n const ipv4 = parser.new(input).parseWith(() => parser.readIPv4Addr());\n if (ipv4 === undefined) {\n return undefined;\n }\n\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, ipv4[0], ipv4[1], ipv4[2], ipv4[3]]);\n}\n\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input: string): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input: string, mapIPv4ToIPv6 = false): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n\n const addr = parser.new(input).parseWith(() => parser.readIPAddr());\n if (!addr) {\n return undefined;\n }\n\n if (mapIPv4ToIPv6 && addr.length === 4) {\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);\n }\n\n return addr;\n}\n", "import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n\n/** Check if `input` is IPv4. */\nexport function isIPv4(input: string): boolean {\n return Boolean(parseIPv4(input));\n}\n\n/** Check if `input` is IPv6. */\nexport function isIPv6(input: string): boolean {\n return Boolean(parseIPv6(input));\n}\n\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input: string): boolean {\n return Boolean(parseIP(input));\n}\n\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input: string): 4 | 6 | undefined {\n if (isIPv4(input)) {\n return 4;\n } else if (isIPv6(input)) {\n return 6;\n } else {\n return undefined;\n }\n}\n", "import { isIPv4 } from '@chainsafe/is-ip'\nimport { base32 } from 'multiformats/bases/base32'\nimport { bases } from 'multiformats/basics'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport type { MultibaseCodec } from 'multiformats'\nimport type { SupportedEncodings } from 'uint8arrays/to-string'\n\nexport function bytesToString (base: SupportedEncodings): (buf: Uint8Array) => string {\n return (buf) => {\n return uint8ArrayToString(buf, base)\n }\n}\n\nexport function stringToBytes (base: SupportedEncodings): (value: string) => Uint8Array {\n return (buf) => {\n return uint8ArrayFromString(buf, base)\n }\n}\n\nexport function bytes2port (buf: Uint8Array): string {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset).toString()\n}\n\nexport function port2bytes (port: string | number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, typeof port === 'string' ? parseInt(port) : port)\n\n return new Uint8Array(buf)\n}\n\nexport function onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = uint8ArrayFromString(addr[0], 'base32')\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.subarray(0, buf.length - 2)\n const portBytes = buf.subarray(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip4ToBytes = function (ip: string): Uint8Array {\n ip = ip.toString().trim()\n\n const bytes = new Uint8Array(4)\n\n ip.split(/\\./g).forEach((byte, index) => {\n const value = parseInt(byte, 10)\n\n if (isNaN(value) || value < 0 || value > 0xff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[index] = value\n })\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip6ToBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isIPv4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = ip4ToBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.subarray(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.subarray(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) { sections.unshift('0') }\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) { sections.push('0') }\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++) { }\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n if (sections[i] === '') {\n sections[i] = '0'\n }\n\n const word = parseInt(sections[i], 16)\n\n if (isNaN(word) || word < 0 || word > 0xffff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const ip4ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 4) {\n throw new InvalidMultiaddrError('IPv4 address was incorrect length')\n }\n\n const result = []\n\n for (let i = 0; i < buf.byteLength; i++) {\n result.push(buf[i])\n }\n\n return result.join('.')\n}\n\nexport const ip6ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 16) {\n throw new InvalidMultiaddrError('IPv6 address was incorrect length')\n }\n\n const result: string[] = []\n\n for (let i = 0; i < buf.byteLength; i += 2) {\n const byte1 = buf[i]\n const byte2 = buf[i + 1]\n\n const tuple = `${byte1.toString(16).padStart(2, '0')}${byte2.toString(16).padStart(2, '0')}`\n\n result.push(tuple)\n }\n\n const ip = result.join(':')\n\n try {\n const url = new URL(`http://[${ip}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${ip}\"`)\n }\n}\n\nexport function ip6StringToValue (str: string): string {\n try {\n const url = new URL(`http://[${str}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${str}\"`)\n }\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nexport function mb2bytes (mbstr: string): Uint8Array {\n return anybaseDecoder.decode(mbstr)\n}\n\nexport function bytes2mb (base: MultibaseCodec<any>): (buf: Uint8Array) => string {\n return (buf) => {\n return base.encoder.encode(buf)\n }\n}\n", "import { ValidationError } from './errors.ts'\n\nexport function integer (value: string): void {\n const int = parseInt(value)\n\n if (int.toString() !== value) {\n throw new ValidationError('Value must be an integer')\n }\n}\n\nexport function positive (value: any): void {\n if (value < 0) {\n throw new ValidationError('Value must be a positive integer, or zero')\n }\n}\n\nexport function maxValue (max: number): (value: any) => void {\n return (value) => {\n if (value > max) {\n throw new ValidationError(`Value must be smaller than or equal to ${max}`)\n }\n }\n}\n\nexport function validate (...funcs: Array<(value: string) => void>): (value: string) => void {\n return (value) => {\n for (const fn of funcs) {\n fn(value)\n }\n }\n}\n\nexport const validatePort = validate(\n integer,\n positive,\n maxValue(65_535)\n)\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { CID } from 'multiformats'\nimport { base64url } from 'multiformats/bases/base64'\nimport { CODE_CERTHASH, CODE_DCCP, CODE_DNS, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_GARLIC32, CODE_GARLIC64, CODE_HTTP, CODE_HTTP_PATH, CODE_HTTPS, CODE_IP4, CODE_IP6, CODE_IP6ZONE, CODE_IPCIDR, CODE_MEMORY, CODE_NOISE, CODE_ONION, CODE_ONION3, CODE_P2P, CODE_P2P_CIRCUIT, CODE_P2P_STARDUST, CODE_P2P_WEBRTC_DIRECT, CODE_P2P_WEBRTC_STAR, CODE_P2P_WEBSOCKET_STAR, CODE_QUIC, CODE_QUIC_V1, CODE_SCTP, CODE_SNI, CODE_TCP, CODE_TLS, CODE_UDP, CODE_UDT, CODE_UNIX, CODE_UTP, CODE_WEBRTC, CODE_WEBRTC_DIRECT, CODE_WEBTRANSPORT, CODE_WS, CODE_WSS } from './constants.ts'\nimport { UnknownProtocolError, ValidationError } from './errors.ts'\nimport { bytes2mb, bytes2onion, bytes2port, bytesToString, ip4ToBytes, ip4ToString, ip6StringToValue, ip6ToBytes, ip6ToString, mb2bytes, onion2bytes, onion32bytes, port2bytes, stringToBytes } from './utils.ts'\nimport { validatePort } from './validation.ts'\nimport type { Registry as RegistryInterface } from './index.ts'\n\nexport const V = -1\n\nexport interface ProtocolCodec {\n /**\n * A numeric code that will be used in the binary representation of the tuple.\n */\n code: number\n\n /**\n * A string name that will be used in the string representation of the addr.\n */\n name: string\n\n /**\n * Size defines the expected length of the address part of the tuple - valid\n * values are `-1` (or the `V` constant) for variable length (this will be\n * varint encoded in the binary representation), `0` for no address part or a\n * number that represents a fixed-length address.\n */\n size?: number\n\n /**\n * If specified this protocol codec will also be used to decode tuples with\n * these names from string multiaddrs.\n */\n aliases?: string[]\n\n /**\n * Where the multiaddr has been encoded as a string, decode the value if\n * necessary, unescaping any escaped values\n */\n stringToValue?(value: string): string\n\n /**\n * To encode the multiaddr as a string, escape any necessary values\n */\n valueToString?(value: string): string\n\n /**\n * To encode the multiaddr as bytes, convert the value to bytes\n */\n valueToBytes?(value: string): Uint8Array\n\n /**\n * To decode bytes to a multiaddr, convert the value bytes to a string\n */\n bytesToValue?(bytes: Uint8Array): string\n\n /**\n * Perform any necessary validation on the string value\n */\n validate?(value: string): void\n}\n\nclass Registry implements RegistryInterface {\n private protocolsByCode = new Map<number, ProtocolCodec>()\n private protocolsByName = new Map<string, ProtocolCodec>()\n\n getProtocol (key: string | number): ProtocolCodec {\n let codec: ProtocolCodec | undefined\n\n if (typeof key === 'string') {\n codec = this.protocolsByName.get(key)\n } else {\n codec = this.protocolsByCode.get(key)\n }\n\n if (codec == null) {\n throw new UnknownProtocolError(`Protocol ${key} was unknown`)\n }\n\n return codec\n }\n\n addProtocol (codec: ProtocolCodec): void {\n this.protocolsByCode.set(codec.code, codec)\n this.protocolsByName.set(codec.name, codec)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.set(alias, codec)\n })\n }\n\n removeProtocol (code: number): void {\n const codec = this.protocolsByCode.get(code)\n\n if (codec == null) {\n return\n }\n\n this.protocolsByCode.delete(codec.code)\n this.protocolsByName.delete(codec.name)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.delete(alias)\n })\n }\n}\n\nexport const registry = new Registry()\n\nconst codecs: ProtocolCodec[] = [{\n code: CODE_IP4,\n name: 'ip4',\n size: 32,\n valueToBytes: ip4ToBytes,\n bytesToValue: ip4ToString,\n validate: (value) => {\n if (!isIPv4(value)) {\n throw new ValidationError(`Invalid IPv4 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_TCP,\n name: 'tcp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDP,\n name: 'udp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_DCCP,\n name: 'dccp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_IP6,\n name: 'ip6',\n size: 128,\n valueToBytes: ip6ToBytes,\n bytesToValue: ip6ToString,\n stringToValue: ip6StringToValue,\n validate: (value) => {\n if (!isIPv6(value)) {\n throw new ValidationError(`Invalid IPv6 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_IP6ZONE,\n name: 'ip6zone',\n size: V\n}, {\n code: CODE_IPCIDR,\n name: 'ipcidr',\n size: 8,\n bytesToValue: bytesToString('base10'),\n valueToBytes: stringToBytes('base10')\n}, {\n code: CODE_DNS,\n name: 'dns',\n size: V\n}, {\n code: CODE_DNS4,\n name: 'dns4',\n size: V\n}, {\n code: CODE_DNS6,\n name: 'dns6',\n size: V\n}, {\n code: CODE_DNSADDR,\n name: 'dnsaddr',\n size: V\n}, {\n code: CODE_SCTP,\n name: 'sctp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDT,\n name: 'udt'\n}, {\n code: CODE_UTP,\n name: 'utp'\n}, {\n code: CODE_UNIX,\n name: 'unix',\n size: V,\n stringToValue: (str) => decodeURIComponent(str),\n valueToString: (val) => encodeURIComponent(val)\n}, {\n code: CODE_P2P,\n name: 'p2p',\n aliases: ['ipfs'],\n size: V,\n bytesToValue: bytesToString('base58btc'),\n valueToBytes: (val) => {\n if (val.startsWith('Q') || val.startsWith('1')) {\n return stringToBytes('base58btc')(val)\n }\n\n return CID.parse(val).multihash.bytes\n }\n}, {\n code: CODE_ONION,\n name: 'onion',\n size: 96,\n bytesToValue: bytes2onion,\n valueToBytes: onion2bytes\n}, {\n code: CODE_ONION3,\n name: 'onion3',\n size: 296,\n bytesToValue: bytes2onion,\n valueToBytes: onion32bytes\n}, {\n code: CODE_GARLIC64,\n name: 'garlic64',\n size: V\n}, {\n code: CODE_GARLIC32,\n name: 'garlic32',\n size: V\n}, {\n code: CODE_TLS,\n name: 'tls'\n}, {\n code: CODE_SNI,\n name: 'sni',\n size: V\n}, {\n code: CODE_NOISE,\n name: 'noise'\n}, {\n code: CODE_QUIC,\n name: 'quic'\n}, {\n code: CODE_QUIC_V1,\n name: 'quic-v1'\n}, {\n code: CODE_WEBTRANSPORT,\n name: 'webtransport'\n}, {\n code: CODE_CERTHASH,\n name: 'certhash',\n size: V,\n bytesToValue: bytes2mb(base64url),\n valueToBytes: mb2bytes\n}, {\n code: CODE_HTTP,\n name: 'http'\n}, {\n code: CODE_HTTP_PATH,\n name: 'http-path',\n size: V,\n stringToValue: (str) => `/${decodeURIComponent(str)}`,\n valueToString: (val) => encodeURIComponent(val.substring(1))\n}, {\n code: CODE_HTTPS,\n name: 'https'\n}, {\n code: CODE_WS,\n name: 'ws'\n}, {\n code: CODE_WSS,\n name: 'wss'\n}, {\n code: CODE_P2P_WEBSOCKET_STAR,\n name: 'p2p-websocket-star'\n}, {\n code: CODE_P2P_STARDUST,\n name: 'p2p-stardust'\n}, {\n code: CODE_P2P_WEBRTC_STAR,\n name: 'p2p-webrtc-star'\n}, {\n code: CODE_P2P_WEBRTC_DIRECT,\n name: 'p2p-webrtc-direct'\n}, {\n code: CODE_WEBRTC_DIRECT,\n name: 'webrtc-direct'\n}, {\n code: CODE_WEBRTC,\n name: 'webrtc'\n}, {\n code: CODE_P2P_CIRCUIT,\n name: 'p2p-circuit'\n}, {\n code: CODE_MEMORY,\n name: 'memory',\n size: V\n}]\n\ncodecs.forEach(codec => {\n registry.addProtocol(codec)\n})\n", "import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport { registry, V } from './registry.ts'\nimport type { Component } from './index.js'\nimport type { ProtocolCodec } from './registry.ts'\n\nexport function bytesToComponents (bytes: Uint8Array): Component[] {\n const components: Component[] = []\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const codec = registry.getProtocol(code)\n const codeLength = varint.encodingLength(code)\n const size = sizeForAddr(codec, bytes, i + codeLength)\n let sizeLength = 0\n\n if (size > 0 && codec.size === V) {\n sizeLength = varint.encodingLength(size)\n }\n\n const componentLength = codeLength + sizeLength + size\n\n const component: Component = {\n code,\n name: codec.name,\n bytes: bytes.subarray(i, i + componentLength)\n }\n\n if (size > 0) {\n const valueOffset = i + codeLength + sizeLength\n const valueBytes = bytes.subarray(valueOffset, valueOffset + size)\n\n component.value = codec.bytesToValue?.(valueBytes) ?? uint8ArrayToString(valueBytes)\n }\n\n components.push(component)\n\n i += componentLength\n }\n\n return components\n}\n\nexport function componentsToBytes (components: Component[]): Uint8Array {\n let length = 0\n const bytes: Uint8Array[] = []\n\n for (const component of components) {\n if (component.bytes == null) {\n const codec = registry.getProtocol(component.code)\n const codecLength = varint.encodingLength(component.code)\n let valueBytes: Uint8Array | undefined\n let valueLength = 0\n let valueLengthLength = 0\n\n if (component.value != null) {\n valueBytes = codec.valueToBytes?.(component.value) ?? uint8ArrayFromString(component.value)\n valueLength = valueBytes.byteLength\n\n if (codec.size === V) {\n valueLengthLength = varint.encodingLength(valueLength)\n }\n }\n\n const bytes = new Uint8Array(codecLength + valueLengthLength + valueLength)\n\n // encode the protocol code\n let offset = 0\n varint.encodeUint8Array(component.code, bytes, offset)\n offset += codecLength\n\n // if there is a value\n if (valueBytes != null) {\n // if the value has variable length, encode the length\n if (codec.size === V) {\n varint.encodeUint8Array(valueLength, bytes, offset)\n offset += valueLengthLength\n }\n\n // finally encode the value\n bytes.set(valueBytes, offset)\n }\n\n component.bytes = bytes\n }\n\n bytes.push(component.bytes)\n length += component.bytes.byteLength\n }\n\n return uint8ArrayConcat(bytes, length)\n}\n\nexport function stringToComponents (string: string): Component[] {\n if (string.charAt(0) !== '/') {\n throw new InvalidMultiaddrError('String multiaddr must start with \"/\"')\n }\n\n const components: Component[] = []\n let collecting: 'protocol' | 'value' = 'protocol'\n let value = ''\n let protocol = ''\n\n for (let i = 1; i < string.length; i++) {\n const char = string.charAt(i)\n\n if (char !== '/') {\n if (collecting === 'protocol') {\n protocol += string.charAt(i)\n } else {\n value += string.charAt(i)\n }\n }\n\n const ended = i === string.length - 1\n\n if (char === '/' || ended) {\n const codec = registry.getProtocol(protocol)\n\n if (collecting === 'protocol') {\n if (codec.size == null || codec.size === 0) {\n // a protocol without an address, eg. `/tls`\n components.push({\n code: codec.code,\n name: codec.name\n })\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n\n continue\n } else if (ended) {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n // continue collecting value\n collecting = 'value'\n } else if (collecting === 'value') {\n const component: Component = {\n code: codec.code,\n name: codec.name\n }\n\n if (codec.size != null && codec.size !== 0) {\n if (value === '') {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n component.value = codec.stringToValue?.(value) ?? value\n }\n\n components.push(component)\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n }\n }\n }\n\n if (protocol !== '' && value !== '') {\n throw new InvalidMultiaddrError('Incomplete multiaddr')\n }\n\n return components\n}\n\nexport function componentsToString (components: Component[]): string {\n return `/${components.flatMap(component => {\n if (component.value == null) {\n return component.name\n }\n\n const codec = registry.getProtocol(component.code)\n\n if (codec == null) {\n throw new InvalidMultiaddrError(`Unknown protocol code ${component.code}`)\n }\n\n return [\n component.name,\n codec.valueToString?.(component.value) ?? component.value\n ]\n }).join('/')}`\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (codec: ProtocolCodec, bytes: Uint8Array, offset: number): number {\n if (codec.size == null || codec.size === 0) {\n return 0\n }\n\n if (codec.size > 0) {\n return codec.size / 8\n }\n\n return varint.decode(bytes, offset)\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { bytesToComponents, componentsToBytes, componentsToString, stringToComponents } from './components.js'\nimport { InvalidMultiaddrError, InvalidParametersError } from './errors.ts'\nimport { registry } from './registry.ts'\nimport { isMultiaddr } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, Component } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/multiaddr')\n\nfunction toComponents (addr: MultiaddrInput): Component[] {\n if (addr == null) {\n addr = '/'\n }\n\n if (isMultiaddr(addr)) {\n return addr.getComponents()\n }\n\n if (addr instanceof Uint8Array) {\n return bytesToComponents(addr)\n }\n\n if (typeof addr === 'string') {\n addr = addr\n .replace(/\\/(\\/)+/, '/')\n .replace(/(\\/)+$/, '')\n\n if (addr === '') {\n addr = '/'\n }\n\n return stringToComponents(addr)\n }\n\n if (Array.isArray(addr)) {\n return addr\n }\n\n throw new InvalidMultiaddrError('Must be a string, Uint8Array, Component[], or another Multiaddr')\n}\n\ninterface MultiaddrOptions {\n validate?: boolean\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n [symbol]: boolean = true\n readonly #components: Component[]\n\n // cache string representation\n #string: string | undefined\n // cache byte representation\n #bytes: Uint8Array | undefined\n\n constructor (addr: MultiaddrInput | Component[] = '/', options: MultiaddrOptions = {}) {\n this.#components = toComponents(addr)\n\n if (options.validate !== false) {\n validate(this)\n }\n }\n\n get bytes (): Uint8Array {\n if (this.#bytes == null) {\n this.#bytes = componentsToBytes(this.#components)\n }\n\n return this.#bytes\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = componentsToString(this.#components)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n getComponents (): Component[] {\n return [\n ...this.#components.map(c => ({ ...c }))\n ]\n }\n\n encapsulate (addr: MultiaddrInput): MultiaddrInterface {\n const ma = new Multiaddr(addr)\n\n return new Multiaddr([\n ...this.#components,\n ...ma.getComponents()\n ], {\n validate: false\n })\n }\n\n decapsulate (addr: Multiaddr | string): MultiaddrInterface {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n\n if (i < 0) {\n throw new InvalidParametersError(`Address ${this.toString()} does not contain subaddress: ${addrString}`)\n }\n\n return new Multiaddr(s.slice(0, i), {\n validate: false\n })\n }\n\n decapsulateCode (code: number): Multiaddr {\n let index\n\n for (let i = this.#components.length - 1; i > -1; i--) {\n if (this.#components[i].code === code) {\n index = i\n break\n }\n }\n\n return new Multiaddr(this.#components.slice(0, index), {\n validate: false\n })\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.toString()})`\n }\n}\n\n/**\n * Ensures all multiaddr tuples are correct. Throws if any invalid protocols or\n * values are encountered.\n */\nexport function validate (addr: Multiaddr): void {\n addr.getComponents()\n .forEach(component => {\n const codec = registry.getProtocol(component.code)\n\n if (component.value == null) {\n return\n }\n\n codec.validate?.(component.value)\n })\n}\n", "/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // <Uint8Array 04 7f 00 00 01 11 04 d2>\n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.getComponents()\n * // [\n * // { code: 4, name: 'ip4', value: '127.0.0.1' },\n * // { code: 273, name: 'udp', value: '1234' }\n * // ]\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * @example Adding custom protocols\n *\n * To add application-specific or experimental protocols, add a protocol codec\n * to the protocol registry:\n *\n * ```ts\n * import { registry, V, multiaddr } from '@multiformats/multiaddr'\n * import type { ProtocolCodec } from '@multiformats/multiaddr'\n *\n * const maWithCustomTuple = '/custom-protocol/hello'\n *\n * // throws UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * const protocol: ProtocolCodec = {\n * code: 2059,\n * name: 'custom-protocol',\n * size: V\n * // V means variable length, can also be 0, a positive integer (e.g. a fixed\n * // length or omitted\n * }\n *\n * registry.addProtocol(protocol)\n *\n * // does not throw UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * // protocols can also be removed\n * registry.removeProtocol(protocol.code)\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { registry, V } from './registry.ts'\nimport type { ProtocolCodec } from './registry.ts'\n\n/**\n * The protocol registry stores protocol codecs that allow transformation of\n * multiaddr tuples from bytes to string and back again, and also validation of\n * the address values.\n */\nexport interface Registry {\n /**\n * Retrieve a protocol definition by it's code or name\n */\n getProtocol (key: string | number): ProtocolCodec\n\n /**\n * Add a new protocol definition\n */\n addProtocol (codec: ProtocolCodec): void\n\n /**\n * Remove a protocol definition by it's code\n */\n removeProtocol (code: number): void\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null | Component[]\n\n/**\n * A Component is a section of a multiaddr with a name/code, possibly with a\n * value.\n *\n * Component names/codes are defined in the protocol table.\n *\n * @see https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n */\nexport interface Component {\n /**\n * The code of the component as defined in the protocol table\n */\n code: number\n\n /**\n * The name of the component as defined in the protocol table\n */\n name: string\n\n /**\n * The component value, if one is present\n */\n value?: string\n\n /**\n * The bytes that make up the component. This will be set if the multiaddr\n * was parsed from a `Uint8Array`, or if `.bytes` has been accessed on it.\n */\n bytes?: Uint8Array\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns the components that make up this Multiaddr\n *\n * @example\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').getComponents()\n * // [{ name: 'ip4', code: 4, value: '127.0.0.1' }, { name: 'tcp', code: 6, value: '4001' }]\n * ```\n */\n getComponents(): Component[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a specific\n * code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\n/**\n * Export all table.csv codes. These are all named exports so can be tree-shaken\n * out by bundlers.\n */\nexport * from './constants.ts'\nexport { registry, V }\nexport type { ProtocolCodec }\n", "import type { Matcher, MultiaddrMatcher } from './index.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * Matches a multiaddr component with the specified code but no value\n */\nexport const code = (code: number): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component == null) {\n return false\n }\n\n if (component.code !== code) {\n return false\n }\n\n if (component.value != null) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const value = (code: number, value?: string): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component?.code !== code) {\n return false\n }\n\n if (component.value == null) {\n return false\n }\n\n if (value != null && component.value !== value) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const not = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return false\n }\n }\n}\n\n/**\n * An optional matcher\n */\nexport const optional = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return result\n }\n }\n}\n\n/**\n * Matches any one of the passed matches\n */\nexport const or = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n let matches: Component[] | undefined\n\n for (const matcher of matchers) {\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n continue\n }\n\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result\n }\n }\n\n if (matches == null) {\n return false\n }\n\n return matches\n }\n }\n}\n\n/**\n * Matches all of the passed matchers\n */\nexport const and = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n return false\n }\n\n vals = result\n }\n\n return vals\n }\n }\n}\n\n/**\n * Create a multiaddr matcher from the passed component matchers\n */\nexport function fmt (...matchers: Matcher[]): MultiaddrMatcher {\n function match (ma?: Multiaddr): Component[] | false {\n if (ma == null) {\n return false\n }\n\n let parts = ma.getComponents()\n\n for (const matcher of matchers) {\n const result = matcher.match(parts)\n\n if (result === false) {\n return false\n }\n\n parts = result\n }\n\n return parts\n }\n\n function matches (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n return result !== false\n }\n\n function exactMatch (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n if (result === false) {\n return false\n }\n\n return result.length === 0\n }\n\n return {\n matchers,\n matches,\n exactMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\nimport { CODE_P2P, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_DNS, CODE_IP4, CODE_IP6, CODE_TCP, CODE_UDP, CODE_QUIC, CODE_QUIC_V1, CODE_WS, CODE_WSS, CODE_TLS, CODE_SNI, CODE_WEBRTC_DIRECT, CODE_CERTHASH, CODE_WEBTRANSPORT, CODE_P2P_CIRCUIT, CODE_WEBRTC, CODE_HTTP, CODE_UNIX, CODE_HTTPS, CODE_MEMORY, CODE_IP6ZONE, CODE_IPCIDR } from '@multiformats/multiaddr'\nimport { and, or, optional, fmt, code, value, not } from './utils.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * A matcher accepts multiaddr components and either fails to match and returns\n * false or returns a sublist of unmatched components\n */\nexport interface Matcher {\n match(parts: Component[]): Component[] | false\n}\n\n/**\n * A MultiaddrMatcher allows interpreting a multiaddr as a certain type of\n * multiaddr\n */\nexport interface MultiaddrMatcher {\n /**\n * The matchers that make up this MultiaddrMatcher - useful if you want to\n * make your own custom matchers\n */\n matchers: Matcher[]\n\n /**\n * Returns true if the passed multiaddr can be treated as this type of\n * multiaddr\n */\n matches(ma?: Multiaddr): boolean\n\n /**\n * Returns true if the passed multiaddr terminates as this type of\n * multiaddr\n */\n exactMatch(ma?: Multiaddr): boolean\n}\n\n/**\n * Matches PeerId addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { PEER_ID } from '@multiformats/multiaddr-matcher'\n *\n * PEER_ID.matches(multiaddr('/p2p/Qmfoo')) // true\n * PEER_ID.matches(multiaddr('/ipfs/Qmfoo')) // true\n * ```\n */\nconst _PEER_ID = value(CODE_P2P)\n\nexport const PEER_ID = fmt(_PEER_ID)\n\n/**\n * DNS matchers\n */\nconst _DNS4 = value(CODE_DNS4)\nconst _DNS6 = value(CODE_DNS6)\nconst _DNSADDR = value(CODE_DNSADDR)\nconst _DNS = value(CODE_DNS)\n\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(value(CODE_P2P)))\n\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(value(CODE_P2P)))\n\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(value(CODE_P2P)))\n\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))\n\nconst _IP4 = and(\n value(CODE_IP4),\n optional(value(CODE_IPCIDR))\n)\nconst _IP6 = and(\n optional(value(CODE_IP6ZONE)),\n value(CODE_IP6),\n optional(value(CODE_IPCIDR))\n)\nconst _IP = or(_IP4, _IP6)\n\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR)\n\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))))\n\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4)\n\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6)\n\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP)\n\nconst _TCP = and(_IP_OR_DOMAIN, value(CODE_TCP))\nconst _UDP = and(_IP_OR_DOMAIN, value(CODE_UDP))\n\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(value(CODE_P2P))))\n\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP)\n\nconst _QUIC = and(_UDP, code(CODE_QUIC), optional(value(CODE_P2P)))\nconst _QUIC_V1 = and(_UDP, code(CODE_QUIC_V1), optional(value(CODE_P2P)))\n\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUIC_V1)\n\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC)\n\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC_V1 } from '@multiformats/multiaddr-matcher'\n *\n * QUIC_V1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUIC_V1 = fmt(_QUIC_V1)\n\nconst _WEB = or(\n _IP_OR_DOMAIN,\n _TCP,\n _UDP,\n _QUIC,\n _QUIC_V1\n)\n\nconst _WebSockets = or(\n and(_WEB, code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets)\n\nconst _WebSocketsSecure = or(\n and(_WEB, code(CODE_WSS), optional(value(CODE_P2P))),\n and(_WEB, code(CODE_TLS), optional(value(CODE_SNI)), code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure)\n\nconst _WebRTCDirect = and(_UDP, code(CODE_WEBRTC_DIRECT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect)\n\nconst _WebTransport = and(_QUIC_V1, code(CODE_WEBTRANSPORT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport)\n\nconst _P2P = or(\n _WebSockets,\n _WebSocketsSecure,\n and(_TCP, optional(value(CODE_P2P))),\n and(QUIC_V0_OR_V1, optional(value(CODE_P2P))),\n and(_IP_OR_DOMAIN, optional(value(CODE_P2P))),\n _WebRTCDirect,\n _WebTransport,\n value(CODE_P2P)\n)\n\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P)\n\nconst _Circuit = and(optional(_P2P), code(CODE_P2P_CIRCUIT), not(code(CODE_WEBRTC)), optional(value(CODE_P2P)))\n\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit)\n\nconst _WebRTC = or(\n and(_P2P, code(CODE_P2P_CIRCUIT), code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(_P2P, code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(code(CODE_WEBRTC), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC)\n\nconst _HTTP = or(\n and(_IP_OR_DOMAIN, value(CODE_TCP), code(CODE_HTTP), optional(value(CODE_P2P))),\n and(_IP_OR_DOMAIN, code(CODE_HTTP), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP)\n\nconst _HTTPS = and(_IP_OR_DOMAIN, or(\n and(value(CODE_TCP, '443'), code(CODE_HTTP)),\n and(value(CODE_TCP), code(CODE_HTTPS)),\n and(value(CODE_TCP), code(CODE_TLS), code(CODE_HTTP)),\n and(code(CODE_TLS), code(CODE_HTTP)),\n code(CODE_TLS),\n code(CODE_HTTPS)\n),\noptional(value(CODE_P2P))\n)\n\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS)\n\nconst _Memory = or(\n and(value(CODE_MEMORY), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nexport const Memory = fmt(_Memory)\n\nconst _Unix = or(\n and(value(CODE_UNIX), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Unix addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Unix } from '@multiformats/multiaddr-matcher'\n *\n * Unix.matches(multiaddr('/unix/%2Fpath%2Fto%2Funix.socket')) // true\n * ```\n */\nexport const Unix = fmt(_Unix)\n"],
|
|
5
|
-
"mappings": ";idAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,eAAAE,KCyCM,IAAOC,GAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GAMWC,GAAP,cAAqC,KAAK,CAC9C,OAAO,KAAO,wBAEd,YAAaD,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,uBACd,GAkKI,IAAOE,GAAP,cAA+B,KAAK,CACxC,OAAO,KAAO,kBAEd,YAAaC,EAAU,cAAa,CAClC,MAAMA,CAAO,EACb,KAAK,KAAO,iBACd,GAMWC,GAAP,cAAqC,KAAK,CAC9C,OAAO,KAAO,wBAEd,YAAaD,EAAU,oBAAmB,CACxC,MAAMA,CAAO,EACb,KAAK,KAAO,uBACd,GA8II,IAAOE,GAAP,cAAuC,KAAK,CAChD,OAAO,KAAO,0BAEd,YAAaC,EAAU,uBAAsB,CAC3C,MAAMA,CAAO,EACb,KAAK,KAAO,yBACd,GC7WK,IAAMC,GAAsB,OAAO,IAAI,wBAAwB,ECqI/D,IAAMC,GAAe,OAAO,IAAI,iBAAiB,EC9DlD,IAAOC,GAAP,cAAuE,WAAW,CAC7EC,GAAa,IAAI,IAE1B,aAAA,CACE,MAAK,CAKP,CAEA,cAAeC,EAAY,CACzB,IAAMC,EAAY,KAAKF,GAAW,IAAIC,CAAI,EAE1C,OAAIC,GAAa,KACR,EAGFA,EAAU,MACnB,CAGA,iBAAkBD,EAAcE,EAA+BC,EAA2C,CACxG,MAAM,iBAAiBH,EAAME,EAAUC,CAAO,EAE9C,IAAIC,EAAO,KAAKL,GAAW,IAAIC,CAAI,EAE/BI,GAAQ,OACVA,EAAO,CAAA,EACP,K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AS,IAIlB,KAAK,IAAI,mEAAoE,KAAK,OAAO,EACzF,KAAK,MAAQ,WAAW,IAAK,CACtB,KAAK,wBAAuB,EAC9B,MAAMC,GAAM,CACX,KAAK,IAAI,MAAM,0CAA2CA,CAAG,CAC/D,CAAC,CACL,EAAG,KAAK,OAAO,EACjB,CAKA,MAAM,yBAAuB,CAC3B,GAAI,KAAK,OAAS,KAIlB,QAAWC,KAAY,KAAK,KAAM,CAYhC,GAXA,MAAM,KAAK,WAAW,UAAU,MAAMA,EAAS,GAAI,CACjD,KAAM,CACJ,CAAC,KAAK,MAAM,SAAWhB,EAA0B,EAAG,CAClD,MAAO,KAAK,MAAM,UAAYC,GAC9B,IAAK,KAAK,MAAM,SAGpB,WAAYe,EAAS,WACtB,EAGG,KAAK,OAAS,KAChB,OAGF,KAAK,kBAAkB,OAAQ,CAAE,OAAQA,CAAQ,CAAE,EACnD,KAAK,WAAW,kBAAkB,eAAeA,EAAS,EAAE,EACzD,MAAMD,GAAM,CACX,KAAK,IAAI,MAAM,wCAAyCC,EAAS,GAAID,CAAG,CAC1E,CAAC,CACL,CACF,CAKA,MAAI,CACE,KAAK,OAAS,MAChB,aAAa,KAAK,KAAK,EAGzB,KAAK,MAAQ,MACf,GAGI,SAAUE,GAAWC,EAAmB,CAC5C,OAAQb,GAAoC,IAAIF,GAAUE,EAAYa,CAAI,CAC5E",
|
|
6
|
-
"names": ["index_exports", "__export", "bootstrap", "InvalidParametersError", "message", "InvalidPublicKeyError", "InvalidCIDError", "message", "InvalidMultihashError", "UnsupportedKeyTypeError", "message", "peerDiscoverySymbol", "peerIdSymbol", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "options", "list", "callback", "event", "result", "once", "detail", "serviceCapabilities", "serviceDependencies", "base58_exports", "__export", "base58btc", "base58flickr", "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", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "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", "options", "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", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "sha2_browser_exports", "__export", "sha256", "sha512", "DEFAULT_MIN_DIGEST_LENGTH", "from", "name", "code", "encode", "minDigestLength", "maxDigestLength", "Hasher", "input", "options", "result", "createDigest", "digest", "truncate", "create", "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", "i", "entries", "result", "start", "end", "vals", "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", "options", "publicKey", "result", "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", "options", "hashAndVerify", "isBytes", "a", "anumber", "n", "title", "prefix", "abytes", "value", "length", "bytes", "len", "needsLen", "ofLen", "got", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "createHasher", "hashCons", "info", "hashC", "msg", "opts", "tmp", "randomBytes", "bytesLength", "cr", "oidNist", "suffix", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "createView", "data", "aexists", "abytes", "view", "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", "i", "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", "SHA2_32B", "HashMD", "outputLen", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "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", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "_0n", "_1n", "abool", "value", "title", "prefix", "abignumber", "n", "isPosBig", "anumber", "numberToHexUnpadded", "num", "hex", "abignumber", "hexToNumber", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "copyBytes", "abytes", "numberToBytesBE", "n", "len", "anumber", "res", "hexToBytes", "numberToBytesLE", "copyBytes", "bytes", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "anumber", "u8n", "len", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "i", "reset", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "iter", "f", "memoized", "fn", "map", "arg", "args", "val", "computed", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_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", "assertIsSquare", "Fp", "root", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "i", "t_tmp", "exponent", "FpSqrt", "_9n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_nBitLength", "nByteLength", "_Field", "_0n", "_1n", "ORDER", "opts", "_nbitLength", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "abytes", "allowedLengths", "BYTES", "isLE", "modFromBytes", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "condition", "Field", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "n", "_0n", "wNAF", "Point", "bits", "elm", "p", "d", "_1n", "point", "W", "windows", "windowSize", "calcWOpts", "points", "base", "window", "i", "precomputes", "f", "wo", "nextN", "offset", "isZero", "isNeg", "isNegF", "offsetF", "calcOffsets", "negateCt", "acc", "item", "transform", "comp", "scalar", "prev", "validateW", "mulEndoUnsafe", "k1", "k2", "p1", "p2", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "validated", "createCurveFields", "Fn", "cofactor", "validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aedpoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "a", "d", "T", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "bytes", "zip215", "len", "copyBytes", "abytes", "abool", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "hex", "hexToBytes", "windowSize", "isLazy", "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", "normalizeZ", "acc", "invertedZ", "bytesToHex", "wNAF", "eddsa", "Point", "cHash", "eddsaOpts", "validateObject", "prehash", "BASE", "Fp", "Fn", "randomBytes", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "modN_LE", "hash", "bytesToNumberLE", "getPrivateScalar", "key", "len", "lengths", "abytes", "hashed", "head", "prefix", "scalar", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "zip215", "mid", "A", "SB", "_size", "randomSecretKey", "seed", "isValidSecretKey", "isBytes", "isValidPublicKey", "utils", "y", "size", "is25519", "u", "_1n", "createKeygen", "_1n", "_2n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "_2n", "b5", "_1n", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "ed25519_Point", "edwards", "ed", "opts", "eddsa", "ed25519_Point", "sha512", "adjustScalarBytes", "ed25519", "VerificationError", "message", "WebCryptoMissingError", "webcrypto_browser_default", "win", "nativeCrypto", "WebCryptoMissingError", "webcrypto_default", "webcrypto_browser_default", "PUBLIC_KEY_BYTE_LENGTH", "ed25519Supported", "webCryptoEd25519SupportedPromise", "webcrypto_default", "hashAndVerifyWebCrypto", "publicKey", "sig", "msg", "key", "webcrypto_default", "hashAndVerifyNoble", "ed25519", "hashAndVerify", "ed25519Supported", "webCryptoEd25519SupportedPromise", "isPromise", "thing", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "result", "hashAndVerify", "isPromise", "res", "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", "decodeUint8ArrayList", "decode", "buf", "offset", "decodeUint8Array", "decodeUint8ArrayList", "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", "streamMessage", "buf", "codec", "opts", "reader", "createReader", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "stream", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "stream", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "stream", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "PrivateKey", "_HMAC", "hash", "key", "ahash", "abytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "_0n", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "optsn", "optName", "abool", "DERErr", "m", "DER", "tag", "data", "E", "dataLen", "len", "numberToHexUnpadded", "lenLen", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "abytes", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "validateObject", "endo", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "comp", "uncomp", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "toAffineMemo", "memoized", "p", "iz", "X", "Y", "Z", "is0", "zz", "assertValidMemo", "finishEndo", "endoBeta", "k1p", "k2p", "negateCt", "P", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "a", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "fake", "mul", "normalizeZ", "k1f", "k2f", "f", "sc", "p1", "p2", "mulEndoUnsafe", "invertedZ", "isTorsionFree", "clearCofactor", "bytesToHex", "bits", "wNAF", "getWLengths", "Fp", "Fn", "ecdh", "Point", "ecdhOpts", "randomBytes_", "randomBytes", "lengths", "getMinHashLength", "isValidSecretKey", "secretKey", "num", "isValidPublicKey", "publicKey", "isCompressed", "comp", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "abytes", "getPublicKey", "isProbPub", "item", "isBytes", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "ahash", "validateObject", "hmac", "key", "msg", "CURVE_ORDER", "fnBits", "defaultSigOpts", "hasLargeCofactor", "_2n", "isBiggerThanHalfOrder", "number", "HALF", "_1n", "validateRS", "title", "assertSmallCofactor", "validateSigLength", "bytes", "format", "validateSigFormat", "size", "sizer", "Signature", "r", "recovery", "recid", "DER", "L", "hex", "hexToBytes", "messageHash", "radj", "x", "R", "concatBytes", "pprefix", "ir", "h", "bits2int_modN", "u1", "u2", "Q", "rb", "sb", "bytesToHex", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "bitMask", "int2octets", "aInRange", "_0n", "validateMsgAndHash", "message", "prehash", "prepSig", "opts", "lowS", "extraEntropy", "validateSigOpts", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "k", "ik", "q", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "P", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "hashAndVerify", "key", "sig", "msg", "options", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "hashAndVerify", "unmarshalSecp256k1PublicKey", "bytes", "Secp256k1PublicKey", "compressSecp256k1PublicKey", "key", "secp256k1", "validateSecp256k1PublicKey", "key", "secp256k1", "err", "InvalidPublicKeyError", "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", "InvalidMultiaddrError", "ValidationError", "InvalidParametersError", "UnknownProtocolError", "Parser", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "input", "MAX_IPV6_LENGTH", "parser", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "bytesToString", "base", "buf", "toString", "stringToBytes", "fromString", "bytes2port", "port2bytes", "port", "onion2bytes", "str", "addr", "portBuf", "concat", "onion32bytes", "base32", "bytes2onion", "addrBytes", "portBytes", "ip4ToBytes", "ip", "bytes", "byte", "index", "value", "InvalidMultiaddrError", "ip6ToBytes", "offset", "sections", "i", "isv4", "isIPv4", "v4Buffer", "argv", "word", "ip4ToString", "result", "ip6ToString", "byte1", "byte2", "tuple", "url", "ip6StringToValue", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "mb2bytes", "mbstr", "bytes2mb", "integer", "value", "ValidationError", "positive", "maxValue", "max", "validate", "funcs", "fn", "validatePort", "V", "Registry", "key", "codec", "UnknownProtocolError", "alias", "code", "registry", "codecs", "ip4ToBytes", "ip4ToString", "value", "isIPv4", "ValidationError", "port2bytes", "bytes2port", "validatePort", "ip6ToBytes", "ip6ToString", "ip6StringToValue", "isIPv6", "bytesToString", "stringToBytes", "str", "val", "CID", "bytes2onion", "onion2bytes", "onion32bytes", "bytes2mb", "base64url", "mb2bytes", "bytesToComponents", "bytes", "components", "i", "code", "decode", "codec", "registry", "codeLength", "encodingLength", "size", "sizeForAddr", "sizeLength", "V", "componentLength", "component", "valueOffset", "valueBytes", "toString", "componentsToBytes", "length", "codecLength", "valueLength", "valueLengthLength", "fromString", "offset", "encodeUint8Array", "concat", "stringToComponents", "string", "InvalidMultiaddrError", "collecting", "value", "protocol", "char", "ended", "componentsToString", "inspect", "symbol", "toComponents", "addr", "isMultiaddr", "bytesToComponents", "stringToComponents", "InvalidMultiaddrError", "Multiaddr", "_Multiaddr", "#components", "#string", "#bytes", "options", "validate", "componentsToBytes", "componentsToString", "c", "ma", "addrString", "s", "i", "InvalidParametersError", "code", "index", "equals", "component", "codec", "registry", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "code", "vals", "component", "value", "not", "matcher", "optional", "result", "or", "matchers", "matches", "and", "fmt", "match", "ma", "parts", "exactMatch", "_PEER_ID", "value", "PEER_ID", "fmt", "_DNS4", "_DNS6", "_DNSADDR", "_DNS", "DNS4", "optional", "DNS6", "DNSADDR", "DNS", "or", "_IP4", "and", "_IP6", "_IP", "_IP_OR_DOMAIN", "IP_OR_DOMAIN", "IP4", "IP6", "IP", "_TCP", "_UDP", "TCP", "UDP", "_QUIC", "code", "_QUIC_V1", "QUIC_V0_OR_V1", "QUIC", "QUIC_V1", "_WEB", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "_WebRTCDirect", "WebRTCDirect", "_WebTransport", "WebTransport", "_P2P", "P2P", "_Circuit", "not", "Circuit", "_WebRTC", "WebRTC", "_HTTP", "HTTP", "_HTTPS", "HTTPS", "_Memory", "Memory", "_Unix", "Unix", "DEFAULT_BOOTSTRAP_TAG_NAME", "DEFAULT_BOOTSTRAP_TAG_VALUE", "DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT", "Bootstrap", "TypedEventEmitter", "components", "options", "str", "multiaddr", "ma", "P2P", "c", "peerIdFromString", "peerDiscoverySymbol", "serviceCapabilities", "err", "peerData", "bootstrap", "init"]
|
|
3
|
+
"sources": ["../src/index.ts", "../../interface/src/errors.ts", "../../interface/src/peer-discovery.ts", "../../interface/src/peer-id.ts", "../../../node_modules/main-event/src/index.ts", "../../interface/src/index.ts", "../../../node_modules/multiformats/src/bases/base58.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/base32.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/base64.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", "../../crypto/src/keys/rsa/der.ts", "../../crypto/src/keys/ecdsa/index.ts", "../../crypto/src/keys/ecdsa/utils.ts", "../../crypto/src/keys/ecdsa/ecdsa.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/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/abstract/hash-to-curve.ts", "../../../node_modules/@noble/curves/src/ed25519.ts", "../../crypto/src/errors.ts", "../../crypto/src/webcrypto/webcrypto.browser.ts", "../../crypto/src/webcrypto/index.ts", "../../crypto/src/keys/ed25519/index.browser.ts", "../../crypto/src/util.ts", "../../crypto/src/keys/ed25519/ed25519.ts", "../../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/stream.ts", "../../../node_modules/protons-runtime/src/codec.ts", "../../../node_modules/protons-runtime/src/codecs/enum.ts", "../../../node_modules/protons-runtime/src/codecs/message.ts", "../../crypto/src/keys/keys.ts", "../../../node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/@noble/curves/src/secp256k1.ts", "../../crypto/src/keys/secp256k1/index.browser.ts", "../../crypto/src/keys/secp256k1/secp256k1.ts", "../../crypto/src/keys/secp256k1/utils.ts", "../../crypto/src/keys/index.ts", "../../peer-id/src/peer-id.ts", "../../peer-id/src/index.ts", "../../../node_modules/@multiformats/multiaddr/src/errors.ts", "../../../node_modules/@chainsafe/is-ip/src/parser.ts", "../../../node_modules/@chainsafe/is-ip/src/parse.ts", "../../../node_modules/@chainsafe/is-ip/src/is-ip.ts", "../../../node_modules/@multiformats/multiaddr/src/utils.ts", "../../../node_modules/@multiformats/multiaddr/src/validation.ts", "../../../node_modules/@multiformats/multiaddr/src/registry.ts", "../../../node_modules/@multiformats/multiaddr/src/components.ts", "../../../node_modules/@multiformats/multiaddr/src/multiaddr.ts", "../../../node_modules/@multiformats/multiaddr/src/index.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/utils.ts", "../../../node_modules/@multiformats/multiaddr-matcher/src/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\n\nimport { peerDiscoverySymbol, serviceCapabilities } from '@libp2p/interface'\nimport { peerIdFromString } from '@libp2p/peer-id'\nimport { CODE_P2P, multiaddr } from '@multiformats/multiaddr'\nimport { P2P } from '@multiformats/multiaddr-matcher'\nimport { TypedEventEmitter } from 'main-event'\nimport type { ComponentLogger, Logger, PeerDiscovery, PeerDiscoveryEvents, PeerInfo, PeerStore, Startable } from '@libp2p/interface'\nimport type { ConnectionManager } from '@libp2p/interface-internal'\n\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap'\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000\n\nexport interface BootstrapInit {\n /**\n * The list of peer addresses in multi-address format\n */\n list: string[]\n\n /**\n * How long to wait before discovering bootstrap nodes\n */\n timeout?: number\n\n /**\n * Tag a bootstrap peer with this name before \"discovering\" it\n *\n * @default 'bootstrap'\n */\n tagName?: string\n\n /**\n * The bootstrap peer tag will have this value\n *\n * @default 50\n */\n tagValue?: number\n\n /**\n * Cause the bootstrap peer tag to be removed after this number of ms\n */\n tagTTL?: number\n}\n\nexport interface BootstrapComponents {\n peerStore: PeerStore\n logger: ComponentLogger\n connectionManager: ConnectionManager\n}\n\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter<PeerDiscoveryEvents> implements PeerDiscovery, Startable {\n static tag = 'bootstrap'\n\n private readonly log: Logger\n private timer?: ReturnType<typeof setTimeout>\n private readonly list: PeerInfo[]\n private readonly timeout: number\n private readonly components: BootstrapComponents\n private readonly _init: BootstrapInit\n\n constructor (components: BootstrapComponents, options: BootstrapInit = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses')\n }\n super()\n\n this.components = components\n this.log = components.logger.forComponent('libp2p:bootstrap')\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT\n this.list = options.list\n .map(str => multiaddr(str))\n .filter(ma => {\n if (!P2P.matches(ma)) {\n this.log.error('invalid multiaddr %a', ma)\n return false\n }\n\n const peerIdStr = ma.getComponents().findLast(c => c.code === CODE_P2P)?.value\n\n if (peerIdStr == null) {\n this.log.error('invalid bootstrap multiaddr without peer id')\n return false\n }\n\n return true\n })\n .map(ma => {\n return {\n id: peerIdFromString(ma.getComponents().findLast(c => c.code === CODE_P2P)?.value ?? ''),\n multiaddrs: [ma]\n }\n })\n\n this._init = options\n }\n\n readonly [peerDiscoverySymbol] = this\n\n readonly [Symbol.toStringTag] = '@libp2p/bootstrap'\n\n readonly [serviceCapabilities]: string[] = [\n '@libp2p/peer-discovery'\n ]\n\n isStarted (): boolean {\n return Boolean(this.timer)\n }\n\n /**\n * Start emitting events\n */\n start (): void {\n if (this.isStarted()) {\n return\n }\n\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout)\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error('failed to discover bootstrap peers - %e', err)\n })\n }, this.timeout)\n }\n\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers (): Promise<void> {\n if (this.timer == null) {\n return\n }\n\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL\n }\n },\n multiaddrs: peerData.multiaddrs\n })\n\n // check we are still running\n if (this.timer == null) {\n return\n }\n\n this.safeDispatchEvent('peer', { detail: peerData })\n this.components.connectionManager.openConnection(peerData.id)\n .catch(err => {\n this.log.error('could not dial bootstrap peer %p - %e', peerData.id, err)\n })\n }\n }\n\n /**\n * Stop emitting events\n */\n stop (): void {\n if (this.timer != null) {\n clearTimeout(this.timer)\n }\n\n this.timer = undefined\n }\n}\n\nexport function bootstrap (init: BootstrapInit): (components: BootstrapComponents) => PeerDiscovery {\n return (components: BootstrapComponents) => new Bootstrap(components, init)\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 protocol stream is aborted locally\n */\nexport class StreamAbortedError extends Error {\n static name = 'StreamAbortedError'\n\n constructor (message = 'The stream has been aborted') {\n super(message)\n this.name = 'StreamAbortedError'\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 stream buffer is full\n */\nexport class StreamBufferError extends Error {\n static name = 'StreamBufferError'\n\n constructor (message = 'The stream buffer was full') {\n super(message)\n this.name = 'StreamBufferError'\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 an 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\n/**\n * Thrown when an operation has not been implemented\n */\nexport class NotImplementedError extends Error {\n static name = 'NotImplementedError'\n\n constructor (message = 'Not implemented') {\n super(message)\n this.name = 'NotImplementedError'\n }\n}\n", "import type { PeerInfo } from './peer-info.js'\nimport type { TypedEventTarget } from 'main-event'\n\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery')\n\n/**\n * Implementers of this interface can provide a PeerDiscovery implementation to\n * interested callers.\n */\nexport interface PeerDiscoveryProvider {\n [peerDiscoverySymbol]: PeerDiscovery\n}\n\nexport interface PeerDiscoveryEvents {\n peer: CustomEvent<PeerInfo>\n}\n\n/**\n * A class that implements the `PeerDiscovery` interface uses an\n * implementation-specific method to discover peers. These peers are then added\n * to the peer store for use by other system components and services.\n */\nexport interface PeerDiscovery extends TypedEventTarget<PeerDiscoveryEvents> {}\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 * @packageDocumentation\n *\n * Adds types to the EventTarget class.\n *\n * Hopefully this won't be necessary\n * forever:\n *\n * - https://github.com/microsoft/TypeScript/issues/28357\n * - https://github.com/microsoft/TypeScript/issues/43477\n * - https://github.com/microsoft/TypeScript/issues/299\n * - https://www.npmjs.com/package/typed-events\n * - https://www.npmjs.com/package/typed-event-emitter\n * - https://www.npmjs.com/package/typed-event-target\n * - etc\n *\n * In addition to types, a `safeDispatchEvent` method is available which\n * prevents dispatching events that aren't in the event map, and a\n * `listenerCount` method which reports the number of listeners that are\n * currently registered for a given event.\n *\n * @example\n *\n * ```ts\n * import { TypedEventEmitter } from 'main-event'\n * import type { TypedEventTarget } from 'main-event'\n *\n * interface EventTypes {\n * 'test': CustomEvent<string>\n * }\n *\n * const target = new TypedEventEmitter<EventTypes>()\n *\n * // it's a regular EventTarget\n * console.info(target instanceof EventTarget) // true\n *\n * // register listeners normally\n * target.addEventListener('test', (evt) => {\n * // evt is CustomEvent<string>\n * })\n *\n * // @ts-expect-error 'derp' is not in the event map\n * target.addEventListener('derp', () => {})\n *\n * // use normal dispatchEvent method\n * target.dispatchEvent(new CustomEvent('test', {\n * detail: 'hello'\n * }))\n *\n * // use type safe dispatch method\n * target.safeDispatchEvent('test', {\n * detail: 'world'\n * })\n *\n * // report listener count\n * console.info(target.listenerCount('test')) // 0\n *\n * // event emitters can be used purely as interfaces too\n * function acceptTarget (target: TypedEventTarget<EventTypes>) {\n * // ...\n * }\n * ```\n */\n\nimport { setMaxListeners } from './events.ts'\n\nexport interface EventCallback<EventType> { (evt: EventType): void }\nexport interface EventObject<EventType> { handleEvent: EventCallback<EventType> }\nexport type EventHandler<EventType> = EventCallback<EventType> | EventObject<EventType>\n\ninterface Listener {\n once: boolean\n callback: any\n}\n\n/**\n *\n */\nexport interface TypedEventTarget <EventMap extends Record<string, any>> extends EventTarget {\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n\n listenerCount (type: string): number\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail?: CustomEventInit<Detail>): boolean\n}\n\nfunction isEventObject <EventType> (obj?: any): obj is EventObject<EventType> {\n return typeof obj?.handleEvent === 'function'\n}\n\nfunction isOnce (options?: boolean | AddEventListenerOptions): boolean {\n return (options !== true && options !== false && options?.once) ?? false\n}\n\n/**\n * An implementation of a typed event target\n */\nexport class TypedEventEmitter<EventMap extends Record<string, any>> extends EventTarget implements TypedEventTarget<EventMap> {\n readonly #listeners = new Map<any, Listener[]>()\n\n constructor () {\n super()\n\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this)\n }\n\n listenerCount (type: string): number {\n const listeners = this.#listeners.get(type)\n\n if (listeners == null) {\n return 0\n }\n\n return listeners.length\n }\n\n addEventListener<K extends keyof EventMap>(type: K, listener: EventHandler<EventMap[K]> | null, options?: boolean | AddEventListenerOptions): void\n addEventListener (type: string, listener: EventHandler<Event>, options?: boolean | AddEventListenerOptions): void {\n const once = isOnce(options)\n\n super.addEventListener(type, (evt) => {\n if (once) {\n let list = this.#listeners.get(evt.type)\n\n if (list != null) {\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(evt.type, list)\n }\n }\n\n if (isEventObject<Event>(listener)) {\n listener.handleEvent(evt)\n } else {\n listener(evt)\n }\n }, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n list = []\n this.#listeners.set(type, list)\n }\n\n list.push({\n callback: listener,\n once\n })\n }\n\n removeEventListener<K extends keyof EventMap>(type: K, listener?: EventHandler<EventMap[K]> | null, options?: boolean | EventListenerOptions): void\n removeEventListener (type: string, listener?: EventHandler<Event>, options?: boolean | EventListenerOptions): void {\n super.removeEventListener(type.toString(), listener ?? null, options)\n\n let list = this.#listeners.get(type)\n\n if (list == null) {\n return\n }\n\n list = list.filter(({ callback }) => callback !== listener)\n this.#listeners.set(type, list)\n }\n\n safeDispatchEvent<Detail>(type: keyof EventMap, detail: CustomEventInit<Detail> = {}): boolean {\n return this.dispatchEvent(new CustomEvent<Detail>(type as string, detail))\n }\n}\n\nexport { setMaxListeners }\n", "/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n\nimport type { Connection, NewStreamOptions, NewStreamProgressEvents } from './connection.js'\nimport type { ContentRouting } from './content-routing.js'\nimport type { Ed25519PublicKey, PublicKey, RSAPublicKey, Secp256k1PublicKey } from './keys.js'\nimport type { Metrics } from './metrics.js'\nimport type { Ed25519PeerId, PeerId, RSAPeerId, Secp256k1PeerId, URLPeerId } from './peer-id.js'\nimport type { PeerInfo } from './peer-info.js'\nimport type { PeerRouting } from './peer-routing.js'\nimport type { Address, Peer, PeerStore } from './peer-store.js'\nimport type { Startable } from './startable.js'\nimport type { StreamHandler, StreamHandlerOptions, StreamMiddleware } from './stream-handler.js'\nimport type { Stream } from './stream.js'\nimport type { Topology } from './topology.js'\nimport type { Listener, OutboundConnectionUpgradeEvents } from './transport.js'\nimport type { DNS } from '@multiformats/dns'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { TypedEventTarget } from 'main-event'\nimport type { ProgressOptions, ProgressEvent } from 'progress-events'\n\n/**\n * Used by the connection manager to sort addresses into order before dialling\n */\nexport interface AddressSorter {\n (a: Address, b: Address): -1 | 0 | 1\n}\n\n/**\n * Event detail emitted when peer data changes\n */\nexport interface PeerUpdate {\n peer: Peer\n previous?: Peer\n}\n\n/**\n * Peer data signed by the remote Peer's public key\n */\nexport interface SignedPeerRecord {\n addresses: Multiaddr[]\n seq: bigint\n}\n\n/**\n * Things that libp2p can dial\n */\nexport type DialTarget = PeerId | Multiaddr | Multiaddr[]\n\n/**\n * A certificate that can be used to secure connections\n */\nexport interface TLSCertificate {\n /**\n * The private key that corresponds to the certificate in PEM format\n */\n key: string\n\n /**\n * The certificate chain in PEM format\n */\n cert: string\n}\n\n/**\n * Data returned from a successful identify response\n */\nexport interface IdentifyResult {\n /**\n * The remote Peer's PeerId\n */\n peerId: PeerId\n\n /**\n * The unsigned addresses they are listening on. Note - any multiaddrs present\n * in the signed peer record should be preferred to the value here.\n */\n listenAddrs: Multiaddr[]\n\n /**\n * The protocols the remote peer supports\n */\n protocols: string[]\n\n /**\n * The remote protocol version\n */\n protocolVersion?: string\n\n /**\n * The remote agent version\n */\n agentVersion?: string\n\n /**\n * The public key part of the remote PeerId - this is only useful for older\n * RSA-based PeerIds, the more modern Ed25519 and secp256k1 types have the\n * public key embedded in them\n */\n publicKey?: Uint8Array\n\n /**\n * If set this is the address that the remote peer saw the identify request\n * originate from\n */\n observedAddr?: Multiaddr\n\n /**\n * If sent by the remote peer this is the deserialized signed peer record\n */\n signedPeerRecord?: SignedPeerRecord\n\n /**\n * The connection that the identify protocol ran over\n */\n connection: Connection\n}\n\n/**\n * Logger component for libp2p\n */\nexport interface Logger {\n /**\n * Log a message\n */\n (formatter: any, ...args: any[]): void\n\n /**\n * Log an error message\n */\n error(formatter: any, ...args: any[]): void\n\n /**\n * Log a trace message\n */\n trace(formatter: any, ...args: any[]): void\n\n /**\n * `true` if this logger is enabled\n */\n enabled: boolean\n\n /**\n * Create a logger scoped below this one\n *\n * @example\n *\n * ```ts\n * import { defaultLogger } from '@libp2p/logger'\n *\n * const log = defaultLogger().forComponent('foo')\n *\n * log('hello')\n * // foo hello\n *\n * const subLog = log.newScope('bar')\n *\n * subLog('hello')\n * // foo:bar hello\n * ```\n */\n newScope(name: string): Logger\n}\n\n/**\n * Peer logger component for libp2p. This can be used to create loggers that are\n * scoped to individual system components or services.\n *\n * To see logs, run your app with `DEBUG` set as an env var or for browsers, in\n * `localStorage`:\n *\n * ```console\n * $ DEBUG=libp2p* node index.js\n * libp2p:my-service hello +0ms\n * ```\n */\nexport interface ComponentLogger {\n /**\n * Returns a logger for the specified component.\n *\n * @example\n *\n * ```TypeScript\n * import { ComponentLogger, Logger } from '@libp2p/interface'\n *\n * interface MyServiceComponents {\n * logger: ComponentLogger\n * }\n *\n * class MyService {\n * private readonly log: Logger\n *\n * constructor (components) {\n * this.log = components.logger.forComponent('libp2p:my-service')\n *\n * this.log('hello')\n * // logs:\n * // libp2p:my-service hello +0ms\n * }\n * }\n * ```\n */\n forComponent(name: string): Logger\n}\n\nexport interface MultiaddrResolveOptions extends AbortOptions, LoggerOptions {\n /**\n * An optional DNS resolver\n */\n dns?: DNS\n}\n\n/**\n * `MultiaddrResolver`s perform resolution of multiaddr components that require\n * translation by external systems (for example DNSADDR to TXT records).\n */\nexport interface MultiaddrResolver {\n /**\n * Returns true if this resolver can resolve components of this multiaddr\n */\n canResolve (address: Multiaddr): boolean\n\n /**\n * Returns one or more multiaddrs with components resolved to other values\n */\n resolve (address: Multiaddr, options: MultiaddrResolveOptions): Promise<Multiaddr[]>\n}\n\n/**\n * Once you have a libp2p instance, you can listen to several events it emits,\n * so that you can be notified of relevant network events.\n *\n * Event names are `noun:verb` so the first part is the name of the object\n * being acted on and the second is the action.\n */\nexport interface Libp2pEvents<T extends ServiceMap = ServiceMap> {\n /**\n * This event is dispatched when a new network peer is discovered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:discovery', (event) => {\n * const peerInfo = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:discovery': CustomEvent<PeerInfo>\n\n /**\n * This event will be triggered any time a new peer connects.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:connect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:connect': CustomEvent<PeerId>\n\n /**\n * This event will be triggered any time we are disconnected from another\n * peer, regardless of the circumstances of that disconnection. If we happen\n * to have multiple connections to a peer, this event will **only** be\n * triggered when the last connection is closed.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:disconnect', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:disconnect': CustomEvent<PeerId>\n\n /**\n * When a peer tagged with `keep-alive` disconnects, we will make multiple\n * attempts to reconnect to it with a backoff factor (see the connection\n * manager settings for details). If these all fail, the `keep-alive` tag will\n * be removed and this event will be emitted.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:reconnect-failure', (event) => {\n * const peerId = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:reconnect-failure': CustomEvent<PeerId>\n\n /**\n * This event is dispatched after a remote peer has successfully responded to\n * the identify protocol. Note that for this to be emitted, both peers must\n * have an identify service configured.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('peer:identify', (event) => {\n * const identifyResult = event.detail\n * // ...\n * })\n * ```\n */\n 'peer:identify': CustomEvent<IdentifyResult>\n\n /**\n * This event is dispatched when the peer store data for a peer has been\n * updated - e.g. their multiaddrs, protocols etc have changed.\n *\n * If they were previously known to this node, the old peer data will be\n * set in the `previous` field.\n *\n * This may be in response to the identify protocol running, a manual\n * update or some other event.\n */\n 'peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when the current node's peer record changes -\n * for example a transport started listening on a new address or a new\n * protocol handler was registered.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.addEventListener('self:peer:update', (event) => {\n * const { peer } = event.detail\n * // ...\n * })\n * ```\n */\n 'self:peer:update': CustomEvent<PeerUpdate>\n\n /**\n * This event is dispatched when a transport begins listening on a new address\n */\n 'transport:listening': CustomEvent<Listener>\n\n /**\n * This event is dispatched when a transport stops listening on an address\n */\n 'transport:close': CustomEvent<Listener>\n\n /**\n * This event is dispatched when the connection manager has more than the\n * configured allowable max connections and has closed some connections to\n * bring the node back under the limit.\n */\n 'connection:prune': CustomEvent<Connection[]>\n\n /**\n * This event notifies listeners when new incoming or outgoing connections\n * are opened.\n */\n 'connection:open': CustomEvent<Connection>\n\n /**\n * This event notifies listeners when incoming or outgoing connections are\n * closed.\n */\n 'connection:close': CustomEvent<Connection>\n\n /**\n * This event notifies listeners that a TLS certificate is available for use\n */\n 'certificate:provision': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that a new TLS certificate is available for\n * use. Any previous certificate may no longer be valid.\n */\n 'certificate:renew': CustomEvent<TLSCertificate>\n\n /**\n * This event notifies listeners that the node has started\n *\n * ```TypeScript\n * libp2p.addEventListener('start', (event) => {\n * console.info(libp2p.isStarted()) // true\n * })\n * ```\n */\n start: CustomEvent<Libp2p<T>>\n\n /**\n * This event notifies listeners that the node has stopped\n *\n * ```TypeScript\n * libp2p.addEventListener('stop', (event) => {\n * console.info(libp2p.isStarted()) // false\n * })\n * ```\n */\n stop: CustomEvent<Libp2p<T>>\n}\n\n/**\n * A map of user defined services available on the libp2p node via the\n * `services` key\n *\n * @example\n *\n * ```TypeScript\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * myService: myService({\n * // ...service options\n * })\n * }\n * })\n *\n * // invoke methods on the service\n * node.services.myService.anOperation()\n * ```\n */\nexport type ServiceMap = Record<string, unknown>\n\nexport type PendingDialStatus = 'queued' | 'active' | 'error' | 'success'\n\n/**\n * An item in the dial queue\n */\nexport interface PendingDial {\n /**\n * A unique identifier for this dial\n */\n id: string\n\n /**\n * The current status of the dial\n */\n status: PendingDialStatus\n\n /**\n * If known, this is the peer id that libp2p expects to be dialling\n */\n peerId?: PeerId\n\n /**\n * The list of multiaddrs that will be dialled. The returned connection will\n * use the first address that succeeds, all other dials part of this pending\n * dial will be cancelled.\n */\n multiaddrs: Multiaddr[]\n}\n\nexport type Libp2pStatus = 'starting' | 'started' | 'stopping' | 'stopped'\n\nexport interface IsDialableOptions extends AbortOptions {\n /**\n * If the dial attempt would open a protocol, and the multiaddr being dialed\n * is a circuit relay address, passing true here would cause the test to fail\n * because that protocol would not be allowed to run over a data/time limited\n * connection.\n */\n runOnLimitedConnection?: boolean\n}\n\nexport type TransportManagerDialProgressEvents =\n ProgressEvent<'transport-manager:selected-transport', string>\n\nexport type OpenConnectionProgressEvents =\n ProgressEvent<'connection:open', DialTarget> |\n ProgressEvent<'connection:opened', Connection> |\n TransportManagerDialProgressEvents |\n ProgressEvent<'dial-queue:already-connected'> |\n ProgressEvent<'dial-queue:already-in-dial-queue'> |\n ProgressEvent<'dial-queue:add-to-dial-queue'> |\n ProgressEvent<'dial-queue:start-dial'> |\n ProgressEvent<'dial-queue:calculated-addresses', Address[]> |\n OutboundConnectionUpgradeEvents\n\nexport interface DialOptions extends AbortOptions, ProgressOptions<OpenConnectionProgressEvents> {\n /**\n * If true, open a new connection to the remote even if one already exists\n */\n force?: boolean\n}\n\nexport interface DialProtocolOptions extends Omit<DialOptions, 'onProgress'>, Omit<NewStreamOptions, 'onProgress'>, ProgressOptions<OpenConnectionProgressEvents | NewStreamProgressEvents> {\n\n}\n\n/**\n * Libp2p nodes implement this interface.\n */\nexport interface Libp2p<T extends ServiceMap = ServiceMap> extends Startable, TypedEventTarget<Libp2pEvents<T>> {\n /**\n * The PeerId is a unique identifier for a node on the network.\n *\n * It is the hash of an RSA public key or, for Ed25519 or secp256k1 keys,\n * the key itself.\n *\n * @example\n *\n * ```TypeScript\n * console.info(libp2p.peerId)\n * // PeerId(12D3Foo...)\n * ````\n */\n peerId: PeerId\n\n /**\n * The peer store holds information we know about other peers on the network.\n * - multiaddrs, supported protocols, etc.\n *\n * @example\n *\n * ```TypeScript\n * const peer = await libp2p.peerStore.get(peerId)\n * console.info(peer)\n * // { id: PeerId(12D3Foo...), addresses: [] ... }\n * ```\n */\n peerStore: PeerStore\n\n /**\n * The peer routing subsystem allows the user to find peers on the network\n * or to find peers close to binary keys.\n *\n * @example\n *\n * ```TypeScript\n * const peerInfo = await libp2p.peerRouting.findPeer(peerId)\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * ```\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.peerRouting.getClosestPeers(key)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n peerRouting: PeerRouting\n\n /**\n * The content routing subsystem allows the user to find providers for content,\n * let the network know they are providers for content, and get/put values to\n * the DHT.\n *\n * @example\n *\n * ```TypeScript\n * for await (const peerInfo of libp2p.contentRouting.findProviders(cid)) {\n * console.info(peerInfo)\n * // { id: PeerId(12D3Foo...), multiaddrs: [] ... }\n * }\n * ```\n */\n contentRouting: ContentRouting\n\n /**\n * The metrics subsystem allows recording values to assess the health/performance\n * of the running node.\n *\n * @example\n *\n * ```TypeScript\n * const metric = libp2p.metrics.registerMetric({\n * 'my-metric'\n * })\n *\n * // later\n * metric.update(5)\n * ```\n */\n metrics?: Metrics\n\n /**\n * The logger used by this libp2p node\n */\n logger: ComponentLogger\n\n /**\n * The current status of the libp2p node\n */\n status: Libp2pStatus\n\n /**\n * Get a deduplicated list of peer advertising multiaddrs by concatenating\n * the listen addresses used by transports with any configured\n * announce addresses as well as observed addresses reported by peers.\n *\n * If Announce addrs are specified, configured listen addresses will be\n * ignored though observed addresses will still be included.\n *\n * @example\n *\n * ```TypeScript\n * const listenMa = libp2p.getMultiaddrs()\n * // [ <Multiaddr 047f00000106f9ba - /ip4/127.0.0.1/tcp/63930> ]\n * ```\n */\n getMultiaddrs(): Multiaddr[]\n\n /**\n * Returns a list of supported protocols\n *\n * @example\n *\n * ```TypeScript\n * const protocols = libp2p.getProtocols()\n * // [ '/ipfs/ping/1.0.0', '/ipfs/id/1.0.0' ]\n * ```\n */\n getProtocols(): string[]\n\n /**\n * Return a list of all connections this node has open, optionally filtering\n * by a PeerId\n *\n * @example\n *\n * ```TypeScript\n * for (const connection of libp2p.getConnections()) {\n * console.log(peerId, connection.remoteAddr.toString())\n * // Logs the PeerId string and the observed remote multiaddr of each Connection\n * }\n * ```\n */\n getConnections(peerId?: PeerId): Connection[]\n\n /**\n * Return the list of dials currently in progress or queued to start\n *\n * @example\n *\n * ```TypeScript\n * for (const pendingDial of libp2p.getDialQueue()) {\n * console.log(pendingDial)\n * }\n * ```\n */\n getDialQueue(): PendingDial[]\n\n /**\n * Return a list of all peers we currently have a connection open to\n */\n getPeers(): PeerId[]\n\n /**\n * Dials to the provided peer. If successful, the known metadata of the\n * peer will be added to the nodes `peerStore`.\n *\n * If a PeerId is passed as the first argument, the peer will need to have known multiaddrs for it in the PeerStore.\n *\n * @example\n *\n * ```TypeScript\n * const conn = await libp2p.dial(remotePeerId)\n *\n * // create a new stream within the connection\n * const stream = await conn.newStream(['/echo/1.1.0', '/echo/1.0.0'])\n *\n * // protocol negotiated: 'echo/1.0.0' means that the other party only supports the older version\n *\n * // ...\n * await conn.close()\n * ```\n */\n dial(peer: DialTarget, options?: DialOptions): Promise<Connection>\n\n /**\n * Dials to the provided peer and tries to handshake with the given protocols in order.\n * If successful, the known metadata of the peer will be added to the nodes `peerStore`,\n * and the `MuxedStream` will be returned together with the successful negotiated protocol.\n *\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n *\n * const { stream, protocol } = await libp2p.dialProtocol(remotePeerId, protocols)\n *\n * // Use this new stream like any other duplex stream\n * pipe([1, 2, 3], stream, consume)\n * ```\n */\n dialProtocol(peer: DialTarget, protocols: string | string[], options?: DialProtocolOptions): Promise<Stream>\n\n /**\n * Attempts to gracefully close an open connection to the given peer. If the\n * connection is not closed in the grace period, it will be forcefully closed.\n *\n * An AbortSignal can optionally be passed to control when the connection is\n * forcefully closed.\n *\n * @example\n *\n * ```TypeScript\n * await libp2p.hangUp(remotePeerId)\n * ```\n */\n hangUp(peer: PeerId | Multiaddr, options?: AbortOptions): Promise<void>\n\n /**\n * Sets up [multistream-select routing](https://github.com/multiformats/multistream-select) of protocols to their application handlers. Whenever a stream is opened on one of the provided protocols, the handler will be called. `handle` must be called in order to register a handler and support for a given protocol. This also informs other peers of the protocols you support.\n *\n * `libp2p.handle(protocols, handler, options)`\n *\n * In the event of a new handler for the same protocol being added and error\n * will be thrown. Pass `force: true` to override this.\n *\n * @example\n *\n * ```TypeScript\n * const handler = ({ connection, stream, protocol }) => {\n * // use stream or connection according to the needs\n * }\n *\n * libp2p.handle('/echo/1.0.0', handler, {\n * maxInboundStreams: 5,\n * maxOutboundStreams: 5\n * })\n * ```\n */\n handle(protocol: string | string[], handler: StreamHandler, options?: StreamHandlerOptions): Promise<void>\n\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unhandle(['/echo/1.0.0'])\n * ```\n */\n unhandle(protocols: string[] | string, options?: AbortOptions): Promise<void>\n\n /**\n * Register a topology to be informed when peers are encountered that\n * support the specified protocol\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register('/echo/1.0.0', {\n * onConnect: (peer, connection) => {\n * // handle connect\n * },\n * onDisconnect: (peer, connection) => {\n * // handle disconnect\n * }\n * })\n * ```\n */\n register(protocol: string, topology: Topology, options?: AbortOptions): Promise<string>\n\n /**\n * Unregister topology to no longer be informed when peers connect or\n * disconnect.\n *\n * @example\n *\n * ```TypeScript\n * const id = await libp2p.register(...)\n *\n * libp2p.unregister(id)\n * ```\n */\n unregister(id: string): void\n\n /**\n * Registers one or more middleware implementations that will be invoked for\n * incoming and outgoing protocol streams that match the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.use('/my/protocol/1.0.0', (stream, connection, next) => {\n * // do something with stream and/or connection\n * next(stream, connection)\n * })\n * ```\n */\n use (protocol: string, middleware: StreamMiddleware | StreamMiddleware[]): void\n\n /**\n * Deregisters all middleware for the passed protocol.\n *\n * @example\n *\n * ```TypeScript\n * libp2p.unuse('/my/protocol/1.0.0')\n * // any previously registered middleware will no longer be invoked\n * ```\n */\n unuse (protocol: string): void\n\n /**\n * Returns the public key for the passed PeerId. If the PeerId is of the 'RSA'\n * type this may mean searching the routing if the peer's key is not present\n * in the peer store.\n */\n getPublicKey(peer: Ed25519PeerId, options?: AbortOptions): Promise<Ed25519PublicKey>\n getPublicKey(peer: Secp256k1PeerId, options?: AbortOptions): Promise<Secp256k1PublicKey>\n getPublicKey(peer: RSAPeerId, options?: AbortOptions): Promise<RSAPublicKey>\n getPublicKey(peer: URLPeerId, options?: AbortOptions): Promise<never>\n getPublicKey(peer: PeerId, options?: AbortOptions): Promise<PublicKey>\n\n /**\n * Given the current node configuration, returns a promise of `true` or\n * `false` if the node would attempt to dial the passed multiaddr.\n *\n * This means a relevant transport is configured, and the connection gater\n * would not block the dial attempt.\n *\n * This may involve resolving DNS addresses so you should pass an AbortSignal.\n */\n isDialable(multiaddr: Multiaddr | Multiaddr[], options?: IsDialableOptions): Promise<boolean>\n\n /**\n * A set of user defined services\n */\n services: T\n}\n\n/**\n * Metadata about the current node\n */\nexport interface NodeInfo {\n /**\n * The implementation name\n */\n name: string\n\n /**\n * The implementation version\n */\n version: string\n\n /**\n * A string that contains information about the implementation and runtime\n */\n userAgent: string\n}\n\n/**\n * An object that contains an AbortSignal as\n * the optional `signal` property.\n *\n * @example\n *\n * ```TypeScript\n * const controller = new AbortController()\n *\n * aLongRunningOperation({\n * signal: controller.signal\n * })\n *\n * // later\n *\n * controller.abort()\n */\nexport interface AbortOptions {\n signal?: AbortSignal\n}\n\n/**\n * An object that contains a Logger as the `log` property.\n */\nexport interface LoggerOptions {\n log: Logger\n}\n\n/**\n * An object that includes a trace object that is passed onwards.\n *\n * This is used by metrics method tracing to link function calls together.\n */\nexport interface TraceOptions {\n trace?: any\n}\n\n/**\n * A signal that needs to be cleared when no longer in use\n */\nexport interface ClearableSignal extends AbortSignal {\n clear(): void\n}\n\n/**\n * When a routing operation involves reading values, these options allow\n * controlling where the values are read from. By default libp2p will check\n * local caches but may not use the network if a valid local value is found,\n * these options allow tuning that behavior.\n */\nexport interface RoutingOptions extends AbortOptions, ProgressOptions, TraceOptions {\n /**\n * Pass `false` to not use the network\n *\n * @default true\n */\n useNetwork?: boolean\n\n /**\n * Pass `false` to not use cached values\n *\n * @default true\n */\n useCache?: boolean\n}\n\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities')\n\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies')\n\nexport * from './connection.js'\nexport * from './connection-encrypter.js'\nexport * from './connection-gater.js'\nexport * from './connection-protector.js'\nexport * from './content-routing.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './keys.js'\nexport * from './message-stream.js'\nexport * from './metrics.js'\nexport * from './multiaddr-connection.js'\nexport * from './peer-discovery.js'\nexport * from './peer-id.js'\nexport * from './peer-info.js'\nexport * from './peer-routing.js'\nexport * from './peer-store.js'\nexport * from './record.js'\nexport * from './startable.js'\nexport * from './stream-handler.js'\nexport * from './stream-muxer.js'\nexport * from './stream.js'\nexport * from './topology.js'\nexport * from './transport.js'\n\nexport * from 'main-event'\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", "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 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, alphabetIdx: Record<string, number>, bitsPerChar: number, name: string): Uint8Array {\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 = alphabetIdx[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\nfunction createAlphabetIdx (alphabet: string): Record<string, number> {\n // Build the character lookup table:\n const alphabetIdx: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n alphabetIdx[alphabet[i]] = i\n }\n return alphabetIdx\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 const alphabetIdx = createAlphabetIdx(alphabet)\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, alphabetIdx, bitsPerChar, name)\n }\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", "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'\nimport type { DigestOptions } from './hasher.js'\n\nconst code: 0x0 = 0x0\nconst name = 'identity'\n\nconst encode: (input: Uint8Array) => Uint8Array = coerce\n\nfunction digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {\n if (options?.truncate != null && options.truncate !== input.byteLength) {\n if (options.truncate < 0 || options.truncate > input.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`)\n }\n\n input = input.subarray(0, options.truncate)\n }\n\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 for (const chunk of buf.bufs) {\n this.bufs.push(chunk)\n }\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 new Uint8ArrayList 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 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", "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\nconst DEFAULT_MIN_DIGEST_LENGTH = 20\n\nexport interface HasherInit <Name extends string, Code extends number> {\n name: Name\n code: Code\n encode(input: Uint8Array): Await<Uint8Array>\n\n /**\n * The minimum length a hash is allowed to be truncated to in bytes\n *\n * @default 20\n */\n minDigestLength?: number\n\n /**\n * The maximum length a hash is allowed to be truncated to in bytes. If not\n * specified it will be inferred from the length of the digest.\n */\n maxDigestLength?: number\n}\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode, minDigestLength, maxDigestLength }: HasherInit<Name, Code>): Hasher<Name, Code> {\n return new Hasher(name, code, encode, minDigestLength, maxDigestLength)\n}\n\nexport interface DigestOptions {\n /**\n * Truncate the returned digest to this number of bytes.\n *\n * This may cause the digest method to throw/reject if the passed value is\n * greater than the digest length or below a threshold under which the risk of\n * hash collisions is significant.\n *\n * The actual value of this threshold can depend on the hashing algorithm in\n * use.\n */\n truncate?: number\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 readonly minDigestLength: number\n readonly maxDigestLength?: number\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>, minDigestLength?: number, maxDigestLength?: number) {\n this.name = name\n this.code = code\n this.encode = encode\n this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH\n this.maxDigestLength = maxDigestLength\n }\n\n digest (input: Uint8Array, options?: DigestOptions): Await<Digest.Digest<Code, number>> {\n if (options?.truncate != null) {\n if (options.truncate < this.minDigestLength) {\n throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`)\n }\n\n if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)\n }\n }\n\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n\n if (result instanceof Uint8Array) {\n return createDigest(result, this.code, options?.truncate)\n }\n\n return result.then(digest => createDigest(digest, this.code, options?.truncate))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * Create a Digest from the passed uint8array and code, optionally truncating it\n * first.\n */\nfunction createDigest <Code extends number> (digest: Uint8Array, code: Code, truncate?: number): Digest.Digest<Code, number> {\n if (truncate != null && truncate !== digest.byteLength) {\n if (truncate > digest.byteLength) {\n throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`)\n }\n\n digest = digest.subarray(0, truncate)\n }\n\n return Digest.create(code, digest)\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 from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\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}`)\n}\n", "import bases from './util/bases.ts'\nimport type { SupportedEncodings } from './util/bases.ts'\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 { AbortOptions } from '@libp2p/interface'\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, options?: AbortOptions): Promise<Uint8Array> {\n const privateKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['sign'])\n options?.signal?.throwIfAborted()\n\n const signature = await crypto.subtle.sign({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, privateKey, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(signature, 0, signature.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<boolean> {\n const publicKey = await crypto.subtle.importKey('jwk', key, {\n name: 'ECDSA',\n namedCurve: key.crv ?? 'P-256'\n }, false, ['verify'])\n options?.signal?.throwIfAborted()\n\n const result = await crypto.subtle.verify({\n name: 'ECDSA',\n hash: {\n name: 'SHA-256'\n }\n }, publicKey, sig, msg.subarray())\n options?.signal?.throwIfAborted()\n\n return result\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, AbortOptions } 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, options?: AbortOptions): Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data, options)\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, options?: AbortOptions): Promise<Uint8Array> {\n return hashAndSign(this.jwk, message, options)\n }\n}\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg<Uint8Array>,\n length?: number,\n title: string = ''\n): TRet<Uint8Array> {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\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/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\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/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\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.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<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 * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('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 RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\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 * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\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;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<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 = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\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 TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg<Uint8Array>): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg<Uint8Array>): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet<Uint8Array>;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg<Uint8Array>): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet<Uint8Array>;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\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 /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet<Uint8Array>;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n create(): T;\n }\n : {\n (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\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 * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\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 canXOF = false;\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 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: TArg<Uint8Array>): this {\n aexists(this);\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 only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\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: TArg<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 // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(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 must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must 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(): TRet<Uint8Array> {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet<Uint8Array>;\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 // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\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 from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<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 from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<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.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\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\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst: bigint[], le = false): TRet<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] as TRet<Uint32Array[]>;\n}\n\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h: number, l: number): number => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead 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\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\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// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\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};\n// Default export mirrors named `u64` for compatibility with object-style imports.\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 {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\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, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * 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 SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\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 // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_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 constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\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// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\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 high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\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 abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\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 // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_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 // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\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\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\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() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\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 the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\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\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\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\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\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. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = <T extends TArg<Uint8Array>>(value: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> =>\n concatBytes_(...arrays) as TRet<Uint8Array>;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet<Uint8Array> => hexToBytes_(hex) as TRet<Uint8Array>;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet<Uint8Array> =>\n randomBytes_(bytesLength) as TRet<Uint8Array>;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg<Uint8Array>): TRet<Uint8Array>;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg<Uint8Array>, message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber<T extends number | bigint>(n: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet<Uint8Array>;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet<Uint8Array> {\n return numberToBytesBE(n, len).reverse() as TRet<Uint8Array>;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet<Uint8Array> {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet<Uint8Array>;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n a = abytes(a);\n b = abytes(b);\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/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet<Uint8Array> {\n if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet<Uint8Array>;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\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: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\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 RangeError('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 * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\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 * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\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 * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\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 * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: TArg<Uint8Array>) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg<HmacFn>\n): TRet<(seed: Uint8Array, predicate: Pred<T>) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet<Uint8Array> => new Uint8Array(len) as TRet<Uint8Array>;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = u8n(hashLen);\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 // hmac(k)(v, ...values)\n const h = (...msgs: TArg<Uint8Array[]>) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg<Uint8Array> = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, 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++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\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: TArg<Uint8Array>, pred: TArg<Pred<T>>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred<T>)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred<T>) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field 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 {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\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 the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\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 const q = b / a;\n const r = b - a * q;\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\nfunction assertIsSquare<T>(Fp: TArg<IField<T>>, root: T, n: T): void {\n const F = Fp as IField<T>;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(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 return (<T>(Fp: TArg<IField<T>>, n: T): T => {\n const F = Fp as IField<T>;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n }) as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, 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 * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: TArg<IField<T>>, n: T): T {\n const F = Fp as IField<T>;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n } as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\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 choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField<T> {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\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 the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\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;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet<IField<T>>;\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 * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T {\n const F = Fp as IField<T>;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero = false): T[] {\n const F = Fp as IField<T>;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField<T>;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.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 * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1 {\n const F = Fp as IField<T>;\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean {\n const l = FpLegendre(Fp as IField<T>, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap<object, ReturnType<typeof FpSqrt>>();\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\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: bigint, b: bigint, condition: boolean) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet<Readonly<FpField>> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\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. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\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 * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\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. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n key: TArg<Uint8Array>,\n fieldOrder: bigint,\n isLE = false\n): TRet<Uint8Array> {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (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 { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint<T> = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint<F>;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void {\n const pc = Point as unknown as CurvePointCons<any>;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper<T> = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\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 * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\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.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype 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; ignore when isZero\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 branch noise only\n const offsetF = offsetStart; // fake branch noise only\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 // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\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 a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = 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 point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\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 * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.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, this.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(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.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 assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, 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 createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\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 points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\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 const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\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 < slength; 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 P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\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 const fieldN = c.Fn;\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: P) => {\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[]): P => {\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/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams<T> = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: TArg<IField<T>>, isLE?: boolean): TRet<IField<T>> {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet<IField<T>>;\n } else {\n return Field(order, { isLE }) as unknown as TRet<IField<T>>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn<T> = {\n /** Base field used for curve coordinates. */\n Fp: IField<T>;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField<bigint>;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: TArg<Partial<FpFn<T>>> = {},\n FpFnLE?: boolean\n): TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn } as TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: TArg<Signer['getPublicKey']>\n): TRet<KeygenFn> {\n return function keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed) as TRet<Uint8Array>;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet<Uint8Array> };\n };\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 * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n aInRange,\n asafenumber,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n hexToBytes,\n isBytes,\n notImplemented,\n validateObject,\n randomBytes as wcRandomBytes,\n type FHash,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);\n\n/** Extended Edwards point with X/Y/Z/T coordinates. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n}\n/** Constructor and decoding helpers for extended Edwards points. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n /** Create a point from extended X/Y/Z/T coordinates without validation. */\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n /**\n * Return the curve parameters used by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): EdwardsOpts;\n /**\n * Decode a point from bytes, optionally using ZIP-215 rules.\n * @param bytes - Encoded point bytes.\n * @param zip215 - Whether to accept ZIP-215 encodings.\n * @returns Decoded Edwards point.\n */\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n /**\n * Decode a point from hex, optionally using ZIP-215 rules.\n * @param hex - Encoded point hex.\n * @param zip215 - Whether to accept ZIP-215 encodings.\n * @returns Decoded Edwards point.\n */\n fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Edwards curve parameter `a`. */\n a: bigint;\n /** Edwards curve parameter `d`. */\n d: bigint;\n /** Generator x coordinate. */\n Gx: bigint;\n /** Generator y coordinate. */\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating \u221A(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n /** Optional base-field override. */\n Fp: IField<bigint>;\n /** Optional scalar-field override. */\n Fn: IField<bigint>;\n /** Whether field encodings are little-endian. */\n FpFnLE: boolean;\n /** Square-root ratio helper used during point decompression. */\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n /** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */\n adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Domain-separation helper for contexts and prehash mode. */\n domain: (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => TRet<Uint8Array>;\n /** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n /** Optional prehash function used before signing or verifying messages. */\n prehash: FHash;\n /** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */\n zip215: boolean;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) helper namespace.\n * Allows creating and verifying signatures, and deriving public keys.\n */\nexport interface EdDSA {\n /**\n * Generate a secret/public key pair.\n * @param seed - Optional seed material.\n * @returns Secret/public key pair.\n */\n keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Sign a message with an EdDSA secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param options - Optional signature tweaks:\n * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n options?: TArg<{ context?: Uint8Array }>\n ) => TRet<Uint8Array>;\n /**\n * Verify a signature against a message and public key.\n * @param sig - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param options - Optional verification tweaks:\n * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n * - `zip215` (optional): Whether to accept ZIP-215 encodings.\n * @returns Whether the signature is valid.\n */\n verify: (\n sig: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n options?: TArg<{ context?: Uint8Array; zip215?: boolean }>\n ) => boolean;\n /** Point constructor used by this signature scheme. */\n Point: EdwardsPointCons;\n /** Helper utilities for key validation and Montgomery conversion. */\n utils: {\n /**\n * Generate a valid random secret key.\n * Optional seed bytes are only length-checked and returned unchanged.\n */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Check whether a secret key has the expected encoding. */\n isValidSecretKey: (secretKey: TArg<Uint8Array>) => boolean;\n /** Check whether a public key decodes to a valid point. */\n isValidPublicKey: (publicKey: TArg<Uint8Array>, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * Converts ed public key to x public key.\n *\n * ```js\n * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n * const aPriv = x25519.utils.randomSecretKey();\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomery: (publicKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * Converts ed secret key to x secret key.\n *\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv_ed = ed25519.utils.randomSecretKey();\n * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomerySecret: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Return the expanded private key components used by RFC8032 signing. */\n getExtendedPublicKey: (key: TArg<Uint8Array>) => {\n head: TRet<Uint8Array>;\n prefix: TRet<Uint8Array>;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: TRet<Uint8Array>;\n };\n };\n /** Byte lengths for keys and signatures exposed by this scheme. */\n lengths: CurveLengths;\n}\n\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp: TArg<IField<bigint>>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=8\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(\n params: TArg<EdwardsOpts>,\n extraOpts: TArg<EdwardsExtraOpts> = {}\n): EdwardsPointCons {\n const opts = extraOpts as EdwardsExtraOpts;\n const validated = createCurveFields('edwards', params as EdwardsOpts, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n validateObject(opts, {}, { uvRatio: 'function' });\n\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(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n opts.uvRatio === undefined\n ? (u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n\n // Validate whether the passed curve params are valid.\n // equation ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2 should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aedpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('EdwardsPoint expected');\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 EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\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 acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[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('point.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('bad point: 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('bad point: 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\n static fromHex(hex: string, zip215 = false): Point {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\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 { X, Y, Z, 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 }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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.X), this.Y, this.Z, modP(-this.T));\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 { X: X1, Y: Y1, Z: 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 aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: 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 // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [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 // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar: bigint): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));\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 // Clears cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.clearCofactor().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.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n const p = this;\n let iz = invertedZ;\n const { X, Y, 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 x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (Fn.BITS >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: string): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this as any;\n }\n\n assertValidity(): void {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this as unknown as T;\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(\n Point: EdwardsPointCons,\n cHash: TArg<FHash>,\n eddsaOpts: TArg<EdDSAOpts> = {}\n): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n const hash = cHash as FHash;\n const opts = eddsaOpts as EdDSAOpts;\n validateObject(\n opts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = (hash as FHash & { outputLen?: number }).outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const adjustScalarBytes =\n opts.adjustScalarBytes === undefined\n ? (bytes: TArg<Uint8Array>) => bytes as TRet<Uint8Array>\n : opts.adjustScalarBytes;\n const domain =\n opts.domain === undefined\n ? (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data as TRet<Uint8Array>;\n }\n : opts.domain; // NOOP\n\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash: TArg<Uint8Array>): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: TArg<Uint8Array>) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\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 = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len) as TRet<Uint8Array>; // 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 * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey: TArg<Uint8Array>) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes() as TRet<Uint8Array>;\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(\n context: TArg<Uint8Array> = Uint8Array.of(),\n ...msgs: TArg<Uint8Array[]>\n ) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n options: TArg<{ context?: Uint8Array }> = {}\n ): TRet<Uint8Array> {\n msg = abytes(msg, undefined, 'message');\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result') as TRet<Uint8Array>;\n }\n\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts: TArg<{ context?: Uint8Array; zip215?: boolean }> = {\n zip215: opts.zip215,\n };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 \u00A7\u00A75.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n options = verifyOpts\n ): boolean {\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n // RFC 8032 \u00A7\u00A75.1.7/5.2.7 and FIPS 186-5 \u00A7\u00A77.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder()) return false;\n\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed') as TRet<Uint8Array>;\n }\n\n function isValidSecretKey(key: TArg<Uint8Array>): boolean {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n\n function isValidPublicKey(key: TArg<Uint8Array>, zip215?: boolean): boolean {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: TArg<Uint8Array>): TRet<Uint8Array> {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u) as TRet<Uint8Array>;\n },\n toMontgomerySecret(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = hash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size) as TRet<Uint8Array>;\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n }) satisfies Signer;\n}\n", "/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash, TArg, TRet } from '../utils.ts';\nimport {\n abytes,\n asafenumber,\n asciiToBytes,\n bytesToNumberBE,\n copyBytes,\n concatBytes,\n isBytes,\n validateObject,\n} from '../utils.ts';\nimport type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\n/** ASCII domain-separation tag or raw bytes. */\nexport type AsciiOrBytes = string | Uint8Array;\ntype H2CDefaults = {\n DST: AsciiOrBytes;\n expand: 'xmd' | 'xof';\n hash: CHash;\n p: bigint;\n m: number;\n k: number;\n encodeDST?: AsciiOrBytes;\n};\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n /** Domain separation tag. */\n DST: AsciiOrBytes;\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n /** Base-field characteristic. */\n p: bigint;\n /** Extension degree (`1` for prime fields). */\n m: number;\n /** Target security level in bits. */\n k: number;\n};\n/** Hash-only subset of RFC 9380 options used by per-call overrides. */\nexport type H2CHashOpts = {\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n};\n/**\n * Map one hash-to-field output tuple onto affine curve coordinates.\n * Implementations receive the validated scalar tuple by reference for performance and MUST treat it\n * as read-only. Callers that need scratch space should copy before mutating.\n * @param scalar - Field-element tuple produced by `hash_to_field`.\n * @returns Affine point before subgroup clearing.\n */\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\n/** Per-call override for the domain-separation tag. */\nexport type H2CDSTOpts = {\n /** Domain-separation tag override. */\n DST: AsciiOrBytes;\n};\n/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */\nexport type H2CHasherBase<PC extends PC_ANY> = {\n /**\n * Hash arbitrary bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after hash-to-curve.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /**\n * Hash arbitrary bytes to one scalar.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Scalar reduced into the target field.\n */\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;\n /**\n * Derive one curve point from non-uniform bytes without the random-oracle\n * guarantees of `hashToCurve`.\n * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve\n * path instead of the random-oracle construction.\n */\n deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Point constructor for the target curve. */\n Point: PC;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {\n /**\n * Encode non-uniform bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after encode-to-curve.\n */\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Deterministic map from `hash_to_field` tuples into affine coordinates. */\n mapToCurve: MapToCurve<PC_F<PC>>;\n /** Default RFC 9380 options captured by this hasher bundle. */\n defaults: H2CDefaults;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value: number, length: number): TRet<Uint8Array> {\n asafenumber(value);\n asafenumber(length);\n // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length);\n if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res) as TRet<Uint8Array>;\n}\n\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a: TArg<Uint8Array>, b: TArg<Uint8Array>): TRet<Uint8Array> {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr as TRet<Uint8Array>;\n}\n\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST: TArg<AsciiOrBytes>): TRet<Uint8Array> {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n // RFC 9380 \u00A73.1 requirement 2: tags \"MUST have nonzero length\".\n if (dst.length === 0) throw new Error('DST must be non-empty');\n return dst as TRet<Uint8Array>;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n // by reaching `I2OSP(256, 1)`.\n for (let i = 1; i < ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n * new TextEncoder().encode('hello noble'),\n * 'DST',\n * 32,\n * 128,\n * shake256\n * );\n * ```\n */\nexport function expand_message_xof(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n k: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // RFC 9380 \u00A75.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n * DST: 'DST',\n * p: 17n,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(\n msg: TArg<Uint8Array>,\n count: number,\n options: TArg<H2COpts>\n): bigint[][] {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n // RFC 9380 \u00A75.2 defines hash_to_field over a list of one or more field elements and requires\n // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n if (count < 1) throw new Error('hash_to_field: expected count >= 1');\n if (m < 1) throw new Error('hash_to_field: expected m >= 1');\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\ntype XY<T> = (x: T, y: T) => { x: T; y: T };\ntype XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // RFC 9380 \u00A76.6.3 / Appendix E: denominator-zero exceptional cases must\n // return the identity on E.\n // Shipped Weierstrass consumers encode that affine identity as all-zero\n // coordinates, so `passZero=true` intentionally collapses zero\n // denominators to `{ x: 0, y: 0 }`.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 \u00A7\u00A74.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-' as const;\n\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n * the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n * DST: 'P256_XMD:SHA-256_SSWU_RO_',\n * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n * p: p256.Point.Fp.ORDER,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher<PC extends PC_ANY>(\n Point: PC,\n mapToCurve: MapToCurve<PC_F<PC>>,\n defaults: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>\n): H2CHasher<PC> {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n const snapshot = (src: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>): TRet<H2CDefaults> =>\n Object.freeze({\n ...src,\n DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n ...(src.encodeDST === undefined\n ? {}\n : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n }) as TRet<H2CDefaults>;\n // Keep one private defaults snapshot for actual hashing and expose fresh\n // detached snapshots via the public getter.\n // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n // the singleton hasher for every other consumer in the same process.\n const safeDefaults = snapshot(defaults);\n function map(num: bigint[]): PC_P<PC> {\n return Point.fromAffine(mapToCurve(num)) as PC_P<PC>;\n }\n function clear(initial: PC_P<PC>): PC_P<PC> {\n const P = initial.clearCofactor();\n // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n if (P.equals(Point.ZERO)) return Point.ZERO as PC_P<PC>;\n P.assertValidity();\n return P as PC_P<PC>;\n }\n\n return Object.freeze({\n get defaults() {\n return snapshot(safeDefaults);\n },\n Point,\n\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const opts = Object.assign({}, safeDefaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1) as PC_P<PC>);\n },\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n const opts = Object.assign({}, safeDefaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars: bigint | bigint[]): PC_P<PC> {\n // Curves with m=1 accept only single scalar\n if (safeDefaults.m === 1) {\n if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\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.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n eddsa,\n edwards,\n PrimeEdwardsPoint,\n type EdDSA,\n type EdDSAOpts,\n type EdwardsOpts,\n type EdwardsPoint,\n type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport { createFROST, type FROST } from './abstract/frost.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CDSTOpts,\n type H2CHasher,\n type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createOPRF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes, type TArg, type TRet } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\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_CURVE_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 // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes: TArg<Uint8Array>): TRet<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 as TRet<Uint8Array>;\n}\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// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_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\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(\n data: TArg<Uint8Array>,\n ctx: TArg<Uint8Array>,\n phflag: boolean\n): TRet<Uint8Array> {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n asciiToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n ) as TRet<Uint8Array>;\n}\n\nfunction ed(opts: TArg<EdDSAOpts>) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(\n ed25519_Point,\n sha512,\n Object.assign({ adjustScalarBytes, zip215: true }, opts as EdDSAOpts)\n );\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree()) throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n }))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: TRet<MontgomeryECDH> = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\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 });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\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/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n const ELL2_C4 = (ed25519_CURVE_p - _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 // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\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 // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\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 // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\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\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\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 // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\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 // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519_Point,\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: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\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// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\n// RFC 9496 \u00A74.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes: TArg<Uint8Array>) =>\n Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 \u00A74.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\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_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint 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 EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: EdwardsPoint) {\n super(ep);\n }\n\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n static fromBytes(bytes: TArg<Uint8Array>): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\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(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\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)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: string): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): TRet<Uint8Array> {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\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 Fp.toBytes(s) as TRet<Uint8Array>; // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\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 is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\nObject.freeze(_RistrettoPoint.BASE);\nObject.freeze(_RistrettoPoint.ZERO);\nObject.freeze(_RistrettoPoint.prototype);\nObject.freeze(_RistrettoPoint);\n\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint });\n\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * \u00A74.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): _RistrettoPoint {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve!(xmd);\n },\n hashToScalar(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts> = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes: TArg<Uint8Array>): _RistrettoPoint {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n }))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP: readonly string[] = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\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 { ed25519 as ed } from '@noble/curves/ed25519.js'\nimport { toString as uint8arrayToString } from 'uint8arrays/to-string'\nimport crypto from '../../webcrypto/index.js'\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\n// memoize support result to skip additional awaits every time we use an ed key\nlet ed25519Supported: boolean | undefined\nconst webCryptoEd25519SupportedPromise = (async () => {\n try {\n await crypto.get().subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])\n return true\n } catch {\n return false\n }\n})()\n\nexport function generateKey (): Uint8ArrayKeyPair {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomSecretKey()\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\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\nasync function hashAndSignWebCrypto (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n let privateKeyRaw: Uint8Array\n if (privateKey.length === PRIVATE_KEY_BYTE_LENGTH) {\n privateKeyRaw = privateKey.subarray(0, 32)\n } else {\n privateKeyRaw = privateKey\n }\n\n const jwk: JsonWebKey = {\n crv: 'Ed25519',\n kty: 'OKP',\n x: uint8arrayToString(privateKey.subarray(32), 'base64url'),\n d: uint8arrayToString(privateKeyRaw, 'base64url'),\n ext: true,\n key_ops: ['sign']\n }\n\n const key = await crypto.get().subtle.importKey('jwk', jwk, { name: 'Ed25519' }, true, ['sign'])\n const sig = await crypto.get().subtle.sign({ name: 'Ed25519' }, key, msg instanceof Uint8Array ? msg : msg.subarray())\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport function hashAndSignNoble (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 async function hashAndSign (privateKey: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<Uint8Array> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndSignWebCrypto(privateKey, msg)\n }\n\n return hashAndSignNoble(privateKey, msg)\n}\n\nasync function hashAndVerifyWebCrypto (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (publicKey.buffer instanceof ArrayBuffer) {\n const key = await crypto.get().subtle.importKey('raw', publicKey.buffer, { name: 'Ed25519' }, false, ['verify'])\n const isValid = await crypto.get().subtle.verify({ name: 'Ed25519' }, key, sig, msg instanceof Uint8Array ? msg : msg.subarray())\n return isValid\n }\n\n throw new TypeError('WebCrypto does not support SharedArrayBuffer for Ed25519 keys')\n}\n\nexport function hashAndVerifyNoble (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): boolean {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey)\n}\n\nexport async function hashAndVerify (publicKey: Uint8Array, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList): Promise<boolean> {\n if (ed25519Supported == null) {\n ed25519Supported = await webCryptoEd25519SupportedPromise\n }\n\n if (ed25519Supported) {\n return hashAndVerifyWebCrypto(publicKey, sig, msg)\n }\n\n return hashAndVerifyNoble(publicKey, sig, msg)\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 { 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) {\n throw new Error('byte array longer than desired length')\n }\n\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 { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { identity } from 'multiformats/hashes/identity'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { isPromise } from '../../util.ts'\nimport { publicKeyToProtobuf } from '../index.js'\nimport { ensureEd25519Key } from './utils.js'\nimport * as crypto from './index.js'\nimport type { Ed25519PublicKey as Ed25519PublicKeyInterface, Ed25519PrivateKey as Ed25519PrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\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, options?: AbortOptions): boolean | Promise<boolean> {\n options?.signal?.throwIfAborted()\n const result = crypto.hashAndVerify(this.raw, sig, data)\n\n if (isPromise<boolean>(result)) {\n return result.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n return result\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n options?.signal?.throwIfAborted()\n const sig = crypto.hashAndSign(this.raw, message)\n\n if (isPromise<Uint8Array>(sig)) {\n return sig.then(res => {\n options?.signal?.throwIfAborted()\n return res\n })\n }\n\n options?.signal?.throwIfAborted()\n return sig\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.ts'\nimport { LongBits } from './longbits.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Reader } from '../index.ts'\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.ts'\nimport type { Codec, DecodeOptions } from './codec.ts'\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.ts'\nimport { LongBits } from './longbits.ts'\nimport pool from './pool.ts'\nimport * as utf8 from './utf8.ts'\nimport type { Writer } from '../index.ts'\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 {}\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.ts'\nimport type { Codec } from './codec.ts'\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 { createReader } from './utils/reader.ts'\nimport type { Codec } from './codec.ts'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function * streamMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'stream'>, opts?: any): Generator<any> {\n const reader = createReader(buf)\n\n yield * codec.stream(reader, undefined, '$', opts)\n}\n", "import type { Writer, Reader } from './index.ts'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport const CODEC_TYPES = {\n VARINT: 0,\n BIT64: 1,\n LENGTH_DELIMITED: 2,\n START_GROUP: 3,\n END_GROUP: 4,\n BIT32: 5\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 StreamFunction<T> {\n (reader: Reader, length?: number, prefix?: string, opts?: DecodeOptions<T>): Generator<any>\n}\n\nexport interface Codec<T> {\n name: string\n type: number\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n stream: StreamFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: number, encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode,\n stream\n }\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { DecodeFunction, EncodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: any): 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<T> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<any> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n const stream: StreamFunction<T> = function * enumStream (reader) {\n const val = reader.int32()\n\n yield findValue(val)\n }\n\n return createCodec<T>('enum', CODEC_TYPES.VARINT, encode, decode, stream)\n}\n", "import { createCodec, CODEC_TYPES } from '../codec.ts'\nimport type { EncodeFunction, DecodeFunction, Codec, StreamFunction } from '../codec.ts'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>, stream: StreamFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode, stream)\n}\n", "import { decodeMessage, encodeMessage, enumeration, message, streamMessage } from 'protons-runtime'\nimport type { Codec, DecodeOptions } 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}\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 }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PublicKeyTypeFieldEvent {\n field: '$.Type'\n value: KeyType\n }\n\n export interface PublicKeyDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PublicKey>): Uint8Array {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): Generator<PublicKeyTypeFieldEvent | PublicKeyDataFieldEvent> {\n return streamMessage(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 }, function * (reader, length, prefix, opts = {}) {\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 yield {\n field: `${prefix}.Type`,\n value: KeyType.codec().decode(reader)\n }\n break\n }\n case 2: {\n yield {\n field: `${prefix}.Data`,\n value: reader.bytes()\n }\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n })\n }\n\n return _codec\n }\n\n export interface PrivateKeyTypeFieldEvent {\n field: '$.Type'\n value: KeyType\n }\n\n export interface PrivateKeyDataFieldEvent {\n field: '$.Data'\n value: Uint8Array\n }\n\n export function encode (obj: Partial<PrivateKey>): Uint8Array {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export function decode (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n\n export function stream (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): Generator<PrivateKeyTypeFieldEvent | PrivateKeyDataFieldEvent> {\n return streamMessage(buf, PrivateKey.codec(), opts)\n }\n}\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC<T extends Hash<T>> implements Hash<_HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg<CHash>, key: TArg<Uint8Array>) {\n ahash(hash);\n abytes(key, undefined, '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 the first block) of the outer hash here,\n // 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: TArg<Uint8Array>): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest(): TRet<Uint8Array> {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet<Uint8Array>;\n }\n _cloneInto(to?: _HMAC<T>): _HMAC<T> {\n // Create new instance without calling constructor since the key\n // is 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 - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg<CHash>, key: TArg<Uint8Array>, message: TArg<Uint8Array>): TRet<Uint8Array>;\n create(hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>>;\n};\nexport const hmac: TRet<HmacFn> = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg<CHash>,\n key: TArg<Uint8Array>,\n message: TArg<Uint8Array>\n ): TRet<Uint8Array> => new _HMAC<any>(hash, key).update(message).digest()) as TRet<HmacFn>;\n hmac_.create = (hash: TArg<CHash>, key: TArg<Uint8Array>): TRet<_HMAC<any>> =>\n new _HMAC<any>(hash, key) as TRet<_HMAC<any>>;\n return hmac_;\n})();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\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) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abignumber,\n abool,\n abytes,\n aInRange,\n asafenumber,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type HmacFn,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n FpIsSquare,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\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 *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n /** Cube root of unity used by the GLV endomorphism. */\n beta: bigint;\n /** Reduced lattice basis used for scalar splitting. */\n basises?: EndoBasis;\n /**\n * Optional custom scalar-splitting helper.\n * Receives one scalar and returns two half-sized scalar components.\n */\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n /** Whether the first split scalar should be negated. */\n k1neg: boolean;\n /** Absolute value of the first split scalar. */\n k1: bigint;\n /** Whether the second split scalar should be negated. */\n k2neg: boolean;\n /** Absolute value of the second split scalar. */\n k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda \u2261 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n /** Whether to hash the message before signature recovery. */\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n /** Whether to hash the message before verification. */\n prehash?: boolean;\n /** Whether to reject high-S signatures. */\n lowS?: boolean;\n /** Signature encoding to accept. */\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n * security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n /** Whether to hash the message before signing. */\n prehash?: boolean;\n /** Whether to normalize signatures into the low-S half-order. */\n lowS?: boolean;\n /** Signature encoding to produce. */\n format?: ECDSASignatureFormat;\n /** Optional hedging input for deterministic k generation. */\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): D {\n validateObject(opts);\n const optsn = {} as D;\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def) as (keyof D)[]) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /**\n * Encode the point into compressed or uncompressed SEC1 bytes.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point bytes.\n */\n toBytes(isCompressed?: boolean): TRet<Uint8Array>;\n /**\n * Encode the point into compressed or uncompressed SEC1 hex.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point hex.\n */\n toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n /**\n * Return the curve parameters captured by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Weierstrass curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts<T> = Partial<{\n /** Optional base-field override. */\n Fp: IField<T>;\n /** Optional scalar-field override. */\n Fn: IField<bigint>;\n /** Whether the point constructor accepts infinity points. */\n allowInfinityPoint: boolean;\n /** Optional GLV endomorphism data. */\n endo: EndomorphismOpts;\n /** Optional torsion-check override. */\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n /** Optional cofactor-clearing override. */\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n /** Optional custom point decoder. */\n fromBytes: (bytes: TArg<Uint8Array>) => AffinePoint<T>;\n /** Optional custom point encoder. */\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => TRet<Uint8Array>;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n * low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n * `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n /** Default low-S policy for this ECDSA instance. */\n lowS: boolean;\n /** HMAC implementation used by RFC6979 DRBG. */\n hmac: HmacFn;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n /** Hash-to-integer conversion override. */\n bits2int: (bytes: TArg<Uint8Array>) => bigint;\n /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n bits2int_modN: (bytes: TArg<Uint8Array>) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\n /**\n * Generate a secret/public key pair.\n * @param seed - Optional seed material.\n * @returns Secret/public key pair.\n */\n keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>, isCompressed?: boolean) => TRet<Uint8Array>;\n /**\n * Compute the shared secret point from a secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded shared point.\n */\n getSharedSecret: (\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed?: boolean\n ) => TRet<Uint8Array>;\n /** Point constructor used by this ECDH instance. */\n Point: WeierstrassPointCons<bigint>;\n /** Validation and random-key helpers. */\n utils: {\n /** Check whether a secret key has the expected encoding. */\n isValidSecretKey: (secretKey: TArg<Uint8Array>) => boolean;\n /** Check whether a public key decodes to a valid point. */\n isValidPublicKey: (publicKey: TArg<Uint8Array>, isCompressed?: boolean) => boolean;\n /** Generate a valid random secret key. */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n };\n /** Byte lengths for keys and signatures exposed by this curve. */\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n /**\n * Sign a message with the given secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<ECDSASignOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify a signature against a message and public key.\n * @param signature - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n * @returns Whether the signature is valid.\n */\n verify: (\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<ECDSAVerifyOpts>\n ) => boolean;\n /**\n * Recover the public key encoded into a recoverable signature.\n * @param signature - Recoverable signature bytes.\n * @param message - Message bytes.\n * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n * @returns Encoded recovered public key.\n */\n recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts?: TArg<ECDSARecoverOpts>\n ): TRet<Uint8Array>;\n /** Signature constructor and parser helpers. */\n Signature: ECDSASignatureCons;\n}\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n // asn.1 DER encoding utils\n /**\n * DER-specific error constructor.\n * @param m - Error message.\n * @returns DER-specific error instance.\n */\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n /** Low-level tag-length-value helpers used by DER encoders. */\n _tlv: {\n /**\n * Encode one TLV record.\n * @param tag - ASN.1 tag byte.\n * @param data - Hex-encoded value payload.\n * @returns Encoded TLV string.\n */\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n /**\n * Decode one TLV record and return the value plus leftover bytes.\n * @param tag - Expected ASN.1 tag byte.\n * @param data - Remaining DER bytes.\n * @returns Parsed value plus leftover bytes.\n */\n decode(tag: number, data: TArg<Uint8Array>): TRet<{ 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 /** Positive-integer DER helpers used by ECDSA signature encoding. */\n _int: {\n /**\n * Encode one positive bigint as a DER INTEGER.\n * @param num - Positive integer to encode.\n * @returns Encoded DER INTEGER.\n */\n encode(num: bigint): string;\n /**\n * Decode one DER INTEGER into a bigint.\n * @param data - DER INTEGER bytes.\n * @returns Decoded bigint.\n */\n decode(data: TArg<Uint8Array>): bigint;\n };\n /**\n * Parse a DER signature into `{ r, s }`.\n * @param bytes - DER signature bytes.\n * @returns Parsed signature components.\n */\n toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint };\n /**\n * Encode `{ r, s }` as a DER signature.\n * @param sig - Signature components.\n * @returns DER-encoded signature hex.\n */\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: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\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 asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof data);\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\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: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }> {\n const { Err: E } = DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255) 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 // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\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 // This would overflow u32 in JS.\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\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) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\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 abignumber(num);\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: TArg<Uint8Array>): bigint {\n const { Err: E } = DER;\n if (data.length < 1) throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && 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(bytes: TArg<Uint8Array>): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\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};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp as IField<T>;\n const Fn = validated.Fn as IField<bigint>;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp as TArg<IField<T>>, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): TRet<Uint8Array> {\n // SEC 1 v2.0 \u00A72.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet<Uint8Array>;\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx) as TRet<Uint8Array>;\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet<Uint8Array>;\n }\n }\n function pointFromBytes(bytes: TArg<Uint8Array>) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x\u00B2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown): asserts other is Point {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\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 WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\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 // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: TArg<Uint8Array>): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\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 *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n const p = this;\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 // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n 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 if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: WeierstrassPoint<T>): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { X: X1, Y: Y1, Z: 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: WeierstrassPoint<T>): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: 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: WeierstrassPoint<T>) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\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 } = extraOpts;\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: 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 x = Fp.mul(X, iz);\n const y = 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, y };\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n if (cofactor === _1n) return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n\n toBytes(isCompressed = true): TRet<Uint8Array> {\n abool(isCompressed, 'isCompressed');\n // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (bits >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n\n/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n /** Signature component `r`. */\n readonly r: bigint;\n /** Signature component `s`. */\n readonly s: bigint;\n /** Optional recovery bit for recoverable signatures. */\n readonly recovery?: number;\n /**\n * Return a copy of the signature with a recovery bit attached.\n * @param recovery - Recovery bit to attach.\n * @returns Signature with an attached recovery bit.\n */\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n /**\n * Check whether the signature uses the high-S half-order.\n * @returns Whether the signature uses the high-S half-order.\n */\n hasHighS(): boolean;\n /**\n * Recover the public key from the hashed message and recovery bit.\n * @param messageHash - Hashed message bytes.\n * @returns Recovered public-key point.\n */\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint>;\n /**\n * Encode the signature into bytes.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature bytes.\n */\n toBytes(format?: string): TRet<Uint8Array>;\n /**\n * Encode the signature into hex.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature hex.\n */\n toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n /** Create a signature from `r`, `s`, and an optional recovery bit. */\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n /**\n * Decode a signature from bytes.\n * @param bytes - Encoded signature bytes.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromBytes(bytes: TArg<Uint8Array>, format?: ECDSASignatureFormat): ECDSASignature;\n /**\n * Decode a signature from hex.\n * @param hex - Encoded signature hex.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet<Uint8Array> {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet<Uint8Array>;\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 * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: TArg<IField<T>>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp as IField<T>) as IField<T>;\n // Generic implementation\n const q = F.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 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.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 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && 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 * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: TArg<IField<T>>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n const F = validateField(Fp as IField<T>) as IField<T>;\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 \u00A76.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField<T>` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd) throw new Error('Field does not have .isOdd()');\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 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.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 = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths<T>(Fp: TArg<IField<T>>, Fn: TArg<IField<bigint>>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet<Uint8Array> }> = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n\n function isValidSecretKey(secretKey: TArg<Uint8Array>) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: TArg<Uint8Array>, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet<Uint8Array>;\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret 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(secretKey: TArg<Uint8Array>, isCompressed = true): TRet<Uint8Array> {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(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: TArg<Uint8Array>): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n if (!isBytes(item)) return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec) return undefined;\n return isPub;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed = true\n ): TRet<Uint8Array> {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: TArg<CHash>,\n ecdsaOpts: TArg<ECDSAOpts> = {}\n): ECDSA {\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash as CHash;\n ahash(hash_);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac =\n ecdsaOpts.hmac === undefined\n ? (key: TArg<Uint8Array>, msg: TArg<Uint8Array>) => nobleHmac(hash_, key, msg)\n : (ecdsaOpts.hmac as HmacFn);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertRecoverableCurve(): void {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: TArg<Uint8Array>, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: TArg<Uint8Array>,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint> {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\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 toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet<Uint8Array> {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet<Uint8Array>;\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet<Uint8Array>;\n }\n return concatBytes(rb, sb) as TRet<Uint8Array>;\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\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: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int === undefined\n ? function bits2int_def(bytes: TArg<Uint8Array>): bigint {\n // Our custom check \"just in case\", for protection against DoS\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 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : (ecdsaOpts.bits2int as (bytes: TArg<Uint8Array>) => bigint);\n const bits2int_modN: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes: TArg<Uint8Array>): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : (ecdsaOpts.bits2int_modN as (bytes: TArg<Uint8Array>) => bigint);\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): TRet<Uint8Array> {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num) as TRet<Uint8Array>;\n }\n\n function validateMsgAndHash(message: TArg<Uint8Array>, prehash: boolean): TRet<Uint8Array> {\n abytes(message, undefined, 'message');\n return (\n prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n ) as TRet<Uint8Array>;\n }\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 *\n * Warning: we cannot assume here that message 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 */\n function prepSig(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts>\n ) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 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(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs: TArg<Uint8Array>[] = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs) as TRet<Uint8Array>; // Step D of RFC6979 3.2\n const m = h1int; // 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 // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\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 function k2sig(kBytes: TArg<Uint8Array>): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\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 = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts> = {}\n ): TRet<Uint8Array> {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<Signature>(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * 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: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts: TArg<ECDSAVerifyOpts> = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts: TArg<ECDSARecoverOpts> = {}\n ): TRet<Uint8Array> {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport {\n createFROST,\n type FROST,\n type FrostPublic,\n type FrostSecret,\n type Nonces,\n} from './abstract/frost.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport {\n abytes,\n asciiToBytes,\n bytesToNumberBE,\n concatBytes,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts<bigint> = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\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 = secp256k1_CURVE.p;\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(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\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\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag: string, ...messages: TArg<Uint8Array[]>): TRet<Uint8Array> {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages)) as TRet<Uint8Array>;\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: TArg<PointType<bigint>>): TRet<Uint8Array> =>\n point.toBytes(true).slice(1) as TRet<Uint8Array>;\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: TArg<Uint8Array>) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { 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 const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args: TArg<Uint8Array[]>): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n return schnorrGetExtPubKey(secretKey).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 output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n auxRand: TArg<Uint8Array> = randomBytes(32)\n): TRet<Uint8Array> {\n const { Fn, BASE } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n if (k_ === 0n) throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const k = hasEven(p.y) ? k_ : Fn.neg(k_);\n const rx = pointToBytes(p);\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(Fn.toBytes(Fn.create(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 as TRet<Uint8Array>;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>\n): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\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 (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s)) return false;\n\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport const __TEST: { lift_x: typeof lift_x } = /* @__PURE__ */ Object.freeze({ lift_x });\n\n/** Schnorr-specific secp256k1 API from BIP340. */\nexport type SecpSchnorr = {\n /**\n * Generate one Schnorr secret/public keypair.\n * @param seed - Optional seed for deterministic testing or custom randomness.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n /**\n * Derive the x-only public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns X-only public key bytes.\n */\n getPublicKey: typeof schnorrGetPublicKey;\n /**\n * Create one BIP340 Schnorr signature.\n * @param message - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param auxRand - Optional auxiliary randomness.\n * @returns Compact Schnorr signature bytes.\n */\n sign: typeof schnorrSign;\n /**\n * Verify one BIP340 Schnorr signature.\n * @param signature - Compact signature bytes.\n * @param message - Signed message bytes.\n * @param publicKey - X-only public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: typeof schnorrVerify;\n /** Underlying secp256k1 point constructor. */\n Point: WeierstrassPointCons<bigint>;\n /** Helper utilities for Schnorr-specific key handling and tagged hashing. */\n utils: {\n /** Generate one Schnorr secret key. */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Convert one point into its x-only BIP340 byte encoding. */\n pointToBytes: (point: TArg<PointType<bigint>>) => TRet<Uint8Array>;\n /** Lift one x coordinate into the unique even-Y point. */\n lift_x: typeof lift_x;\n /** Compute a BIP340 tagged hash. */\n taggedHash: typeof taggedHash;\n };\n /** Public byte lengths for keys, signatures, and seeds. */\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\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 ))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nconst getMapSWU = () =>\n mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher: H2CHasher<WeierstrassPointCons<bigint>> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\n (scalars: bigint[]) => {\n const { x, y } = getMapSWU()(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 }\n ))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n }))();\n\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point: PointType<bigint>, merkleRoot?: TArg<Uint8Array>): bigint {\n if (merkleRoot === undefined) return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t)) throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub: TArg<FrostPublic>): TRet<FrostPublic> {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y)) return pub as TRet<FrostPublic>;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(\n Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])\n ),\n } as TRet<FrostPublic>;\n}\nfunction frostSecretToEvenY(s: TArg<FrostSecret>, pub: TArg<FrostPublic>): TRet<FrostSecret> {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y)) return s as TRet<FrostSecret>;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n } as TRet<FrostSecret>;\n}\nfunction frostNoncesToEvenY(PK: PointType<bigint>, nonces: TArg<Nonces>): TRet<Nonces> {\n if (hasEven(PK.y)) return nonces as TRet<Nonces>;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n } as TRet<Nonces>;\n}\n\nfunction frostTweakSecret(\n s: TArg<FrostSecret>,\n pub: TArg<FrostPublic>,\n merkleRoot?: TArg<Uint8Array>\n): TRet<FrostSecret> {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n } as TRet<FrostSecret>;\n}\n\nfunction frostTweakPublic(\n pub: TArg<FrostPublic>,\n merkleRoot?: TArg<Uint8Array>\n): TRet<FrostPublic> {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) =>\n (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes()\n );\n const verifyingShares: Record<string, Uint8Array> = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n } as TRet<FrostPublic>;\n}\n\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32) return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33) return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n: bigint) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1) as TRet<Uint8Array>,\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx) as TRet<Uint8Array>,\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n }))();\n", "import { secp256k1 as secp } from '@noble/curves/secp256k1.js'\nimport { sha256 } from 'multiformats/hashes/sha2'\nimport { SigningError, VerificationError } from '../../errors.js'\nimport { isPromise } from '../../util.js'\nimport type { AbortOptions } from '@libp2p/interface'\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.sign(digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new SigningError(String(err))\n })\n }\n\n try {\n return secp.sign(p.digest, key, {\n prehash: false,\n format: 'der'\n })\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, options?: AbortOptions): boolean | Promise<boolean> {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray())\n\n if (isPromise(p)) {\n return p\n .then(({ digest }) => {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, digest, key, {\n prehash: false,\n format: 'der'\n })\n })\n .catch(err => {\n if (err.name === 'AbortError') {\n throw err\n }\n\n throw new VerificationError(String(err))\n })\n }\n\n try {\n options?.signal?.throwIfAborted()\n return secp.verify(sig, p.digest, key, {\n prehash: false,\n format: 'der'\n })\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, AbortOptions } 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, options?: AbortOptions): boolean {\n return hashAndVerify(this._key, sig, data, options)\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, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.raw, message, options)\n }\n}\n", "import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js'\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 return secp.Point.fromBytes(key).toBytes()\n}\n\nexport function decompressSecp256k1PublicKey (key: Uint8Array): Uint8Array {\n return secp.Point.fromBytes(key).toBytes(false)\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.Point.fromBytes(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.randomSecretKey()\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 } 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 { MultibaseDecoder } from 'multiformats/cid'\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", "/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError'\n name = 'InvalidMultiaddrError'\n}\n\nexport class ValidationError extends Error {\n static name = 'ValidationError'\n name = 'ValidationError'\n}\n\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError'\n name = 'InvalidParametersError'\n}\n\nexport class UnknownProtocolError extends Error {\n static name = 'UnknownProtocolError'\n name = 'UnknownProtocolError'\n}\n", "/* eslint-disable @typescript-eslint/no-unsafe-return */\n\n// Heavily inspired by https://doc.rust-lang.org/src/std/net/parser.rs.html\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Fn = (...foo: any) => any;\n\nexport class Parser {\n private index = 0;\n private input = \"\";\n\n new(input: string): this {\n this.index = 0;\n this.input = input;\n return this;\n }\n\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically<T extends Fn>(fn: T): ReturnType<T> {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith<T extends Fn>(fn: T): ReturnType<T> | undefined {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n\n /** Peek the next character from the input */\n peekChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n\n /** Read the next character from the input */\n readChar(): string | undefined {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target: string): string | undefined {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator<T extends Fn>(sep: string, index: number, inner: T): ReturnType<T> {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(\n radix: number,\n maxDigits: number | undefined,\n allowZeroPrefix: boolean,\n maxBytes: number\n ): number | undefined {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n\n if (digitCount === 0) {\n return undefined;\n } else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n } else {\n return result;\n }\n });\n }\n\n /** Read an IPv4 address. */\n readIPv4Addr(): Uint8Array | undefined {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n\n return out;\n });\n }\n\n /** Read an IPv6 Address. */\n readIPv6Addr(): Uint8Array | undefined {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups: Uint8Array): [number, boolean] => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n\n return [ix + 4, true];\n }\n }\n\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n\n if (headSize === 16) {\n return head;\n }\n\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n\n return head;\n });\n }\n\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr(): Uint8Array | undefined {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n", "import { Parser } from \"./parser.js\";\n\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\n\nconst parser = new Parser();\n\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n\n/** Parse IPv4 `input` into IPv6 with IPv4-mapped bytes, eg ::ffff:1.2.3.4 */\nexport function parseIPv4Mapped(input: string): Uint8Array | undefined {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n\n const ipv4 = parser.new(input).parseWith(() => parser.readIPv4Addr());\n if (ipv4 === undefined) {\n return undefined;\n }\n\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, ipv4[0], ipv4[1], ipv4[2], ipv4[3]]);\n}\n\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input: string): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input: string, mapIPv4ToIPv6 = false): Uint8Array | undefined {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n\n const addr = parser.new(input).parseWith(() => parser.readIPAddr());\n if (!addr) {\n return undefined;\n }\n\n if (mapIPv4ToIPv6 && addr.length === 4) {\n return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, addr[0], addr[1], addr[2], addr[3]]);\n }\n\n return addr;\n}\n", "import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n\n/** Check if `input` is IPv4. */\nexport function isIPv4(input: string): boolean {\n return Boolean(parseIPv4(input));\n}\n\n/** Check if `input` is IPv6. */\nexport function isIPv6(input: string): boolean {\n return Boolean(parseIPv6(input));\n}\n\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input: string): boolean {\n return Boolean(parseIP(input));\n}\n\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input: string): 4 | 6 | undefined {\n if (isIPv4(input)) {\n return 4;\n } else if (isIPv6(input)) {\n return 6;\n } else {\n return undefined;\n }\n}\n", "import { isIPv4 } from '@chainsafe/is-ip'\nimport { base32 } from 'multiformats/bases/base32'\nimport { bases } from 'multiformats/basics'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport type { MultibaseCodec } from 'multiformats'\nimport type { SupportedEncodings } from 'uint8arrays/to-string'\n\nexport function bytesToString (base: SupportedEncodings): (buf: Uint8Array) => string {\n return (buf) => {\n return uint8ArrayToString(buf, base)\n }\n}\n\nexport function stringToBytes (base: SupportedEncodings): (value: string) => Uint8Array {\n return (buf) => {\n return uint8ArrayFromString(buf, base)\n }\n}\n\nexport function bytes2port (buf: Uint8Array): string {\n const view = new DataView(buf.buffer)\n return view.getUint16(buf.byteOffset).toString()\n}\n\nexport function port2bytes (port: string | number): Uint8Array {\n const buf = new ArrayBuffer(2)\n const view = new DataView(buf)\n view.setUint16(0, typeof port === 'string' ? parseInt(port) : port)\n\n return new Uint8Array(buf)\n}\n\nexport function onion2bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = uint8ArrayFromString(addr[0], 'base32')\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function onion32bytes (str: string): Uint8Array {\n const addr = str.split(':')\n\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`)\n }\n\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`)\n }\n\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`)\n\n // onion port number\n const port = parseInt(addr[1], 10)\n\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)')\n }\n\n const portBuf = port2bytes(port)\n\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length)\n}\n\nexport function bytes2onion (buf: Uint8Array): string {\n const addrBytes = buf.subarray(0, buf.length - 2)\n const portBytes = buf.subarray(buf.length - 2)\n const addr = uint8ArrayToString(addrBytes, 'base32')\n const port = bytes2port(portBytes)\n return `${addr}:${port}`\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip4ToBytes = function (ip: string): Uint8Array {\n ip = ip.toString().trim()\n\n const bytes = new Uint8Array(4)\n\n ip.split(/\\./g).forEach((byte, index) => {\n const value = parseInt(byte, 10)\n\n if (isNaN(value) || value < 0 || value > 0xff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[index] = value\n })\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const ip6ToBytes = function (ip: string): Uint8Array {\n let offset = 0\n ip = ip.toString().trim()\n\n const sections = ip.split(':', 8)\n\n let i\n for (i = 0; i < sections.length; i++) {\n const isv4 = isIPv4(sections[i])\n let v4Buffer: Uint8Array | undefined\n\n if (isv4) {\n v4Buffer = ip4ToBytes(sections[i])\n sections[i] = uint8ArrayToString(v4Buffer.subarray(0, 2), 'base16')\n }\n\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.subarray(2, 4), 'base16'))\n }\n }\n\n if (sections[0] === '') {\n while (sections.length < 8) { sections.unshift('0') }\n } else if (sections[sections.length - 1] === '') {\n while (sections.length < 8) { sections.push('0') }\n } else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++) { }\n const argv: [number, number, ...string[]] = [i, 1]\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0')\n }\n sections.splice.apply(sections, argv)\n }\n\n const bytes = new Uint8Array(offset + 16)\n\n for (i = 0; i < sections.length; i++) {\n if (sections[i] === '') {\n sections[i] = '0'\n }\n\n const word = parseInt(sections[i], 16)\n\n if (isNaN(word) || word < 0 || word > 0xffff) {\n throw new InvalidMultiaddrError('Invalid byte value in IP address')\n }\n\n bytes[offset++] = (word >> 8) & 0xff\n bytes[offset++] = word & 0xff\n }\n\n return bytes\n}\n\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const ip4ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 4) {\n throw new InvalidMultiaddrError('IPv4 address was incorrect length')\n }\n\n const result = []\n\n for (let i = 0; i < buf.byteLength; i++) {\n result.push(buf[i])\n }\n\n return result.join('.')\n}\n\nexport const ip6ToString = function (buf: Uint8Array): string {\n if (buf.byteLength !== 16) {\n throw new InvalidMultiaddrError('IPv6 address was incorrect length')\n }\n\n const result: string[] = []\n\n for (let i = 0; i < buf.byteLength; i += 2) {\n const byte1 = buf[i]\n const byte2 = buf[i + 1]\n\n const tuple = `${byte1.toString(16).padStart(2, '0')}${byte2.toString(16).padStart(2, '0')}`\n\n result.push(tuple)\n }\n\n const ip = result.join(':')\n\n try {\n const url = new URL(`http://[${ip}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${ip}\"`)\n }\n}\n\nexport function ip6StringToValue (str: string): string {\n try {\n const url = new URL(`http://[${str}]`)\n\n return url.hostname.substring(1, url.hostname.length - 1)\n } catch {\n throw new InvalidMultiaddrError(`Invalid IPv6 address \"${str}\"`)\n }\n}\n\nconst decoders = Object.values(bases).map((c) => c.decoder)\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1])\n decoders.slice(2).forEach((d) => (acc = acc.or(d)))\n return acc\n})()\n\nexport function mb2bytes (mbstr: string): Uint8Array {\n return anybaseDecoder.decode(mbstr)\n}\n\nexport function bytes2mb (base: MultibaseCodec<any>): (buf: Uint8Array) => string {\n return (buf) => {\n return base.encoder.encode(buf)\n }\n}\n", "import { ValidationError } from './errors.ts'\n\nexport function integer (value: string): void {\n const int = parseInt(value)\n\n if (int.toString() !== value) {\n throw new ValidationError('Value must be an integer')\n }\n}\n\nexport function positive (value: any): void {\n if (value < 0) {\n throw new ValidationError('Value must be a positive integer, or zero')\n }\n}\n\nexport function maxValue (max: number): (value: any) => void {\n return (value) => {\n if (value > max) {\n throw new ValidationError(`Value must be smaller than or equal to ${max}`)\n }\n }\n}\n\nexport function validate (...funcs: Array<(value: string) => void>): (value: string) => void {\n return (value) => {\n for (const fn of funcs) {\n fn(value)\n }\n }\n}\n\nexport const validatePort = validate(\n integer,\n positive,\n maxValue(65_535)\n)\n", "import { isIPv4, isIPv6 } from '@chainsafe/is-ip'\nimport { CID } from 'multiformats'\nimport { base64url } from 'multiformats/bases/base64'\nimport { CODE_CERTHASH, CODE_DCCP, CODE_DNS, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_GARLIC32, CODE_GARLIC64, CODE_HTTP, CODE_HTTP_PATH, CODE_HTTPS, CODE_IP4, CODE_IP6, CODE_IP6ZONE, CODE_IPCIDR, CODE_MEMORY, CODE_NOISE, CODE_ONION, CODE_ONION3, CODE_P2P, CODE_P2P_CIRCUIT, CODE_P2P_STARDUST, CODE_P2P_WEBRTC_DIRECT, CODE_P2P_WEBRTC_STAR, CODE_P2P_WEBSOCKET_STAR, CODE_QUIC, CODE_QUIC_V1, CODE_SCTP, CODE_SNI, CODE_TCP, CODE_TLS, CODE_UDP, CODE_UDT, CODE_UNIX, CODE_UTP, CODE_WEBRTC, CODE_WEBRTC_DIRECT, CODE_WEBTRANSPORT, CODE_WS, CODE_WSS } from './constants.ts'\nimport { UnknownProtocolError, ValidationError } from './errors.ts'\nimport { bytes2mb, bytes2onion, bytes2port, bytesToString, ip4ToBytes, ip4ToString, ip6StringToValue, ip6ToBytes, ip6ToString, mb2bytes, onion2bytes, onion32bytes, port2bytes, stringToBytes } from './utils.ts'\nimport { validatePort } from './validation.ts'\nimport type { Registry as RegistryInterface } from './index.ts'\n\nexport const V = -1\n\nexport interface ProtocolCodec {\n /**\n * A numeric code that will be used in the binary representation of the tuple.\n */\n code: number\n\n /**\n * A string name that will be used in the string representation of the addr.\n */\n name: string\n\n /**\n * Size defines the expected length of the address part of the tuple - valid\n * values are `-1` (or the `V` constant) for variable length (this will be\n * varint encoded in the binary representation), `0` for no address part or a\n * number that represents a fixed-length address.\n */\n size?: number\n\n /**\n * If specified this protocol codec will also be used to decode tuples with\n * these names from string multiaddrs.\n */\n aliases?: string[]\n\n /**\n * Where the multiaddr has been encoded as a string, decode the value if\n * necessary, unescaping any escaped values\n */\n stringToValue?(value: string): string\n\n /**\n * To encode the multiaddr as a string, escape any necessary values\n */\n valueToString?(value: string): string\n\n /**\n * To encode the multiaddr as bytes, convert the value to bytes\n */\n valueToBytes?(value: string): Uint8Array\n\n /**\n * To decode bytes to a multiaddr, convert the value bytes to a string\n */\n bytesToValue?(bytes: Uint8Array): string\n\n /**\n * Perform any necessary validation on the string value\n */\n validate?(value: string): void\n}\n\nclass Registry implements RegistryInterface {\n private protocolsByCode = new Map<number, ProtocolCodec>()\n private protocolsByName = new Map<string, ProtocolCodec>()\n\n getProtocol (key: string | number): ProtocolCodec {\n let codec: ProtocolCodec | undefined\n\n if (typeof key === 'string') {\n codec = this.protocolsByName.get(key)\n } else {\n codec = this.protocolsByCode.get(key)\n }\n\n if (codec == null) {\n throw new UnknownProtocolError(`Protocol ${key} was unknown`)\n }\n\n return codec\n }\n\n addProtocol (codec: ProtocolCodec): void {\n this.protocolsByCode.set(codec.code, codec)\n this.protocolsByName.set(codec.name, codec)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.set(alias, codec)\n })\n }\n\n removeProtocol (code: number): void {\n const codec = this.protocolsByCode.get(code)\n\n if (codec == null) {\n return\n }\n\n this.protocolsByCode.delete(codec.code)\n this.protocolsByName.delete(codec.name)\n\n codec.aliases?.forEach(alias => {\n this.protocolsByName.delete(alias)\n })\n }\n}\n\nexport const registry = new Registry()\n\nconst codecs: ProtocolCodec[] = [{\n code: CODE_IP4,\n name: 'ip4',\n size: 32,\n valueToBytes: ip4ToBytes,\n bytesToValue: ip4ToString,\n validate: (value) => {\n if (!isIPv4(value)) {\n throw new ValidationError(`Invalid IPv4 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_TCP,\n name: 'tcp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDP,\n name: 'udp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_DCCP,\n name: 'dccp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_IP6,\n name: 'ip6',\n size: 128,\n valueToBytes: ip6ToBytes,\n bytesToValue: ip6ToString,\n stringToValue: ip6StringToValue,\n validate: (value) => {\n if (!isIPv6(value)) {\n throw new ValidationError(`Invalid IPv6 address \"${value}\"`)\n }\n }\n}, {\n code: CODE_IP6ZONE,\n name: 'ip6zone',\n size: V\n}, {\n code: CODE_IPCIDR,\n name: 'ipcidr',\n size: 8,\n bytesToValue: bytesToString('base10'),\n valueToBytes: stringToBytes('base10')\n}, {\n code: CODE_DNS,\n name: 'dns',\n size: V\n}, {\n code: CODE_DNS4,\n name: 'dns4',\n size: V\n}, {\n code: CODE_DNS6,\n name: 'dns6',\n size: V\n}, {\n code: CODE_DNSADDR,\n name: 'dnsaddr',\n size: V\n}, {\n code: CODE_SCTP,\n name: 'sctp',\n size: 16,\n valueToBytes: port2bytes,\n bytesToValue: bytes2port,\n validate: validatePort\n}, {\n code: CODE_UDT,\n name: 'udt'\n}, {\n code: CODE_UTP,\n name: 'utp'\n}, {\n code: CODE_UNIX,\n name: 'unix',\n size: V,\n stringToValue: (str) => decodeURIComponent(str),\n valueToString: (val) => encodeURIComponent(val)\n}, {\n code: CODE_P2P,\n name: 'p2p',\n aliases: ['ipfs'],\n size: V,\n bytesToValue: bytesToString('base58btc'),\n valueToBytes: (val) => {\n if (val.startsWith('Q') || val.startsWith('1')) {\n return stringToBytes('base58btc')(val)\n }\n\n return CID.parse(val).multihash.bytes\n }\n}, {\n code: CODE_ONION,\n name: 'onion',\n size: 96,\n bytesToValue: bytes2onion,\n valueToBytes: onion2bytes\n}, {\n code: CODE_ONION3,\n name: 'onion3',\n size: 296,\n bytesToValue: bytes2onion,\n valueToBytes: onion32bytes\n}, {\n code: CODE_GARLIC64,\n name: 'garlic64',\n size: V\n}, {\n code: CODE_GARLIC32,\n name: 'garlic32',\n size: V\n}, {\n code: CODE_TLS,\n name: 'tls'\n}, {\n code: CODE_SNI,\n name: 'sni',\n size: V\n}, {\n code: CODE_NOISE,\n name: 'noise'\n}, {\n code: CODE_QUIC,\n name: 'quic'\n}, {\n code: CODE_QUIC_V1,\n name: 'quic-v1'\n}, {\n code: CODE_WEBTRANSPORT,\n name: 'webtransport'\n}, {\n code: CODE_CERTHASH,\n name: 'certhash',\n size: V,\n bytesToValue: bytes2mb(base64url),\n valueToBytes: mb2bytes\n}, {\n code: CODE_HTTP,\n name: 'http'\n}, {\n code: CODE_HTTP_PATH,\n name: 'http-path',\n size: V,\n stringToValue: (str) => `/${decodeURIComponent(str)}`,\n valueToString: (val) => encodeURIComponent(val.substring(1))\n}, {\n code: CODE_HTTPS,\n name: 'https'\n}, {\n code: CODE_WS,\n name: 'ws'\n}, {\n code: CODE_WSS,\n name: 'wss'\n}, {\n code: CODE_P2P_WEBSOCKET_STAR,\n name: 'p2p-websocket-star'\n}, {\n code: CODE_P2P_STARDUST,\n name: 'p2p-stardust'\n}, {\n code: CODE_P2P_WEBRTC_STAR,\n name: 'p2p-webrtc-star'\n}, {\n code: CODE_P2P_WEBRTC_DIRECT,\n name: 'p2p-webrtc-direct'\n}, {\n code: CODE_WEBRTC_DIRECT,\n name: 'webrtc-direct'\n}, {\n code: CODE_WEBRTC,\n name: 'webrtc'\n}, {\n code: CODE_P2P_CIRCUIT,\n name: 'p2p-circuit'\n}, {\n code: CODE_MEMORY,\n name: 'memory',\n size: V\n}]\n\ncodecs.forEach(codec => {\n registry.addProtocol(codec)\n})\n", "import * as varint from 'uint8-varint'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidMultiaddrError } from './errors.ts'\nimport { registry, V } from './registry.ts'\nimport type { Component } from './index.js'\nimport type { ProtocolCodec } from './registry.ts'\n\nexport function bytesToComponents (bytes: Uint8Array): Component[] {\n const components: Component[] = []\n\n let i = 0\n while (i < bytes.length) {\n const code = varint.decode(bytes, i)\n const codec = registry.getProtocol(code)\n const codeLength = varint.encodingLength(code)\n const size = sizeForAddr(codec, bytes, i + codeLength)\n let sizeLength = 0\n\n if (size > 0 && codec.size === V) {\n sizeLength = varint.encodingLength(size)\n }\n\n const componentLength = codeLength + sizeLength + size\n\n const component: Component = {\n code,\n name: codec.name,\n bytes: bytes.subarray(i, i + componentLength)\n }\n\n if (size > 0) {\n const valueOffset = i + codeLength + sizeLength\n const valueBytes = bytes.subarray(valueOffset, valueOffset + size)\n\n component.value = codec.bytesToValue?.(valueBytes) ?? uint8ArrayToString(valueBytes)\n }\n\n components.push(component)\n\n i += componentLength\n }\n\n return components\n}\n\nexport function componentsToBytes (components: Component[]): Uint8Array {\n let length = 0\n const bytes: Uint8Array[] = []\n\n for (const component of components) {\n if (component.bytes == null) {\n const codec = registry.getProtocol(component.code)\n const codecLength = varint.encodingLength(component.code)\n let valueBytes: Uint8Array | undefined\n let valueLength = 0\n let valueLengthLength = 0\n\n if (component.value != null) {\n valueBytes = codec.valueToBytes?.(component.value) ?? uint8ArrayFromString(component.value)\n valueLength = valueBytes.byteLength\n\n if (codec.size === V) {\n valueLengthLength = varint.encodingLength(valueLength)\n }\n }\n\n const bytes = new Uint8Array(codecLength + valueLengthLength + valueLength)\n\n // encode the protocol code\n let offset = 0\n varint.encodeUint8Array(component.code, bytes, offset)\n offset += codecLength\n\n // if there is a value\n if (valueBytes != null) {\n // if the value has variable length, encode the length\n if (codec.size === V) {\n varint.encodeUint8Array(valueLength, bytes, offset)\n offset += valueLengthLength\n }\n\n // finally encode the value\n bytes.set(valueBytes, offset)\n }\n\n component.bytes = bytes\n }\n\n bytes.push(component.bytes)\n length += component.bytes.byteLength\n }\n\n return uint8ArrayConcat(bytes, length)\n}\n\nexport function stringToComponents (string: string): Component[] {\n if (string.charAt(0) !== '/') {\n throw new InvalidMultiaddrError('String multiaddr must start with \"/\"')\n }\n\n const components: Component[] = []\n let collecting: 'protocol' | 'value' = 'protocol'\n let value = ''\n let protocol = ''\n\n for (let i = 1; i < string.length; i++) {\n const char = string.charAt(i)\n\n if (char !== '/') {\n if (collecting === 'protocol') {\n protocol += string.charAt(i)\n } else {\n value += string.charAt(i)\n }\n }\n\n const ended = i === string.length - 1\n\n if (char === '/' || ended) {\n const codec = registry.getProtocol(protocol)\n\n if (collecting === 'protocol') {\n if (codec.size == null || codec.size === 0) {\n // a protocol without an address, eg. `/tls`\n components.push({\n code: codec.code,\n name: codec.name\n })\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n\n continue\n } else if (ended) {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n // continue collecting value\n collecting = 'value'\n } else if (collecting === 'value') {\n const component: Component = {\n code: codec.code,\n name: codec.name\n }\n\n if (codec.size != null && codec.size !== 0) {\n if (value === '') {\n throw new InvalidMultiaddrError(`Component ${protocol} was missing value`)\n }\n\n component.value = codec.stringToValue?.(value) ?? value\n }\n\n components.push(component)\n\n value = ''\n protocol = ''\n collecting = 'protocol'\n }\n }\n }\n\n if (protocol !== '' && value !== '') {\n throw new InvalidMultiaddrError('Incomplete multiaddr')\n }\n\n return components\n}\n\nexport function componentsToString (components: Component[]): string {\n return `/${components.flatMap(component => {\n if (component.value == null) {\n return component.name\n }\n\n const codec = registry.getProtocol(component.code)\n\n if (codec == null) {\n throw new InvalidMultiaddrError(`Unknown protocol code ${component.code}`)\n }\n\n return [\n component.name,\n codec.valueToString?.(component.value) ?? component.value\n ]\n }).join('/')}`\n}\n\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr (codec: ProtocolCodec, bytes: Uint8Array, offset: number): number {\n if (codec.size == null || codec.size === 0) {\n return 0\n }\n\n if (codec.size > 0) {\n return codec.size / 8\n }\n\n return varint.decode(bytes, offset)\n}\n", "import { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { bytesToComponents, componentsToBytes, componentsToString, stringToComponents } from './components.js'\nimport { InvalidMultiaddrError, InvalidParametersError } from './errors.ts'\nimport { registry } from './registry.ts'\nimport { isMultiaddr } from './index.js'\nimport type { MultiaddrInput, Multiaddr as MultiaddrInterface, Component } from './index.js'\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom')\nexport const symbol = Symbol.for('@multiformats/multiaddr')\n\nfunction toComponents (addr: MultiaddrInput): Component[] {\n if (addr == null) {\n addr = '/'\n }\n\n if (isMultiaddr(addr)) {\n return addr.getComponents()\n }\n\n if (addr instanceof Uint8Array) {\n return bytesToComponents(addr)\n }\n\n if (typeof addr === 'string') {\n addr = addr\n .replace(/\\/(\\/)+/, '/')\n .replace(/(\\/)+$/, '')\n\n if (addr === '') {\n addr = '/'\n }\n\n return stringToComponents(addr)\n }\n\n if (Array.isArray(addr)) {\n return addr\n }\n\n throw new InvalidMultiaddrError('Must be a string, Uint8Array, Component[], or another Multiaddr')\n}\n\ninterface MultiaddrOptions {\n validate?: boolean\n}\n\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr implements MultiaddrInterface {\n [symbol]: boolean = true\n readonly #components: Component[]\n\n // cache string representation\n #string: string | undefined\n // cache byte representation\n #bytes: Uint8Array | undefined\n\n constructor (addr: MultiaddrInput | Component[] = '/', options: MultiaddrOptions = {}) {\n this.#components = toComponents(addr)\n\n if (options.validate !== false) {\n validate(this)\n }\n }\n\n get bytes (): Uint8Array {\n if (this.#bytes == null) {\n this.#bytes = componentsToBytes(this.#components)\n }\n\n return this.#bytes\n }\n\n toString (): string {\n if (this.#string == null) {\n this.#string = componentsToString(this.#components)\n }\n\n return this.#string\n }\n\n toJSON (): string {\n return this.toString()\n }\n\n getComponents (): Component[] {\n return [\n ...this.#components.map(c => ({ ...c }))\n ]\n }\n\n encapsulate (addr: MultiaddrInput): MultiaddrInterface {\n const ma = new Multiaddr(addr)\n\n return new Multiaddr([\n ...this.#components,\n ...ma.getComponents()\n ], {\n validate: false\n })\n }\n\n decapsulate (addr: Multiaddr | string): MultiaddrInterface {\n const addrString = addr.toString()\n const s = this.toString()\n const i = s.lastIndexOf(addrString)\n\n if (i < 0) {\n throw new InvalidParametersError(`Address ${this.toString()} does not contain subaddress: ${addrString}`)\n }\n\n return new Multiaddr(s.slice(0, i), {\n validate: false\n })\n }\n\n decapsulateCode (code: number): Multiaddr {\n let index\n\n for (let i = this.#components.length - 1; i > -1; i--) {\n if (this.#components[i].code === code) {\n index = i\n break\n }\n }\n\n return new Multiaddr(this.#components.slice(0, index), {\n validate: false\n })\n }\n\n equals (addr: { bytes: Uint8Array }): boolean {\n return uint8ArrayEquals(this.bytes, addr.bytes)\n }\n\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect] (): string {\n return `Multiaddr(${this.toString()})`\n }\n}\n\n/**\n * Ensures all multiaddr tuples are correct. Throws if any invalid protocols or\n * values are encountered.\n */\nexport function validate (addr: Multiaddr): void {\n addr.getComponents()\n .forEach(component => {\n const codec = registry.getProtocol(component.code)\n\n if (component.value == null) {\n return\n }\n\n codec.validate?.(component.value)\n })\n}\n", "/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // <Uint8Array 04 7f 00 00 01 11 04 d2>\n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.getComponents()\n * // [\n * // { code: 4, name: 'ip4', value: '127.0.0.1' },\n * // { code: 273, name: 'udp', value: '1234' }\n * // ]\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * @example Adding custom protocols\n *\n * To add application-specific or experimental protocols, add a protocol codec\n * to the protocol registry:\n *\n * ```ts\n * import { registry, V, multiaddr } from '@multiformats/multiaddr'\n * import type { ProtocolCodec } from '@multiformats/multiaddr'\n *\n * const maWithCustomTuple = '/custom-protocol/hello'\n *\n * // throws UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * const protocol: ProtocolCodec = {\n * code: 2059,\n * name: 'custom-protocol',\n * size: V\n * // V means variable length, can also be 0, a positive integer (e.g. a fixed\n * // length or omitted\n * }\n *\n * registry.addProtocol(protocol)\n *\n * // does not throw UnknownProtocolError\n * multiaddr(maWithCustomTuple)\n *\n * // protocols can also be removed\n * registry.removeProtocol(protocol.code)\n * ```\n */\n\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js'\nimport { registry, V } from './registry.ts'\nimport type { ProtocolCodec } from './registry.ts'\n\n/**\n * The protocol registry stores protocol codecs that allow transformation of\n * multiaddr tuples from bytes to string and back again, and also validation of\n * the address values.\n */\nexport interface Registry {\n /**\n * Retrieve a protocol definition by it's code or name\n */\n getProtocol (key: string | number): ProtocolCodec\n\n /**\n * Add a new protocol definition\n */\n addProtocol (codec: ProtocolCodec): void\n\n /**\n * Remove a protocol definition by it's code\n */\n removeProtocol (code: number): void\n}\n\n/**\n * These types can be parsed into a {@link Multiaddr} object\n */\nexport type MultiaddrInput = string | Multiaddr | Uint8Array | null | Component[]\n\n/**\n * A Component is a section of a multiaddr with a name/code, possibly with a\n * value.\n *\n * Component names/codes are defined in the protocol table.\n *\n * @see https://github.com/multiformats/multiaddr/blob/master/protocols.csv\n */\nexport interface Component {\n /**\n * The code of the component as defined in the protocol table\n */\n code: number\n\n /**\n * The name of the component as defined in the protocol table\n */\n name: string\n\n /**\n * The component value, if one is present\n */\n value?: string\n\n /**\n * The bytes that make up the component. This will be set if the multiaddr\n * was parsed from a `Uint8Array`, or if `.bytes` has been accessed on it.\n */\n bytes?: Uint8Array\n}\n\nexport interface Multiaddr {\n bytes: Uint8Array\n\n /**\n * Returns Multiaddr as a String\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').toString()\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toString(): string\n\n /**\n * Returns Multiaddr as a JSON encoded object\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * JSON.stringify(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // '/ip4/127.0.0.1/tcp/4001'\n * ```\n */\n toJSON(): string\n\n /**\n * Returns the components that make up this Multiaddr\n *\n * @example\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001').getComponents()\n * // [{ name: 'ip4', code: 4, value: '127.0.0.1' }, { name: 'tcp', code: 6, value: '4001' }]\n * ```\n */\n getComponents(): Component[]\n\n /**\n * Encapsulates a Multiaddr in another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.toString()\n * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001'\n * ```\n *\n * @param {MultiaddrInput} addr - Multiaddr to add into this Multiaddr\n */\n encapsulate(addr: MultiaddrInput): Multiaddr\n\n /**\n * Decapsulates a Multiaddr from another Multiaddr\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * const mh3 = mh1.encapsulate(mh2)\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001)\n *\n * mh3.decapsulate(mh2).toString()\n * // '/ip4/8.8.8.8/tcp/1080'\n * ```\n *\n * @param {Multiaddr | string} addr - Multiaddr to remove from this Multiaddr\n */\n decapsulate(addr: Multiaddr | string): Multiaddr\n\n /**\n * A more reliable version of `decapsulate` if you are targeting a specific\n * code, such as 421 (the `p2p` protocol code). The last index of the code\n * will be removed from the `Multiaddr`, and a new instance will be returned.\n * If the code is not present, the original `Multiaddr` is returned.\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')\n * // Multiaddr(/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC)\n *\n * addr.decapsulateCode(421).toString()\n * // '/ip4/0.0.0.0/tcp/8080'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()\n * // '/ip4/127.0.0.1/tcp/8080'\n * ```\n */\n decapsulateCode(code: number): Multiaddr\n\n /**\n * Checks if two Multiaddrs are the same\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const mh1 = multiaddr('/ip4/8.8.8.8/tcp/1080')\n * // Multiaddr(/ip4/8.8.8.8/tcp/1080)\n *\n * const mh2 = multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n *\n * mh1.equals(mh1)\n * // true\n *\n * mh1.equals(mh2)\n * // false\n * ```\n */\n equals(addr: { bytes: Uint8Array }): boolean\n}\n\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr (value: any): value is Multiaddr {\n return Boolean(value?.[symbol])\n}\n\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr (addr?: MultiaddrInput): Multiaddr {\n return new MultiaddrClass(addr)\n}\n\n/**\n * Export all table.csv codes. These are all named exports so can be tree-shaken\n * out by bundlers.\n */\nexport * from './constants.ts'\nexport { registry, V }\nexport type { ProtocolCodec }\n", "import type { Matcher, MultiaddrMatcher } from './index.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * Matches a multiaddr component with the specified code but no value\n */\nexport const code = (code: number): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component == null) {\n return false\n }\n\n if (component.code !== code) {\n return false\n }\n\n if (component.value != null) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const value = (code: number, value?: string): Matcher => {\n return {\n match: (vals) => {\n const component = vals[0]\n\n if (component?.code !== code) {\n return false\n }\n\n if (component.value == null) {\n return false\n }\n\n if (value != null && component.value !== value) {\n return false\n }\n\n return vals.slice(1)\n }\n }\n}\n\n/**\n * Matches a multiaddr component with the specified code and value. If the value\n * is omitted any non-undefined value is matched.\n */\nexport const not = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return false\n }\n }\n}\n\n/**\n * An optional matcher\n */\nexport const optional = (matcher: Matcher): Matcher => {\n return {\n match: (vals) => {\n const result = matcher.match(vals)\n\n if (result === false) {\n return vals\n }\n\n return result\n }\n }\n}\n\n/**\n * Matches any one of the passed matches\n */\nexport const or = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n let matches: Component[] | undefined\n\n for (const matcher of matchers) {\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n continue\n }\n\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result\n }\n }\n\n if (matches == null) {\n return false\n }\n\n return matches\n }\n }\n}\n\n/**\n * Matches all of the passed matchers\n */\nexport const and = (...matchers: Matcher[]): Matcher => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals)\n\n // no match\n if (result === false) {\n return false\n }\n\n vals = result\n }\n\n return vals\n }\n }\n}\n\n/**\n * Create a multiaddr matcher from the passed component matchers\n */\nexport function fmt (...matchers: Matcher[]): MultiaddrMatcher {\n function match (ma?: Multiaddr): Component[] | false {\n if (ma == null) {\n return false\n }\n\n let parts = ma.getComponents()\n\n for (const matcher of matchers) {\n const result = matcher.match(parts)\n\n if (result === false) {\n return false\n }\n\n parts = result\n }\n\n return parts\n }\n\n function matches (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n return result !== false\n }\n\n function exactMatch (ma?: Multiaddr): boolean {\n const result = match(ma)\n\n if (result === false) {\n return false\n }\n\n return result.length === 0\n }\n\n return {\n matchers,\n matches,\n exactMatch\n }\n}\n", "/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\nimport { CODE_P2P, CODE_DNS4, CODE_DNS6, CODE_DNSADDR, CODE_DNS, CODE_IP4, CODE_IP6, CODE_TCP, CODE_UDP, CODE_QUIC, CODE_QUIC_V1, CODE_WS, CODE_WSS, CODE_TLS, CODE_SNI, CODE_WEBRTC_DIRECT, CODE_CERTHASH, CODE_WEBTRANSPORT, CODE_P2P_CIRCUIT, CODE_WEBRTC, CODE_HTTP, CODE_UNIX, CODE_HTTPS, CODE_MEMORY, CODE_IP6ZONE, CODE_IPCIDR, CODE_HTTP_PATH } from '@multiformats/multiaddr'\nimport { and, or, optional, fmt, code, value, not } from './utils.js'\nimport type { Multiaddr, Component } from '@multiformats/multiaddr'\n\n/**\n * A matcher accepts multiaddr components and either fails to match and returns\n * false or returns a sublist of unmatched components\n */\nexport interface Matcher {\n match(parts: Component[]): Component[] | false\n}\n\n/**\n * A MultiaddrMatcher allows interpreting a multiaddr as a certain type of\n * multiaddr\n */\nexport interface MultiaddrMatcher {\n /**\n * The matchers that make up this MultiaddrMatcher - useful if you want to\n * make your own custom matchers\n */\n matchers: Matcher[]\n\n /**\n * Returns true if the passed multiaddr can be treated as this type of\n * multiaddr\n */\n matches(ma?: Multiaddr): boolean\n\n /**\n * Returns true if the passed multiaddr terminates as this type of\n * multiaddr\n */\n exactMatch(ma?: Multiaddr): boolean\n}\n\n/**\n * Matches PeerId addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { PEER_ID } from '@multiformats/multiaddr-matcher'\n *\n * PEER_ID.matches(multiaddr('/p2p/Qmfoo')) // true\n * PEER_ID.matches(multiaddr('/ipfs/Qmfoo')) // true\n * ```\n */\nconst _PEER_ID = value(CODE_P2P)\n\nexport const PEER_ID = fmt(_PEER_ID)\n\n/**\n * DNS matchers\n */\nconst _DNS4 = value(CODE_DNS4)\nconst _DNS6 = value(CODE_DNS6)\nconst _DNSADDR = value(CODE_DNSADDR)\nconst _DNS = value(CODE_DNS)\n\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(value(CODE_P2P)))\n\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(value(CODE_P2P)))\n\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(value(CODE_P2P)))\n\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))\n\nconst _IP4 = and(\n value(CODE_IP4),\n optional(value(CODE_IPCIDR))\n)\nconst _IP6 = and(\n optional(value(CODE_IP6ZONE)),\n value(CODE_IP6),\n optional(value(CODE_IPCIDR))\n)\nconst _IP = or(_IP4, _IP6)\n\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR)\n\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(value(CODE_P2P)))))\n\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4)\n\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6)\n\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP)\n\nconst _TCP = and(_IP_OR_DOMAIN, value(CODE_TCP))\nconst _UDP = and(_IP_OR_DOMAIN, value(CODE_UDP))\n\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(value(CODE_P2P))))\n\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP)\n\nconst _QUIC = and(_UDP, code(CODE_QUIC), optional(value(CODE_P2P)))\nconst _QUIC_V1 = and(_UDP, code(CODE_QUIC_V1), optional(value(CODE_P2P)))\n\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUIC_V1)\n\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC)\n\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC_V1 } from '@multiformats/multiaddr-matcher'\n *\n * QUIC_V1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUIC_V1 = fmt(_QUIC_V1)\n\nconst _WEB = or(\n _IP_OR_DOMAIN,\n _TCP,\n _UDP,\n _QUIC,\n _QUIC_V1\n)\n\nconst _WebSockets = or(\n and(_WEB, code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets)\n\nconst _WebSocketsSecure = or(\n and(_WEB, code(CODE_WSS), optional(value(CODE_P2P))),\n and(_WEB, code(CODE_TLS), optional(value(CODE_SNI)), code(CODE_WS), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure)\n\nconst _WebRTCDirect = and(_UDP, code(CODE_WEBRTC_DIRECT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect)\n\nconst _WebTransport = and(_QUIC_V1, code(CODE_WEBTRANSPORT), optional(value(CODE_CERTHASH)), optional(value(CODE_CERTHASH)), optional(value(CODE_P2P)))\n\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport)\n\nconst _P2P = or(\n _WebSockets,\n _WebSocketsSecure,\n and(_TCP, optional(value(CODE_P2P))),\n and(QUIC_V0_OR_V1, optional(value(CODE_P2P))),\n and(_IP_OR_DOMAIN, optional(value(CODE_P2P))),\n _WebRTCDirect,\n _WebTransport,\n value(CODE_P2P)\n)\n\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P)\n\nconst _Circuit = and(optional(_P2P), code(CODE_P2P_CIRCUIT), not(code(CODE_WEBRTC)), optional(value(CODE_P2P)))\n\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit)\n\nconst _WebRTC = or(\n and(_P2P, code(CODE_P2P_CIRCUIT), code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(_P2P, code(CODE_WEBRTC), optional(value(CODE_P2P))),\n and(code(CODE_WEBRTC), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC)\n\nconst _HTTP = and(_IP_OR_DOMAIN, or(\n and(value(CODE_TCP, '80')),\n and(value(CODE_TCP), code(CODE_HTTP)),\n code(CODE_HTTP)\n), optional(value(CODE_HTTP_PATH)), optional(value(CODE_P2P))\n)\n\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP)\n\nconst _HTTPS = and(_IP_OR_DOMAIN, or(\n and(value(CODE_TCP, '443')),\n and(value(CODE_TCP, '443'), code(CODE_HTTP)),\n and(value(CODE_TCP), code(CODE_HTTPS)),\n and(value(CODE_TCP), code(CODE_TLS), code(CODE_HTTP)),\n and(code(CODE_TLS), code(CODE_HTTP)),\n code(CODE_TLS),\n code(CODE_HTTPS)\n), optional(value(CODE_HTTP_PATH)), optional(value(CODE_P2P))\n)\n\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS)\n\nconst _Memory = or(\n and(value(CODE_MEMORY), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nexport const Memory = fmt(_Memory)\n\nconst _Unix = or(\n and(value(CODE_UNIX), optional(value(CODE_P2P)))\n)\n\n/**\n * Matches Unix addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Unix } from '@multiformats/multiaddr-matcher'\n *\n * Unix.matches(multiaddr('/unix/%2Fpath%2Fto%2Funix.socket')) // true\n * ```\n */\nexport const Unix = fmt(_Unix)\n"],
|
|
5
|
+
"mappings": ";idAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,eAAAE,KCyCM,IAAOC,GAAP,cAAsC,KAAK,CAC/C,OAAO,KAAO,yBAEd,YAAaC,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,wBACd,GAMWC,GAAP,cAAqC,KAAK,CAC9C,OAAO,KAAO,wBAEd,YAAaD,EAAU,qBAAoB,CACzC,MAAMA,CAAO,EACb,KAAK,KAAO,uBACd,GAkKI,IAAOE,GAAP,cAA+B,KAAK,CACxC,OAAO,KAAO,kBAEd,YAAaC,EAAU,cAAa,CAClC,MAAMA,CAAO,EACb,KAAK,KAAO,iBACd,GAMWC,GAAP,cAAqC,KAAK,CAC9C,OAAO,KAAO,wBAEd,YAAaD,EAAU,oBAAmB,CACxC,MAAMA,CAAO,EACb,K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AElB,EAEH,KAAK,MAAQH,CACf,CAES,CAACO,EAAmB,EAAI,KAExB,CAAC,OAAO,WAAW,EAAI,oBAEvB,CAACC,EAAmB,EAAc,CACzC,0BAGF,WAAS,CACP,MAAO,EAAQ,KAAK,KACtB,CAKA,OAAK,CACC,KAAK,UAAS,IAIlB,KAAK,IAAI,mEAAoE,KAAK,OAAO,EACzF,KAAK,MAAQ,WAAW,IAAK,CACtB,KAAK,wBAAuB,EAC9B,MAAMC,GAAM,CACX,KAAK,IAAI,MAAM,0CAA2CA,CAAG,CAC/D,CAAC,CACL,EAAG,KAAK,OAAO,EACjB,CAKA,MAAM,yBAAuB,CAC3B,GAAI,KAAK,OAAS,KAIlB,QAAWC,KAAY,KAAK,KAAM,CAYhC,GAXA,MAAM,KAAK,WAAW,UAAU,MAAMA,EAAS,GAAI,CACjD,KAAM,CACJ,CAAC,KAAK,MAAM,SAAWhB,EAA0B,EAAG,CAClD,MAAO,KAAK,MAAM,UAAYC,GAC9B,IAAK,KAAK,MAAM,SAGpB,WAAYe,EAAS,WACtB,EAGG,KAAK,OAAS,KAChB,OAGF,KAAK,kBAAkB,OAAQ,CAAE,OAAQA,CAAQ,CAAE,EACnD,KAAK,WAAW,kBAAkB,eAAeA,EAAS,EAAE,EACzD,MAAMD,GAAM,CACX,KAAK,IAAI,MAAM,wCAAyCC,EAAS,GAAID,CAAG,CAC1E,CAAC,CACL,CACF,CAKA,MAAI,CACE,KAAK,OAAS,MAChB,aAAa,KAAK,KAAK,EAGzB,KAAK,MAAQ,MACf,GAGI,SAAUE,GAAWC,EAAmB,CAC5C,OAAQb,GAAoC,IAAIF,GAAUE,EAAYa,CAAI,CAC5E",
|
|
6
|
+
"names": ["index_exports", "__export", "bootstrap", "InvalidParametersError", "message", "InvalidPublicKeyError", "InvalidCIDError", "message", "InvalidMultihashError", "UnsupportedKeyTypeError", "message", "peerDiscoverySymbol", "peerIdSymbol", "isEventObject", "obj", "isOnce", "options", "TypedEventEmitter", "#listeners", "type", "listeners", "listener", "once", "evt", "list", "callback", "detail", "serviceCapabilities", "base58_exports", "__export", "base58btc", "base58flickr", "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", "alphabetIdx", "bitsPerChar", "end", "out", "bits", "buffer", "written", "i", "value", "data", "pad", "mask", "createAlphabetIdx", "rfc4648", "base58btc", "baseX", "base58flickr", "base32_exports", "__export", "base32", "base32hex", "base32hexpad", "base32hexpadupper", "base32hexupper", "base32pad", "base32padupper", "base32upper", "base32z", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "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", "options", "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", "chunk", "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", "base64_exports", "__export", "base64", "base64pad", "base64url", "base64urlpad", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "base8_exports", "__export", "base8", "base8", "rfc4648", "identity_exports", "__export", "identity", "identity", "from", "buf", "toString", "str", "fromString", "textEncoder", "textDecoder", "sha2_browser_exports", "__export", "sha256", "sha512", "DEFAULT_MIN_DIGEST_LENGTH", "from", "name", "code", "encode", "minDigestLength", "maxDigestLength", "Hasher", "input", "options", "result", "createDigest", "digest", "truncate", "create", "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", "i", "entries", "result", "start", "end", "vals", "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", "options", "publicKey", "result", "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", "options", "hashAndVerify", "isBytes", "a", "anumber", "n", "title", "prefix", "abytes", "value", "length", "bytes", "len", "needsLen", "ofLen", "got", "message", "ahash", "h", "anumber", "aexists", "instance", "checkFinished", "aoutput", "out", "abytes", "min", "clean", "arrays", "i", "createView", "arr", "rotr", "word", "shift", "hasHexBuiltin", "hexes", "_", "i", "bytesToHex", "bytes", "abytes", "hex", "asciis", "asciiToBase16", "ch", "hexToBytes", "error", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "concatBytes", "arrays", "sum", "i", "a", "abytes", "res", "pad", "createHasher", "hashCons", "info", "hashC", "msg", "opts", "tmp", "randomBytes", "bytesLength", "anumber", "cr", "oidNist", "suffix", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "createView", "data", "aexists", "abytes", "view", "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", "i", "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", "SHA2_32B", "HashMD", "outputLen", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "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", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "abytes", "value", "length", "title", "anumber", "bytesToHex", "concatBytes", "arrays", "hexToBytes", "hex", "isBytes", "randomBytes", "bytesLength", "_0n", "_1n", "abool", "prefix", "abignumber", "n", "isPosBig", "asafenumber", "numberToHexUnpadded", "num", "hexToNumber", "bytesToNumberBE", "bytes", "bytesToNumberLE", "copyBytes", "numberToBytesBE", "len", "numberToBytesLE", "equalBytes", "a", "b", "abytes", "diff", "i", "copyBytes", "bytes", "asciiToBytes", "ascii", "c", "charCode", "isPosBig", "n", "_0n", "inRange", "min", "max", "aInRange", "title", "bitLen", "len", "_1n", "bitMask", "n", "_1n", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "anumber", "u8n", "len", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "i", "reset", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "val", "current", "iter", "f", "notImplemented", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_7n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow2", "x", "power", "modulo", "_0n", "res", "invert", "number", "a", "mod", "b", "y", "_1n", "u", "v", "q", "r", "m", "n", "assertIsSquare", "Fp", "root", "F", "sqrt3mod4", "p1div4", "_4n", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "_2n", "nv", "i", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "t_tmp", "exponent", "FpSqrt", "_9n", "isNegativeLE", "num", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "asafenumber", "FpPow", "p", "d", "FpInvertBatch", "nums", "passZero", "inverted", "multipliedAcc", "acc", "invertedAcc", "FpLegendre", "Fp", "n", "F", "p1mod2", "_1n", "_2n", "powered", "yes", "zero", "no", "nLength", "n", "nBitLength", "anumber", "_0n", "bits", "bitLen", "_nBitLength", "nByteLength", "FIELD_SQRT", "_Field", "_1n", "ORDER", "opts", "_nbitLength", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "sqrt", "FpSqrt", "numberToBytesLE", "numberToBytesBE", "bytes", "skipValidation", "abytes", "allowedLengths", "BYTES", "isLE", "modFromBytes", "padded", "scalar", "bytesToNumberLE", "bytesToNumberBE", "lst", "FpInvertBatch", "a", "b", "condition", "abool", "Field", "getFieldBytesLength", "fieldOrder", "_1n", "bitLength", "bitLen", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "num", "bytesToNumberLE", "bytesToNumberBE", "reduced", "mod", "numberToBytesLE", "numberToBytesBE", "_0n", "_1n", "negateCt", "condition", "item", "neg", "normalizeZ", "c", "points", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "calcWOpts", "scalarBits", "windows", "windowSize", "maxNumber", "mask", "bitMask", "shiftBy", "calcOffsets", "n", "window", "wOpts", "wbits", "nextN", "_1n", "offsetStart", "offset", "isZero", "isNeg", "isNegF", "pointPrecomputes", "pointWindowSizes", "getW", "P", "assert0", "n", "_0n", "wNAF", "Point", "bits", "elm", "p", "d", "_1n", "point", "W", "windows", "windowSize", "calcWOpts", "points", "base", "window", "i", "precomputes", "f", "wo", "nextN", "offset", "isZero", "isNeg", "isNegF", "offsetF", "calcOffsets", "negateCt", "acc", "item", "transform", "comp", "scalar", "prev", "validateW", "mulEndoUnsafe", "k1", "k2", "p1", "p2", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "p", "val", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "_0n", "_1n", "_2n", "_8n", "isEdValidXY", "Fp", "CURVE", "x", "y", "x2", "y2", "left", "right", "edwards", "params", "extraOpts", "opts", "validated", "createCurveFields", "Fn", "cofactor", "validateObject", "MASK", "modP", "n", "uvRatio", "u", "v", "acoord", "title", "banZero", "min", "aInRange", "aedpoint", "other", "Point", "X", "Y", "Z", "T", "p", "bytes", "zip215", "len", "a", "d", "copyBytes", "abytes", "abool", "normed", "lastByte", "bytesToNumberLE", "max", "isValid", "isXOdd", "isLastByteOdd", "hex", "hexToBytes", "windowSize", "isLazy", "wnaf", "X2", "Y2", "Z2", "Z4", "aX2", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "F", "scalar", "f", "normalizeZ", "invertedZ", "iz", "is0", "zz", "bytesToHex", "wNAF", "PrimeEdwardsPoint", "ep", "_bytes", "notImplemented", "_hex", "eddsa", "cHash", "eddsaOpts", "hash", "prehash", "BASE", "outputLen", "expectedLen", "asafenumber", "randomBytes", "adjustScalarBytes", "domain", "data", "ctx", "phflag", "modN_LE", "getPrivateScalar", "key", "lengths", "hashed", "head", "prefix", "getExtendedPublicKey", "secretKey", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "rs", "verifyOpts", "verify", "sig", "publicKey", "mid", "SB", "_size", "randomSecretKey", "seed", "isValidSecretKey", "isBytes", "isValidPublicKey", "utils", "size", "is25519", "createKeygen", "i2osp", "value", "length", "asafenumber", "res", "i", "strxor", "a", "b", "arr", "normDST", "DST", "isBytes", "dst", "asciiToBytes", "expand_message_xmd", "msg", "lenInBytes", "H", "abytes", "concatBytes", "b_in_bytes", "r_in_bytes", "ell", "DST_prime", "Z_pad", "l_i_b_str", "b_0", "args", "_DST_scalar", "_0n", "_1n", "_2n", "_5n", "_8n", "ed25519_CURVE_p", "ed25519_CURVE", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "_2n", "b5", "_1n", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "ED25519_SQRT_M1", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "ed25519_Point", "edwards", "Fp", "Fn", "ed", "opts", "eddsa", "ed25519_Point", "sha512", "adjustScalarBytes", "ed25519", "SQRT_M1", "ED25519_SQRT_M1", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "invertSqrt", "number", "uvRatio", "_1n", "MAX_255B", "bytes255ToNumberLE", "bytes", "Fp", "bytesToNumberLE", "calcElligatorRistrettoMap", "r0", "d", "ed25519_CURVE", "P", "ed25519_CURVE_p", "mod", "n", "r", "Ns", "c", "D", "Ns_D_is_sq", "s", "s_", "isNegativeLE", "Nt", "s2", "W0", "W1", "W2", "W3", "ed25519_Point", "_RistrettoPoint", "__RistrettoPoint", "PrimeEdwardsPoint", "Fn", "ep", "ap", "other", "abytes", "a", "equalBytes", "u1", "u2", "u1_2", "u2_2", "v", "isValid", "I", "Dx", "Dy", "x", "y", "t", "_0n", "hex", "hexToBytes", "X", "Y", "Z", "T", "u2sq", "invsqrt", "D1", "D2", "zInv", "_x", "_y", "X1", "Y1", "X2", "Y2", "one", "two", "ristretto255_hasher", "_RistrettoPoint", "msg", "options", "DST", "xmd", "expand_message_xmd", "sha512", "_DST_scalar", "Fn", "bytesToNumberLE", "bytes", "abytes", "r1", "bytes255ToNumberLE", "R1", "calcElligatorRistrettoMap", "r2", "R2", "VerificationError", "message", "WebCryptoMissingError", "webcrypto_browser_default", "win", "nativeCrypto", "WebCryptoMissingError", "webcrypto_default", "webcrypto_browser_default", "PUBLIC_KEY_BYTE_LENGTH", "ed25519Supported", "webCryptoEd25519SupportedPromise", "webcrypto_default", "hashAndVerifyWebCrypto", "publicKey", "sig", "msg", "key", "webcrypto_default", "hashAndVerifyNoble", "ed25519", "hashAndVerify", "ed25519Supported", "webCryptoEd25519SupportedPromise", "isPromise", "thing", "Ed25519PublicKey", "key", "ensureEd25519Key", "PUBLIC_KEY_BYTE_LENGTH", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "result", "hashAndVerify", "isPromise", "res", "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", "decodeUint8ArrayList", "decode", "buf", "offset", "decodeUint8Array", "decodeUint8ArrayList", "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", "streamMessage", "buf", "codec", "opts", "reader", "createReader", "CODEC_TYPES", "createCodec", "name", "type", "encode", "decode", "stream", "enumeration", "v", "findValue", "val", "encode", "writer", "enumValue", "decode", "reader", "stream", "createCodec", "CODEC_TYPES", "message", "encode", "decode", "stream", "createCodec", "CODEC_TYPES", "KeyType", "__KeyTypeValues", "enumeration", "PublicKey", "_codec", "message", "obj", "w", "opts", "reader", "length", "end", "tag", "prefix", "encode", "encodeMessage", "decode", "buf", "decodeMessage", "stream", "streamMessage", "PrivateKey", "_HMAC", "hash", "key", "ahash", "abytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "aoutput", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "hmac_", "message", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "aInRange", "_0n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "validateObject", "optsn", "optName", "abool", "DERErr", "m", "DER", "tag", "data", "E", "asafenumber", "dataLen", "len", "numberToHexUnpadded", "lenLen", "abytes", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "abignumber", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "rs", "ss", "seq", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "endo", "allowInfinityPoint", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "comp", "uncomp", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "finishEndo", "endoBeta", "k1p", "k2p", "negateCt", "X", "Y", "Z", "p", "P", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "a", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "fake", "mul", "normalizeZ", "k1f", "k2f", "f", "sc", "p1", "p2", "mulEndoUnsafe", "invertedZ", "iz", "is0", "zz", "isTorsionFree", "clearCofactor", "bytesToHex", "bits", "wNAF", "getWLengths", "Fp", "Fn", "ecdh", "Point", "ecdhOpts", "randomBytes_", "randomBytes", "lengths", "getMinHashLength", "isValidSecretKey", "secretKey", "num", "isValidPublicKey", "publicKey", "isCompressed", "comp", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "abytes", "getPublicKey", "isProbPub", "item", "allowedLengths", "isBytes", "isPub", "isSec", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "hash_", "ahash", "validateObject", "hmac", "key", "msg", "CURVE_ORDER", "fnBits", "defaultSigOpts", "hasLargeRecoveryLifts", "_2n", "_1n", "isBiggerThanHalfOrder", "number", "HALF", "validateRS", "title", "assertRecoverableCurve", "validateSigLength", "bytes", "format", "validateSigFormat", "size", "sizer", "Signature", "r", "recovery", "recid", "DER", "L", "hex", "hexToBytes", "messageHash", "radj", "x", "R", "concatBytes", "pprefix", "ir", "h", "bits2int_modN", "u1", "u2", "Q", "rb", "sb", "bytesToHex", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "bitMask", "int2octets", "aInRange", "_0n", "validateMsgAndHash", "message", "prehash", "prepSig", "opts", "lowS", "extraEntropy", "validateSigOpts", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "k", "ik", "q", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "P", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "hashAndVerify", "key", "sig", "msg", "options", "p", "sha256", "isPromise", "digest", "secp256k1", "err", "VerificationError", "Secp256k1PublicKey", "key", "validateSecp256k1PublicKey", "compressSecp256k1PublicKey", "identity", "publicKeyToProtobuf", "CID", "base58btc", "equals", "data", "sig", "options", "hashAndVerify", "unmarshalSecp256k1PublicKey", "bytes", "Secp256k1PublicKey", "compressSecp256k1PublicKey", "key", "secp256k1", "validateSecp256k1PublicKey", "key", "secp256k1", "err", "InvalidPublicKeyError", "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", "InvalidMultiaddrError", "ValidationError", "InvalidParametersError", "UnknownProtocolError", "Parser", "input", "fn", "index", "result", "target", "char", "sep", "inner", "radix", "maxDigits", "allowZeroPrefix", "maxBytes", "digitCount", "leadingChar", "hasLeadingZero", "maxValue", "digit", "num", "out", "i", "ix", "readGroups", "groups", "ipv4", "group", "head", "headSize", "headIp4", "tail", "limit", "tailSize", "MAX_IPV6_LENGTH", "MAX_IPV4_LENGTH", "parser", "Parser", "parseIPv4", "input", "parseIPv6", "input", "MAX_IPV6_LENGTH", "parser", "isIPv4", "input", "parseIPv4", "isIPv6", "parseIPv6", "bytesToString", "base", "buf", "toString", "stringToBytes", "fromString", "bytes2port", "port2bytes", "port", "onion2bytes", "str", "addr", "portBuf", "concat", "onion32bytes", "base32", "bytes2onion", "addrBytes", "portBytes", "ip4ToBytes", "ip", "bytes", "byte", "index", "value", "InvalidMultiaddrError", "ip6ToBytes", "offset", "sections", "i", "isv4", "isIPv4", "v4Buffer", "argv", "word", "ip4ToString", "result", "ip6ToString", "byte1", "byte2", "tuple", "url", "ip6StringToValue", "decoders", "bases", "c", "anybaseDecoder", "acc", "d", "mb2bytes", "mbstr", "bytes2mb", "integer", "value", "ValidationError", "positive", "maxValue", "max", "validate", "funcs", "fn", "validatePort", "V", "Registry", "key", "codec", "UnknownProtocolError", "alias", "code", "registry", "codecs", "ip4ToBytes", "ip4ToString", "value", "isIPv4", "ValidationError", "port2bytes", "bytes2port", "validatePort", "ip6ToBytes", "ip6ToString", "ip6StringToValue", "isIPv6", "bytesToString", "stringToBytes", "str", "val", "CID", "bytes2onion", "onion2bytes", "onion32bytes", "bytes2mb", "base64url", "mb2bytes", "bytesToComponents", "bytes", "components", "i", "code", "decode", "codec", "registry", "codeLength", "encodingLength", "size", "sizeForAddr", "sizeLength", "V", "componentLength", "component", "valueOffset", "valueBytes", "toString", "componentsToBytes", "length", "codecLength", "valueLength", "valueLengthLength", "fromString", "offset", "encodeUint8Array", "concat", "stringToComponents", "string", "InvalidMultiaddrError", "collecting", "value", "protocol", "char", "ended", "componentsToString", "inspect", "symbol", "toComponents", "addr", "isMultiaddr", "bytesToComponents", "stringToComponents", "InvalidMultiaddrError", "Multiaddr", "_Multiaddr", "#components", "#string", "#bytes", "options", "validate", "componentsToBytes", "componentsToString", "c", "ma", "addrString", "s", "i", "InvalidParametersError", "code", "index", "equals", "component", "codec", "registry", "isMultiaddr", "value", "symbol", "multiaddr", "addr", "Multiaddr", "code", "vals", "component", "value", "not", "matcher", "optional", "result", "or", "matchers", "matches", "and", "fmt", "match", "ma", "parts", "exactMatch", "_PEER_ID", "value", "PEER_ID", "fmt", "_DNS4", "_DNS6", "_DNSADDR", "_DNS", "DNS4", "optional", "DNS6", "DNSADDR", "DNS", "or", "_IP4", "and", "_IP6", "_IP", "_IP_OR_DOMAIN", "IP_OR_DOMAIN", "IP4", "IP6", "IP", "_TCP", "_UDP", "TCP", "UDP", "_QUIC", "code", "_QUIC_V1", "QUIC_V0_OR_V1", "QUIC", "QUIC_V1", "_WEB", "_WebSockets", "WebSockets", "_WebSocketsSecure", "WebSocketsSecure", "_WebRTCDirect", "WebRTCDirect", "_WebTransport", "WebTransport", "_P2P", "P2P", "_Circuit", "not", "Circuit", "_WebRTC", "WebRTC", "_HTTP", "HTTP", "_HTTPS", "HTTPS", "_Memory", "Memory", "_Unix", "Unix", "DEFAULT_BOOTSTRAP_TAG_NAME", "DEFAULT_BOOTSTRAP_TAG_VALUE", "DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT", "Bootstrap", "TypedEventEmitter", "components", "options", "str", "multiaddr", "ma", "P2P", "c", "peerIdFromString", "peerDiscoverySymbol", "serviceCapabilities", "err", "peerData", "bootstrap", "init"]
|
|
7
7
|
}
|