@wovin/core 0.1.25 → 0.1.27

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.
Files changed (46) hide show
  1. package/dist/applog.min.js +2 -1
  2. package/dist/blockstore/index.d.ts +21 -0
  3. package/dist/blockstore/index.d.ts.map +1 -0
  4. package/dist/blockstore.d.ts +2 -0
  5. package/dist/blockstore.d.ts.map +1 -0
  6. package/dist/blockstore.min.js +26 -0
  7. package/dist/blockstore.min.js.map +1 -0
  8. package/dist/{chunk-ZGU3O24G.min.js → chunk-CWVWWFE3.min.js} +6 -6
  9. package/dist/chunk-CWVWWFE3.min.js.map +1 -0
  10. package/dist/{chunk-USEP3ZEM.min.js → chunk-LHD7NNK6.min.js} +2 -2
  11. package/dist/{chunk-ITZTLALV.min.js → chunk-MCMSRRF7.min.js} +2 -2
  12. package/dist/chunk-MCMSRRF7.min.js.map +1 -0
  13. package/dist/{chunk-SA7YLEF6.min.js → chunk-N2LOFNFT.min.js} +20 -8
  14. package/dist/chunk-N2LOFNFT.min.js.map +1 -0
  15. package/dist/{chunk-CWGXD56S.min.js → chunk-NKGFXL72.min.js} +18 -13
  16. package/dist/{chunk-CWGXD56S.min.js.map → chunk-NKGFXL72.min.js.map} +1 -1
  17. package/dist/chunk-QO2KMGDN.min.js +3771 -0
  18. package/dist/chunk-QO2KMGDN.min.js.map +1 -0
  19. package/dist/{chunk-R7EMHBM3.min.js → chunk-XWBLRTV5.min.js} +783 -4064
  20. package/dist/chunk-XWBLRTV5.min.js.map +1 -0
  21. package/dist/{chunk-HHFNRKOI.min.js → chunk-YUH56CPQ.min.js} +2 -2
  22. package/dist/index.min.js +16 -13
  23. package/dist/ipfs.min.js +5 -4
  24. package/dist/ipns/ipns-record.d.ts +34 -0
  25. package/dist/ipns/ipns-record.d.ts.map +1 -0
  26. package/dist/ipns.d.ts +2 -0
  27. package/dist/ipns.d.ts.map +1 -0
  28. package/dist/ipns.min.js +6419 -0
  29. package/dist/ipns.min.js.map +1 -0
  30. package/dist/pubsub/pubsub-types.d.ts +1 -1
  31. package/dist/pubsub/pubsub-types.d.ts.map +1 -1
  32. package/dist/pubsub/snap-push.d.ts +2 -2
  33. package/dist/pubsub/snap-push.d.ts.map +1 -1
  34. package/dist/pubsub.min.js +5 -4
  35. package/dist/query.min.js +4 -3
  36. package/dist/retrieve/update-thread.d.ts +8 -1
  37. package/dist/retrieve/update-thread.d.ts.map +1 -1
  38. package/dist/retrieve.min.js +9 -6
  39. package/dist/thread.min.js +2 -1
  40. package/package.json +11 -1
  41. package/dist/chunk-ITZTLALV.min.js.map +0 -1
  42. package/dist/chunk-R7EMHBM3.min.js.map +0 -1
  43. package/dist/chunk-SA7YLEF6.min.js.map +0 -1
  44. package/dist/chunk-ZGU3O24G.min.js.map +0 -1
  45. /package/dist/{chunk-USEP3ZEM.min.js.map → chunk-LHD7NNK6.min.js.map} +0 -0
  46. /package/dist/{chunk-HHFNRKOI.min.js.map → chunk-YUH56CPQ.min.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/.pnpm/timestamp-nano@1.0.1/node_modules/timestamp-nano/dist/timestamp.min.js","../../../../node_modules/.pnpm/@libp2p+interface@3.0.0/node_modules/@libp2p/interface/src/errors.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/hashes/identity.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/equals.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/alloc.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/util/as-uint8array.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/concat.ts","../../../../node_modules/.pnpm/uint8arraylist@2.4.8/node_modules/uint8arraylist/src/index.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/base10.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/base16.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/base2.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/base256emoji.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/base8.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/bases/identity.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/codecs/json.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/hashes/sha2-browser.ts","../../../../node_modules/.pnpm/multiformats@13.4.2/node_modules/multiformats/src/basics.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/util/bases.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/from-string.ts","../../../../node_modules/.pnpm/uint8arrays@5.1.0/node_modules/uint8arrays/src/to-string.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/rsa/der.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ecdsa/index.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ecdsa/utils.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ecdsa/ecdsa.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/utils.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/modular.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/curve.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/edwards.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/ed25519.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/errors.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/webcrypto/webcrypto.browser.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/webcrypto/index.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ed25519/index.browser.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/util.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ed25519/ed25519.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/ed25519/utils.ts","../../../../node_modules/.pnpm/uint8-varint@2.0.4/node_modules/uint8-varint/src/index.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/float.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/longbits.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/utf8.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/reader.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/decode.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/pool.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/utils/writer.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/encode.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/codec.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/codecs/enum.ts","../../../../node_modules/.pnpm/protons-runtime@5.6.0/node_modules/protons-runtime/src/codecs/message.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/keys.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/rsa/utils.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/rsa/rsa.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/rsa/index.browser.ts","../../../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/src/hmac.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../../node_modules/.pnpm/@noble+curves@2.0.1/node_modules/@noble/curves/src/secp256k1.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/secp256k1/index.browser.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/secp256k1/secp256k1.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/secp256k1/utils.ts","../../../../node_modules/.pnpm/@libp2p+crypto@5.1.10/node_modules/@libp2p/crypto/src/keys/index.ts","../../../../node_modules/.pnpm/ms@3.0.0-canary.202508261828/node_modules/ms/src/index.ts","../../../../node_modules/.pnpm/weald@1.0.6/node_modules/weald/src/common.ts","../../../../node_modules/.pnpm/weald@1.0.6/node_modules/weald/src/browser.ts","../../../../node_modules/.pnpm/weald@1.0.6/node_modules/weald/src/index.ts","../../../../node_modules/.pnpm/@libp2p+logger@5.2.0/node_modules/@libp2p/logger/src/index.ts","../../../../node_modules/.pnpm/ipns@10.1.2/node_modules/ipns/src/index.ts","../../../../node_modules/.pnpm/ipns@10.1.2/node_modules/ipns/src/errors.ts","../../../../node_modules/.pnpm/ipns@10.1.2/node_modules/ipns/src/pb/ipns.ts","../../../../node_modules/.pnpm/ipns@10.1.2/node_modules/ipns/src/utils.ts","../../../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/src/bases/base64.ts","../src/ipns/ipns-record.ts"],"sourcesContent":["var Timestamp=function(){\"undefined\"!=typeof module&&(module.exports=d);var l=86400,s=3200,T=146097*s/400,e=l*T,f=1e3*e,c=864e13,g=4294967296,h=1e6,u=\"000000000\",m=Math.trunc||function(n){var t=n-n%1;return 0==t&&(n<0||0===n&&1/n!=1/0)?-0:t},n=d.prototype,o=(d.fromDate=function(n){return new d(+n)},d.fromInt64BE=r(0,1,2,3,0,4),d.fromInt64LE=r(3,2,1,0,4,0),d.fromString=function(n){var e,r=new d,n=(n+=\"\").replace(/^\\s*[+\\-]?\\d+/,function(n){var n=+n,t=1970+(n-1970)%400;return r.year=n-t,t}).replace(/(?:Z|([+\\-]\\d{2}):?(\\d{2}))$/,function(n,t,r){return t<0&&(r*=-1),e=6e4*(60*+t+ +r),\"\"}).replace(/\\.\\d+$/,function(n){return r.nano=+(n+u).substr(1,9),\"\"}).split(/\\D+/);1<n.length?n[1]--:n[1]=0;if(r.time=e=Date.UTC.apply(Date,n)-(e||0),isNaN(e))throw new TypeError(\"Invalid Date\");return p(r)},d.fromTimeT=function(n){return y(n,0)},n.year=0,n.time=0,n.nano=0,n.addNano=function(n){return this.nano+=+n||0,this},n.getNano=function(){var n=p(this);return(n.time%1e3*h+ +n.nano+1e9)%1e9},n.getTimeT=function(){var n=p(this),t=Math.floor(n.time/1e3),n=n.year;n&&(t+=n*T*l/s);return t},n.getYear=function(){return this.toDate().getUTCFullYear()+this.year},n.toDate=function(){return M(p(this).time)},n.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,\"Z\")},n.toString=function(n){var t=this,r=t.toDate(),u={H:function(){return C(r.getUTCHours())},L:function(){return D(r.getUTCMilliseconds(),3)},M:function(){return C(r.getUTCMinutes())},N:function(){return D(t.getNano(),9)},S:function(){return C(r.getUTCSeconds())},Y:function(){var n=t.getYear();return 999999<n?\"+\"+n:9999<n?\"+\"+D(n,6):0<=n?D(n,4):-999999<=n?\"-\"+D(-n,6):n},a:function(){return a[r.getUTCDay()]},b:function(){return i[r.getUTCMonth()]},d:function(){return C(r.getUTCDate())},e:function(){return function(n){return(9<n?\"\":\" \")+(0|n)}(r.getUTCDate())},m:function(){return C(r.getUTCMonth()+1)}};return function e(n){return n.replace(/%./g,function(n){var t=n[1],r=v[t],t=u[t];return r?e(r):t?t():n})}(n||o)},n.writeInt64BE=t(0,1,2,3,0,4),n.writeInt64LE=t(3,2,1,0,4,0),\"%Y-%m-%dT%H:%M:%S.%NZ\"),i=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],a=[\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\"],v={\"%\":\"%\",F:\"%Y-%m-%d\",n:\"\\n\",R:\"%H:%M\",T:\"%H:%M:%S\",t:\"\\t\",X:\"%T\",Z:\"GMT\",z:\"+0000\"};return d;function d(n,t,r){var e=this;if(!(e instanceof d))return new d(n,t,r);e.time=+n||0,e.nano=+t||0,e.year=+r||0,p(e)}function p(n){var t,r,e,u=n.year,o=n.time,i=n.nano,a=((i<0||h<=i)&&(i-=(r=Math.floor(i/h))*h,o+=r,r=1),u%s);return(o<-c||c<o||a)&&((t=m(o/f))&&(u+=t*s,o-=t*f),(e=M(o)).setUTCFullYear(a+e.getUTCFullYear()),e=(o=+e)+(t=m((u-=a)/s))*f,t&&-c<=e&&e<=c&&(u-=t*s,o=e),r=1),r&&(n.year=u,n.time=o,n.nano=i),n}function M(n){var t=new Date(0);return t.setTime(n),t}function y(n,t){n=+n||0;var r=m((t=(t|0)*g)/e)+m(n/e),t=t%e+n%e,n=m(t/e);return n&&(r+=n,t-=n*e),new d(1e3*t,0,r*s)}function t(e,u,o,i,a,f){return function(n,t){var r=p(this);n=n||new Array(8);w(n,t|=0);var e=Math.floor(r.time/1e3),r=r.year*(T*l/s),u=m(r/g)+m(e/g),r=r%g+e%g,e=Math.floor(r/g);e&&(u+=e,r-=e*g);return c(n,t+a,u),c(n,t+f,r),n};function c(n,t,r){n[t+e]=r>>24&255,n[t+u]=r>>16&255,n[t+o]=r>>8&255,n[t+i]=255&r}}function r(r,e,u,o,i,a){return function(n,t){w(n,t|=0);var r=f(n,t+i);return y(f(n,t+a),r)};function f(n,t){return 16777216*n[t+r]+(n[t+e]<<16|n[t+u]<<8|n[t+o])}}function w(n,t){n=n&&n.length;if(null==n)throw new TypeError(\"Invalid Buffer\");if(n<t+8)throw new RangeError(\"Out of range\")}function C(n){return(9<n?\"\":\"0\")+(0|n)}function D(n,t){return(u+(0|n)).substr(-t)}}();","/**\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 { 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","/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nexport function asUint8Array (buf: Uint8Array): Uint8Array {\n return buf\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('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂')\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: '🚀',\n name: 'base256emoji',\n encode,\n decode\n})\n","import { rfc4648 } from './base.js'\n\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n})\n","import { fromString, toString } from '../bytes.js'\nimport { from } from './base.js'\n\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n})\n","import type { ArrayBufferView, ByteView } from './interface.js'\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\nexport const name = 'json'\nexport const code = 0x0200\n\nexport function encode <T> (node: T): ByteView<T> {\n return textEncoder.encode(JSON.stringify(node))\n}\n\nexport function decode <T> (data: ByteView<T> | ArrayBufferView<T>): T {\n return JSON.parse(textDecoder.decode(data))\n}\n","/* global crypto */\n\nimport { from } from './hasher.js'\n\nfunction sha (name: AlgorithmIdentifier): (data: Uint8Array) => Promise<Uint8Array> {\n return async data => new Uint8Array(await crypto.subtle.digest(name, data))\n}\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n","import * as 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 * 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) ≡ 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 ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 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 ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8;\n // P ≡ 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) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 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 / 𝑊) + 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^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 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 × 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 × 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 × 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² + y² = 1 + dx²y².\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 √(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² + y² = 1 + dx²y² 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² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\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) ∋ (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² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(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// √(-1) aka √(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³\n const v7 = mod(v3 * v3 * v, P); // v⁷\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³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\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² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-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// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/√(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 * ⟨T⟩ = { 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.js'\nimport { LongBits } from './longbits.js'\nimport * as utf8 from './utf8.js'\nimport type { Reader } from '../index.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\n/* istanbul ignore next */\nfunction indexOutOfRange (reader: Reader, writeLength?: number): RangeError {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`)\n}\n\nfunction readFixed32End (buf: Uint8Array, end: number): number { // note that this uses `end`, not `pos`\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader implements Reader {\n public buf: Uint8Array\n public pos: number\n public len: number\n\n public _slice = Uint8Array.prototype.subarray\n\n constructor (buffer: Uint8Array) {\n /**\n * Read buffer\n */\n this.buf = buffer\n\n /**\n * Read buffer position\n */\n this.pos = 0\n\n /**\n * Read buffer length\n */\n this.len = buffer.length\n }\n\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32 (): number {\n let value = 4294967295\n\n value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) { return value }\n\n if ((this.pos += 5) > this.len) {\n this.pos = this.len\n throw indexOutOfRange(this, 10)\n }\n\n return value\n }\n\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32 (): number {\n return this.uint32() | 0\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32 (): number {\n const value = this.uint32()\n return value >>> 1 ^ -(value & 1) | 0\n }\n\n /**\n * Reads a varint as a boolean\n */\n bool (): boolean {\n return this.uint32() !== 0\n }\n\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32 (): number {\n if (this.pos + 4 > this.len) { throw indexOutOfRange(this, 4) }\n\n const res = readFixed32End(this.buf, this.pos += 4)\n\n return res\n }\n\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32 (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const res = readFixed32End(this.buf, this.pos += 4) | 0\n\n return res\n }\n\n /**\n * Reads a float (32 bit) as a number\n */\n float (): number {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4)\n }\n\n const value = readFloatLE(this.buf, this.pos)\n this.pos += 4\n return value\n }\n\n /**\n * Reads a double (64 bit float) as a number\n */\n double (): number {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) { throw indexOutOfRange(this, 4) }\n\n const value = readDoubleLE(this.buf, this.pos)\n this.pos += 8\n return value\n }\n\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes (): Uint8Array {\n const length = this.uint32()\n const start = this.pos\n const end = this.pos + length\n\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length)\n }\n\n this.pos += length\n\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end)\n }\n\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string (): string {\n const bytes = this.bytes()\n return utf8.read(bytes, 0, bytes.length)\n }\n\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip (length?: number): this {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) { throw indexOutOfRange(this, length) }\n this.pos += length\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n } while ((this.buf[this.pos++] & 128) !== 0)\n }\n return this\n }\n\n /**\n * Skips the next element of the specified wire type\n */\n skipType (wireType: number): this {\n switch (wireType) {\n case 0:\n this.skip()\n break\n case 1:\n this.skip(8)\n break\n case 2:\n this.skip(this.uint32())\n break\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType)\n }\n break\n case 5:\n this.skip(4)\n break\n\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`)\n }\n return this\n }\n\n private readLongVarint (): LongBits {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0)\n let i = 0\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n i = 0\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) { throw indexOutOfRange(this) }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0\n return bits\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n } else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this)\n }\n\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0\n if (this.buf[this.pos++] < 128) { return bits }\n }\n }\n\n throw Error('invalid varint encoding')\n }\n\n private readFixed64 (): LongBits {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8)\n }\n\n const lo = readFixed32End(this.buf, this.pos += 4)\n const hi = readFixed32End(this.buf, this.pos += 4)\n\n return new LongBits(lo, hi)\n }\n\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64 (): bigint {\n return this.readLongVarint().toBigInt()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number (): number {\n return this.readLongVarint().toNumber()\n }\n\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String (): string {\n return this.readLongVarint().toString()\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64 (): bigint {\n return this.readLongVarint().toBigInt(true)\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number (): number {\n const value = decodeUint8Array(this.buf, this.pos)\n this.pos += encodingLength(value)\n return value\n }\n\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String (): string {\n return this.readLongVarint().toString(true)\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64 (): bigint {\n return this.readLongVarint().zzDecode().toBigInt()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number (): number {\n return this.readLongVarint().zzDecode().toNumber()\n }\n\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String (): string {\n return this.readLongVarint().zzDecode().toString()\n }\n\n /**\n * Reads fixed 64 bits\n */\n fixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String (): string {\n return this.readFixed64().toString()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64 (): bigint {\n return this.readFixed64().toBigInt()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number (): number {\n return this.readFixed64().toNumber()\n }\n\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String (): string {\n return this.readFixed64().toString()\n }\n}\n\nexport function createReader (buf: Uint8Array | Uint8ArrayList): Reader {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray())\n}\n","import { createReader } from './utils/reader.js'\nimport type { Codec, DecodeOptions } from './codec.js'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport function decodeMessage <T> (buf: Uint8Array | Uint8ArrayList, codec: Pick<Codec<T>, 'decode'>, opts?: DecodeOptions<T>): T {\n const reader = createReader(buf)\n\n return codec.decode(reader, undefined, opts)\n}\n","import { allocUnsafe } from 'uint8arrays/alloc'\n\n/**\n * A general purpose buffer pool\n */\nexport default function pool (size?: number): (size: number) => Uint8Array {\n const SIZE = size ?? 8192\n const MAX = SIZE >>> 1\n let slab: Uint8Array\n let offset = SIZE\n return function poolAlloc (size: number) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size)\n }\n\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE)\n offset = 0\n }\n\n const buf = slab.subarray(offset, offset += size)\n\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1\n }\n\n return buf\n }\n}\n","import { encodeUint8Array, encodingLength } from 'uint8-varint'\nimport { allocUnsafe } from 'uint8arrays/alloc'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { writeFloatLE, writeDoubleLE } from './float.js'\nimport { LongBits } from './longbits.js'\nimport pool from './pool.js'\nimport * as utf8 from './utf8.js'\nimport type { Writer } from '../index.js'\n\ninterface WriterOperation<T> {\n (val: T, buf: Uint8Array, pos: number): any\n}\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op<T> {\n /**\n * Function to call\n */\n public fn: WriterOperation<T>\n\n /**\n * Value byte length\n */\n public len: number\n\n /**\n * Next operation\n */\n public next?: Op<any>\n\n /**\n * Value to write\n */\n public val: T\n\n constructor (fn: WriterOperation<T>, len: number, val: T) {\n this.fn = fn\n this.len = len\n this.next = undefined\n this.val = val // type varies\n }\n}\n\n/* istanbul ignore next */\nfunction noop (): void {}\n\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n public head: Op<any>\n\n /**\n * Current tail\n */\n public tail: Op<any>\n\n /**\n * Current buffer length\n */\n public len: number\n\n /**\n * Next state\n */\n public next?: State\n\n constructor (writer: Uint8ArrayWriter) {\n this.head = writer.head\n this.tail = writer.tail\n this.len = writer.len\n this.next = writer.states\n }\n}\n\nconst bufferPool = pool()\n\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc (size: number): Uint8Array {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size)\n }\n\n return bufferPool(size)\n}\n\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter implements Writer {\n /**\n * Current length\n */\n public len: number\n\n /**\n * Operations head\n */\n public head: Op<any>\n\n /**\n * Operations tail\n */\n public tail: Op<any>\n\n /**\n * Linked forked states\n */\n public states?: any\n\n constructor () {\n this.len = 0\n this.head = new Op(noop, 0, 0)\n this.tail = this.head\n this.states = null\n }\n\n /**\n * Pushes a new operation to the queue\n */\n _push (fn: WriterOperation<any>, len: number, val: any): this {\n this.tail = this.tail.next = new Op(fn, len, val)\n this.len += len\n\n return this\n }\n\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32 (value: number): this {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5,\n value)).len\n return this\n }\n\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32 (value: number): this {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value)\n }\n\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32 (value: number): this {\n return this.uint32((value << 1 ^ value >> 31) >>> 0)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number (value: number): this {\n return this._push(encodeUint8Array, encodingLength(value), value)\n }\n\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String (value: string): this {\n return this.uint64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64 (value: bigint): this {\n return this.uint64(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number (value: number): this {\n return this.uint64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String (value: string): this {\n return this.uint64String(value)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number (value: number): this {\n const bits = LongBits.fromNumber(value).zzEncode()\n return this._push(writeVarint64, bits.length(), bits)\n }\n\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String (value: string): this {\n return this.sint64(BigInt(value))\n }\n\n /**\n * Writes a boolish value as a varint\n */\n bool (value: boolean): this {\n return this._push(writeByte, 1, value ? 1 : 0)\n }\n\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32 (value: number): this {\n return this._push(writeFixed32, 4, value >>> 0)\n }\n\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32 (value: number): this {\n return this.fixed32(value)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64 (value: bigint): this {\n const bits = LongBits.fromBigInt(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number (value: number): this {\n const bits = LongBits.fromNumber(value)\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi)\n }\n\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String (value: string): this {\n return this.fixed64(BigInt(value))\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64 (value: bigint): this {\n return this.fixed64(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number (value: number): this {\n return this.fixed64Number(value)\n }\n\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String (value: string): this {\n return this.fixed64String(value)\n }\n\n /**\n * Writes a float (32 bit)\n */\n float (value: number): this {\n return this._push(writeFloatLE, 4, value)\n }\n\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double (value: number): this {\n return this._push(writeDoubleLE, 8, value)\n }\n\n /**\n * Writes a sequence of bytes\n */\n bytes (value: Uint8Array): this {\n const len = value.length >>> 0\n\n if (len === 0) {\n return this._push(writeByte, 1, 0)\n }\n\n return this.uint32(len)._push(writeBytes, len, value)\n }\n\n /**\n * Writes a string\n */\n string (value: string): this {\n const len = utf8.length(value)\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0)\n }\n\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork (): this {\n this.states = new State(this)\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n return this\n }\n\n /**\n * Resets this instance to the last state\n */\n reset (): this {\n if (this.states != null) {\n this.head = this.states.head\n this.tail = this.states.tail\n this.len = this.states.len\n this.states = this.states.next\n } else {\n this.head = this.tail = new Op(noop, 0, 0)\n this.len = 0\n }\n return this\n }\n\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim (): this {\n const head = this.head\n const tail = this.tail\n const len = this.len\n this.reset().uint32(len)\n if (len !== 0) {\n this.tail.next = head.next // skip noop\n this.tail = tail\n this.len += len\n }\n return this\n }\n\n /**\n * Finishes the write operation\n */\n finish (): Uint8Array {\n let head = this.head.next // skip noop\n const buf = alloc(this.len)\n let pos = 0\n while (head != null) {\n head.fn(head.val, buf, pos)\n pos += head.len\n head = head.next\n }\n // this.head = this.tail = null;\n return buf\n }\n}\n\nfunction writeByte (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n}\n\nfunction writeVarint32 (val: number, buf: Uint8Array, pos: number): void {\n while (val > 127) {\n buf[pos++] = val & 127 | 128\n val >>>= 7\n }\n buf[pos] = val\n}\n\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op<number> {\n public next?: Op<any>\n\n constructor (len: number, val: number) {\n super(writeVarint32, len, val)\n this.next = undefined\n }\n}\n\nfunction writeVarint64 (val: LongBits, buf: Uint8Array, pos: number): void {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0\n val.hi >>>= 7\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128\n val.lo = val.lo >>> 7\n }\n buf[pos++] = val.lo\n}\n\nfunction writeFixed32 (val: number, buf: Uint8Array, pos: number): void {\n buf[pos] = val & 255\n buf[pos + 1] = val >>> 8 & 255\n buf[pos + 2] = val >>> 16 & 255\n buf[pos + 3] = val >>> 24\n}\n\nfunction writeBytes (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos)\n}\n\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value: Uint8Array) {\n const len = value.length >>> 0\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeBytesBuffer, len, value)\n }\n\n return this\n }\n\n Uint8ArrayWriter.prototype.string = function (value: string) {\n const len = globalThis.Buffer.byteLength(value)\n\n this.uint32(len)\n\n if (len > 0) {\n this._push(writeStringBuffer, len, value)\n }\n\n return this\n }\n}\n\nfunction writeBytesBuffer (val: Uint8Array, buf: Uint8Array, pos: number): void {\n buf.set(val, pos) // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\n\nfunction writeStringBuffer (val: string, buf: Uint8Array, pos: number): void {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos)\n // @ts-expect-error buf isn't a Uint8Array?\n } else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos)\n } else {\n buf.set(uint8ArrayFromString(val), pos)\n }\n}\n\n/**\n * Creates a new writer\n */\nexport function createWriter (): Writer {\n return new Uint8ArrayWriter()\n}\n","import { createWriter } from './utils/writer.js'\nimport type { Codec } from './codec.js'\n\nexport function encodeMessage <T> (message: Partial<T>, codec: Pick<Codec<T>, 'encode'>): Uint8Array {\n const w = createWriter()\n\n codec.encode(message, w, {\n lengthDelimited: false\n })\n\n return w.finish()\n}\n","import type { Writer, Reader } from './index.js'\n\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport enum CODEC_TYPES {\n VARINT = 0,\n BIT64,\n LENGTH_DELIMITED,\n START_GROUP,\n END_GROUP,\n BIT32\n}\n\nexport interface EncodeOptions {\n lengthDelimited?: boolean\n writeDefaults?: boolean\n}\n\nexport interface EncodeFunction<T> {\n (value: Partial<T>, writer: Writer, opts?: EncodeOptions): void\n}\n\n// protobuf types that contain multiple values\ntype CollectionTypes = any[] | Map<any, any>\n\n// protobuf types that are not collections or messages\ntype PrimitiveTypes = boolean | number | string | bigint | Uint8Array\n\n// recursive array/map field length limits\ntype CollectionLimits <T> = {\n [K in keyof T]: T[K] extends CollectionTypes ? number :\n T[K] extends PrimitiveTypes ? never : Limits<T[K]>\n}\n\n// recursive array member array/map field length limits\ntype ArrayElementLimits <T> = {\n [K in keyof T as `${string & K}$`]: T[K] extends Array<infer ElementType> ?\n (ElementType extends PrimitiveTypes ? never : Limits<ElementType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// recursive map value array/map field length limits\ntype MapValueLimits <T> = {\n [K in keyof T as `${string & K}$value`]: T[K] extends Map<any, infer MapValueType> ?\n (MapValueType extends PrimitiveTypes ? never : Limits<MapValueType>) :\n (T[K] extends PrimitiveTypes ? never : Limits<T[K]>)\n}\n\n// union of collection and array elements\ntype Limits<T> = Partial<CollectionLimits<T> & ArrayElementLimits<T> & MapValueLimits<T>>\n\nexport interface DecodeOptions<T> {\n /**\n * Runtime-specified limits for lengths of repeated/map fields\n */\n limits?: Limits<T>\n}\n\nexport interface DecodeFunction<T> {\n (reader: Reader, length?: number, opts?: DecodeOptions<T>): T\n}\n\nexport interface Codec<T> {\n name: string\n type: CODEC_TYPES\n encode: EncodeFunction<T>\n decode: DecodeFunction<T>\n}\n\nexport function createCodec <T> (name: string, type: CODEC_TYPES, encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return {\n name,\n type,\n encode,\n decode\n }\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { DecodeFunction, EncodeFunction, Codec } from '../codec.js'\n\nexport function enumeration <T> (v: any): Codec<T> {\n function findValue (val: string | number): number {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value')\n }\n\n return v[val]\n }\n\n const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {\n const enumValue = findValue(val)\n\n writer.int32(enumValue)\n }\n\n const decode: DecodeFunction<number | string> = function enumDecode (reader) {\n const val = reader.int32()\n\n return findValue(val)\n }\n\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)\n}\n","import { createCodec, CODEC_TYPES } from '../codec.js'\nimport type { EncodeFunction, DecodeFunction, Codec } from '../codec.js'\n\nexport interface Factory<A, T> {\n new (obj: A): T\n}\n\nexport function message <T> (encode: EncodeFunction<T>, decode: DecodeFunction<T>): Codec<T> {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode)\n}\n","import { decodeMessage, encodeMessage, enumeration, message } 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}\nexport interface PublicKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PublicKey {\n let _codec: Codec<PublicKey>\n\n export const codec = (): Codec<PublicKey> => {\n if (_codec == null) {\n _codec = message<PublicKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PublicKey>): Uint8Array => {\n return encodeMessage(obj, PublicKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PublicKey>): PublicKey => {\n return decodeMessage(buf, PublicKey.codec(), opts)\n }\n}\n\nexport interface PrivateKey {\n Type?: KeyType\n Data?: Uint8Array\n}\n\nexport namespace PrivateKey {\n let _codec: Codec<PrivateKey>\n\n export const codec = (): Codec<PrivateKey> => {\n if (_codec == null) {\n _codec = message<PrivateKey>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.Type != null) {\n w.uint32(8)\n KeyType.codec().encode(obj.Type, w)\n }\n\n if (obj.Data != null) {\n w.uint32(18)\n w.bytes(obj.Data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader)\n break\n }\n case 2: {\n obj.Data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<PrivateKey>): Uint8Array => {\n return encodeMessage(obj, PrivateKey.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<PrivateKey>): PrivateKey => {\n return decodeMessage(buf, PrivateKey.codec(), opts)\n }\n}\n","import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface'\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { create } from 'multiformats/hashes/digest'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport * as pb from '../keys.js'\nimport { decodeDer, encodeBitString, encodeInteger, encodeSequence } from './der.js'\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from './rsa.js'\nimport { generateRSAKey, rsaKeySize } from './index.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { RSAPrivateKey, RSAPublicKey } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\n\nexport const MAX_RSA_KEY_SIZE = 8192\nconst SHA2_256_CODE = 0x12\nconst MAX_RSA_JWK_SIZE = 1062\n\nconst RSA_ALGORITHM_IDENTIFIER = Uint8Array.from([\n 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00\n])\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToJwk(message)\n}\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK private key\n */\nexport function pkcs1MessageToJwk (message: any): JsonWebKey {\n return {\n n: uint8ArrayToString(message[1], 'base64url'),\n e: uint8ArrayToString(message[2], 'base64url'),\n d: uint8ArrayToString(message[3], 'base64url'),\n p: uint8ArrayToString(message[4], 'base64url'),\n q: uint8ArrayToString(message[5], 'base64url'),\n dp: uint8ArrayToString(message[6], 'base64url'),\n dq: uint8ArrayToString(message[7], 'base64url'),\n qi: uint8ArrayToString(message[8], 'base64url'),\n kty: 'RSA'\n }\n}\n\n/**\n * Convert a JWK private key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1 (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n return encodeSequence([\n encodeInteger(Uint8Array.from([0])),\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.d, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.p, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.q, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dp, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.dq, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.qi, 'base64url'))\n ]).subarray()\n}\n\n/**\n * Convert a PKIX in ASN1 DER format to a JWK public key\n */\nexport function pkixToJwk (bytes: Uint8Array): JsonWebKey {\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToJwk(message)\n}\n\nexport function pkixMessageToJwk (message: any): JsonWebKey {\n const keys = decodeDer(message[1], {\n offset: 0\n })\n\n // this looks fragile but DER is a canonical format so we are safe to have\n // deeply property chains like this\n return {\n kty: 'RSA',\n n: uint8ArrayToString(\n keys[0],\n 'base64url'\n ),\n e: uint8ArrayToString(\n keys[1],\n 'base64url'\n )\n }\n}\n\n/**\n * Convert a JWK public key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix (jwk: JsonWebKey): Uint8Array {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components')\n }\n\n const subjectPublicKeyInfo = encodeSequence([\n RSA_ALGORITHM_IDENTIFIER,\n encodeBitString(\n encodeSequence([\n encodeInteger(uint8ArrayFromString(jwk.n, 'base64url')),\n encodeInteger(uint8ArrayFromString(jwk.e, 'base64url'))\n ])\n )\n ])\n\n return subjectPublicKeyInfo.subarray()\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey (bytes: Uint8Array): RSAPrivateKey {\n const message = decodeDer(bytes)\n\n return pkcs1MessageToRSAPrivateKey(message)\n}\n\n/**\n * Turn PKCS#1 DER bytes into a PrivateKey\n */\nexport function pkcs1MessageToRSAPrivateKey (message: any): RSAPrivateKey {\n const jwk = pkcs1MessageToJwk(message)\n\n return jwkToRSAPrivateKey(jwk)\n}\n\n/**\n * Turn a PKIX message into a PublicKey\n */\nexport function pkixToRSAPublicKey (bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n if (bytes.byteLength >= MAX_RSA_JWK_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large')\n }\n\n const message = decodeDer(bytes, {\n offset: 0\n })\n\n return pkixMessageToRSAPublicKey(message, bytes, digest)\n}\n\nexport function pkixMessageToRSAPublicKey (message: any, bytes: Uint8Array, digest?: Digest<18, number>): RSAPublicKey {\n const jwk = pkixMessageToJwk(message)\n\n if (digest == null) {\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }))\n digest = create(SHA2_256_CODE, hash)\n }\n\n return new RSAPublicKeyClass(jwk, digest)\n}\n\nexport function jwkToRSAPrivateKey (jwk: JsonWebKey): RSAPrivateKey {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = jwkToJWKKeyPair(jwk)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\nexport async function generateRSAKeyPair (bits: number): Promise<RSAPrivateKey> {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large')\n }\n\n const keys = await generateRSAKey(bits)\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }))\n const digest = create(SHA2_256_CODE, hash)\n\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest))\n}\n\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair (key: JsonWebKey): JWKKeyPair {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter')\n }\n\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n }\n}\n","import { base58btc } from 'multiformats/bases/base58'\nimport { CID } from 'multiformats/cid'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { hashAndSign, utils, hashAndVerify } from './index.js'\nimport type { RSAPublicKey as RSAPublicKeyInterface, RSAPrivateKey as RSAPrivateKeyInterface, AbortOptions } from '@libp2p/interface'\nimport type { Digest } from 'multiformats/hashes/digest'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport class RSAPublicKey implements RSAPublicKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n private readonly _multihash: Digest<18, number>\n\n constructor (jwk: JsonWebKey, digest: Digest<18, number>) {\n this.jwk = jwk\n this._multihash = digest\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this.jwk)\n }\n\n return this._raw\n }\n\n toMultihash (): Digest<18, number> {\n return this._multihash\n }\n\n toCID (): CID<unknown, 114, 18, 1> {\n return CID.createV1(114, this._multihash)\n }\n\n toString (): string {\n return base58btc.encode(this.toMultihash().bytes).substring(1)\n }\n\n equals (key?: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n verify (data: Uint8Array | Uint8ArrayList, sig: Uint8Array, options?: AbortOptions): boolean | Promise<boolean> {\n return hashAndVerify(this.jwk, sig, data, options)\n }\n}\n\nexport class RSAPrivateKey implements RSAPrivateKeyInterface {\n public readonly type = 'RSA'\n public readonly jwk: JsonWebKey\n private _raw?: Uint8Array\n public readonly publicKey: RSAPublicKey\n\n constructor (jwk: JsonWebKey, publicKey: RSAPublicKey) {\n this.jwk = jwk\n this.publicKey = publicKey\n }\n\n get raw (): Uint8Array {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this.jwk)\n }\n\n return this._raw\n }\n\n equals (key: any): boolean {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false\n }\n\n return uint8ArrayEquals(this.raw, key.raw)\n }\n\n sign (message: Uint8Array | Uint8ArrayList, options?: AbortOptions): Uint8Array | Promise<Uint8Array> {\n return hashAndSign(this.jwk, message, options)\n }\n}\n","import { InvalidParametersError } from '@libp2p/interface'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport randomBytes from '../../random-bytes.js'\nimport webcrypto from '../../webcrypto/index.js'\nimport * as utils from './utils.js'\nimport type { JWKKeyPair } from '../interface.js'\nimport type { AbortOptions } from '@libp2p/interface'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport const RSAES_PKCS1_V1_5_OID = '1.2.840.113549.1.1.1'\nexport { utils }\n\nexport async function generateRSAKey (bits: number, options?: AbortOptions): Promise<JWKKeyPair> {\n const pair = await webcrypto.get().subtle.generateKey(\n {\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n },\n true,\n ['sign', 'verify']\n )\n options?.signal?.throwIfAborted()\n\n const keys = await exportKey(pair, options)\n\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n }\n}\n\nexport { randomBytes as getRandomValues }\n\nexport async function hashAndSign (key: JsonWebKey, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<Uint8Array> {\n const privateKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['sign']\n )\n options?.signal?.throwIfAborted()\n\n const sig = await webcrypto.get().subtle.sign(\n { name: 'RSASSA-PKCS1-v1_5' },\n privateKey,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n options?.signal?.throwIfAborted()\n\n return new Uint8Array(sig, 0, sig.byteLength)\n}\n\nexport async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<boolean> {\n const publicKey = await webcrypto.get().subtle.importKey(\n 'jwk',\n key,\n {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n },\n false,\n ['verify']\n )\n options?.signal?.throwIfAborted()\n\n const result = await webcrypto.get().subtle.verify(\n { name: 'RSASSA-PKCS1-v1_5' },\n publicKey,\n sig,\n msg instanceof Uint8Array ? msg : msg.subarray()\n )\n options?.signal?.throwIfAborted()\n\n return result\n}\n\nasync function exportKey (pair: CryptoKeyPair, options?: AbortOptions): Promise<[JsonWebKey, JsonWebKey]> {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required')\n }\n\n const result = await Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ])\n options?.signal?.throwIfAborted()\n\n return result\n}\n\nexport function rsaKeySize (jwk: JsonWebKey): number {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type')\n } else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus')\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url')\n return bytes.length * 8\n}\n","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, 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² = x³ + 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 ψ**.\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 ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(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: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 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² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (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² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Validate whether the passed curve params are valid.\n // Test 1: equation y² = x³ + 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 Δ part should be non-zero: 4a³ + 27b² != 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) ∋ (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) ∋ (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ïve 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⋅G\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 ∈ [1,q−1] 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⋅G\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 × 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⋅G + u2⋅P\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⋅G + u2⋅P\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 ψ,\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 * √n = 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'⋅G; 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 ≥ p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 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'≥n. Ret bytes(d'⋅G)\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'⋅G\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 ≥ 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 ≥ 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⋅G - e⋅P, 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) ≠ 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","const s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nconst mo = y / 12;\n\ntype Years = 'years' | 'year' | 'yrs' | 'yr' | 'y';\ntype Months = 'months' | 'month' | 'mo';\ntype Weeks = 'weeks' | 'week' | 'w';\ntype Days = 'days' | 'day' | 'd';\ntype Hours = 'hours' | 'hour' | 'hrs' | 'hr' | 'h';\ntype Minutes = 'minutes' | 'minute' | 'mins' | 'min' | 'm';\ntype Seconds = 'seconds' | 'second' | 'secs' | 'sec' | 's';\ntype Milliseconds = 'milliseconds' | 'millisecond' | 'msecs' | 'msec' | 'ms';\ntype Unit =\n | Years\n | Months\n | Weeks\n | Days\n | Hours\n | Minutes\n | Seconds\n | Milliseconds;\n\ntype UnitAnyCase = Capitalize<Unit> | Uppercase<Unit> | Unit;\n\nexport type StringValue =\n | `${number}`\n | `${number}${UnitAnyCase}`\n | `${number} ${UnitAnyCase}`;\n\ninterface Options {\n /**\n * Set to `true` to use verbose formatting. Defaults to `false`.\n */\n long?: boolean;\n}\n\n/**\n * Parse or format the given value.\n *\n * @param value - The string or number to convert\n * @param options - Options for the conversion\n * @throws Error if `value` is not a non-empty string or a number\n */\nexport function ms(value: StringValue, options?: Options): number;\nexport function ms(value: number, options?: Options): string;\nexport function ms(\n value: StringValue | number,\n options?: Options,\n): number | string {\n if (typeof value === 'string') {\n return parse(value);\n } else if (typeof value === 'number') {\n return format(value, options);\n }\n throw new Error(\n `Value provided to ms() must be a string or number. value=${JSON.stringify(value)}`,\n );\n}\n\nexport default ms;\n\n/**\n * Parse the given string and return milliseconds.\n *\n * @param str - A string to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parse(str: string): number {\n if (typeof str !== 'string' || str.length === 0 || str.length > 100) {\n throw new Error(\n `Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(str)}`,\n );\n }\n const match =\n /^(?<value>-?\\d*\\.?\\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(\n str,\n );\n\n if (!match?.groups) {\n return NaN;\n }\n\n // Named capture groups need to be manually typed today.\n // https://github.com/microsoft/TypeScript/issues/32098\n const { value, unit = 'ms' } = match.groups as {\n value: string;\n unit: string | undefined;\n };\n\n const n = parseFloat(value);\n\n const matchUnit = unit.toLowerCase() as Lowercase<Unit>;\n\n /* istanbul ignore next - istanbul doesn't understand, but thankfully the TypeScript the exhaustiveness check in the default case keeps us type safe here */\n switch (matchUnit) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'months':\n case 'month':\n case 'mo':\n return n * mo;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n matchUnit satisfies never;\n throw new Error(\n `Unknown unit \"${matchUnit}\" provided to ms.parse(). value=${JSON.stringify(str)}`,\n );\n }\n}\n\n/**\n * Parse the given StringValue and return milliseconds.\n *\n * @param value - A typesafe StringValue to parse to milliseconds\n * @returns The parsed value in milliseconds, or `NaN` if the string can't be\n * parsed\n */\nexport function parseStrict(value: StringValue): number {\n return parse(value);\n}\n\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return `${Math.round(ms / y)}y`;\n }\n if (msAbs >= mo) {\n return `${Math.round(ms / mo)}mo`;\n }\n if (msAbs >= w) {\n return `${Math.round(ms / w)}w`;\n }\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms: number): StringValue {\n const msAbs = Math.abs(ms);\n if (msAbs >= y) {\n return plural(ms, msAbs, y, 'year');\n }\n if (msAbs >= mo) {\n return plural(ms, msAbs, mo, 'month');\n }\n if (msAbs >= w) {\n return plural(ms, msAbs, w, 'week');\n }\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n\n/**\n * Format the given integer as a string.\n *\n * @param ms - milliseconds\n * @param options - Options for the conversion\n * @returns The formatted string\n */\nexport function format(ms: number, options?: Options): string {\n if (typeof ms !== 'number' || !Number.isFinite(ms)) {\n throw new Error('Value provided to ms.format() must be of type number.');\n }\n\n return options?.long ? fmtLong(ms) : fmtShort(ms);\n}\n\n/**\n * Pluralization helper.\n */\nfunction plural(\n ms: number,\n msAbs: number,\n n: number,\n name: string,\n): StringValue {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}` as StringValue;\n}\n","/* eslint-disable no-console */\n\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms'\nimport type { Debug, Debugger } from './index.js'\n\nexport default function setup (env: any): Debug {\n createDebug.debug = createDebug\n createDebug.default = createDebug\n createDebug.coerce = coerce\n createDebug.disable = disable\n createDebug.enable = enable\n createDebug.enabled = enabled\n createDebug.humanize = humanize\n createDebug.destroy = destroy\n\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key]\n })\n\n /**\n * The currently active debug mode names, and names to skip.\n */\n\n createDebug.names = [] as any[]\n createDebug.skips = [] as any[]\n\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {} satisfies Record<string, any>\n\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor (namespace: string): number | string {\n let hash = 0\n\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i)\n hash |= 0 // Convert to 32bit integer\n }\n\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length]\n }\n createDebug.selectColor = selectColor\n\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug (namespace: string): Debugger {\n let prevTime: any\n let enableOverride: any = null\n let namespacesCache: any\n let enabledCache: any\n\n function debug (...args: any[]): void {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return\n }\n\n const self: any = debug\n\n // Set `diff` timestamp\n const curr = Number(new Date())\n const ms = curr - (prevTime || curr)\n self.diff = ms\n self.prev = prevTime\n self.curr = curr\n prevTime = curr\n\n args[0] = createDebug.coerce(args[0])\n\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O')\n }\n\n // Apply any `formatters` transformations\n let index = 0\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match: any, format: any): any => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%'\n }\n index++\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format]\n if (typeof formatter === 'function') {\n const val = args[index]\n match = formatter.call(self, val)\n\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1)\n index--\n }\n return match\n })\n\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args)\n\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log\n logFn.apply(self, args)\n }\n\n debug.namespace = namespace\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors()\n debug.color = createDebug.selectColor(namespace)\n debug.extend = extend\n debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.\n\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces\n enabledCache = createDebug.enabled(namespace)\n }\n\n return enabledCache\n },\n set: v => {\n enableOverride = v\n }\n })\n\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug)\n }\n\n // @ts-expect-error some properties are added dynamically\n return debug\n }\n\n function extend (this: any, namespace: string, delimiter: string): any {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace)\n newDebug.log = this.log\n return newDebug\n }\n\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable (namespaces: string): void {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces)\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces\n\n createDebug.names = []\n createDebug.skips = []\n\n let i\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/)\n const len = split.length\n\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue\n }\n\n namespaces = split[i].replace(/\\*/g, '.*?')\n\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'))\n } else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'))\n }\n }\n }\n\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable (): string {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',')\n createDebug.enable('')\n return namespaces\n }\n\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled (name: string): boolean {\n if (name[name.length - 1] === '*') {\n return true\n }\n\n let i\n let len\n\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false\n }\n }\n\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Convert regexp to namespace\n */\n function toNamespace (regexp: RegExp): string {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*')\n }\n\n /**\n * Coerce `val`.\n */\n function coerce (val: any): any {\n if (val instanceof Error) {\n return val.stack ?? val.message\n }\n return val\n }\n\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy (): void {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.')\n }\n\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters)\n\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load())\n\n // @ts-expect-error some properties are added dynamically\n return createDebug\n}\n","/* eslint-disable no-console */\n\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms'\nimport setup from './common.js'\n\nconst storage = localstorage()\n\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n]\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors (): boolean {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true\n }\n\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false\n }\n\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/))\n}\n\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs (this: any, args: any[]): void {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff)\n\n if (!this.useColors) {\n return\n }\n\n const c = 'color: ' + this.color\n args.splice(1, 0, c, 'color: inherit')\n\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0\n let lastC = 0\n args[0].replace(/%[a-zA-Z%]/g, (match: string) => {\n if (match === '%%') {\n return\n }\n index++\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index\n }\n })\n\n args.splice(lastC, 0, c)\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { })\n\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save (namespaces: string): void {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces)\n } else {\n storage?.removeItem('debug')\n }\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load (): string | null | undefined {\n let r\n try {\n r = storage?.getItem('debug')\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG\n }\n\n return r\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage (): Storage | undefined {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage\n } catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n\nfunction setupFormatters (formatters: any): void {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v: any) {\n try {\n return JSON.stringify(v)\n } catch (error: any) {\n return '[UnexpectedJSONParseError]: ' + error.message\n }\n }\n}\n\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log })\n","/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n\n/**\n * Module dependencies.\n */\nimport weald from './node.js'\nimport type ms from 'ms'\n\nexport interface Debug {\n (namespace: string): Debugger\n coerce(val: any): any\n disable(...args: string[]): string\n enable(namespaces: string | boolean): void\n enabled(namespaces: string): boolean\n formatArgs(this: Debugger, args: any[]): void\n log(...args: any[]): any\n selectColor(namespace: string): string | number\n humanize: typeof ms\n\n names: RegExp[]\n skips: RegExp[]\n\n formatters: Formatters\n\n inspectOpts?: {\n hideDate?: boolean | number | null\n colors?: boolean | number | null\n depth?: boolean | number | null\n showHidden?: boolean | number | null\n }\n}\n\nexport type Formatters = Record<string, (v: any) => string>\n\nexport interface Debugger {\n (formatter: any, ...args: any[]): void\n\n color: string\n diff: number\n enabled: boolean\n log(...args: any[]): any\n namespace: string\n destroy(): boolean\n extend(namespace: string, delimiter?: string): Debugger\n}\n\nexport default weald\n","/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: <stack trace>\n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\nimport { base32 } from 'multiformats/bases/base32'\nimport { base58btc } from 'multiformats/bases/base58'\nimport { base64 } from 'multiformats/bases/base64'\nimport debug from 'weald'\nimport { truncatePeerId } from './utils.js'\nimport type { PeerId, Logger, ComponentLogger } from '@libp2p/interface'\nimport type { Multiaddr } from '@multiformats/multiaddr'\nimport type { Key } from 'interface-datastore'\nimport type { CID } from 'multiformats/cid'\n\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base58btc.baseEncode(v)\n}\n\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base32.baseEncode(v)\n}\n\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v?: Uint8Array): string => {\n return v == null ? 'undefined' : base64.baseEncode(v)\n}\n\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v?: PeerId): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v?: CID): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v: Key): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v?: Multiaddr): string => {\n return v == null ? 'undefined' : v.toString()\n}\n\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v?: Error): string => {\n return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString()\n}\n\nexport type { Logger, ComponentLogger }\n\nfunction createDisabledLogger (namespace: string): debug.Debugger {\n const logger = (): void => {}\n logger.enabled = false\n logger.color = ''\n logger.diff = 0\n logger.log = (): void => {}\n logger.namespace = namespace\n logger.destroy = () => true\n logger.extend = () => logger\n\n return logger\n}\n\nexport interface PeerLoggerOptions {\n prefixLength: number\n suffixLength: number\n}\n\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger (peerId: PeerId, options: Partial<PeerLoggerOptions> = {}): ComponentLogger {\n return prefixLogger(truncatePeerId(peerId, options))\n}\n\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger (prefix: string): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(`${prefix}:${name}`)\n }\n }\n}\n\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger (): ComponentLogger {\n return {\n forComponent (name: string) {\n return logger(name)\n }\n }\n}\n\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger (name: string): Logger {\n // trace logging is a no-op by default\n let trace: debug.Debugger = createDisabledLogger(`${name}:trace`)\n\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r: any) => r.toString()).find((n: string) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`)\n }\n\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace,\n newScope: (scope: string) => logger(`${name}:${scope}`)\n })\n}\n\nexport function disable (): void {\n debug.disable()\n}\n\nexport function enable (namespaces: string): void {\n debug.enable(namespaces)\n}\n\nexport function enabled (namespaces: string): boolean {\n return debug.enabled(namespaces)\n}\n\nfunction notEmpty (str?: string): string | undefined {\n if (str == null) {\n return\n }\n\n str = str.trim()\n\n if (str.length === 0) {\n return\n }\n\n return str\n}\n","/**\n * @packageDocumentation\n *\n * Implements parsing and serialization of [IPNS Records](https://specs.ipfs.tech/ipns/ipns-record/).\n *\n * @example Create record\n *\n * ```TypeScript\n * import { createIPNSRecord } from 'ipns'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const privateKey = await generateKeyPair('Ed25519')\n * const value = 'hello world'\n * const sequenceNumber = 0\n * const lifetime = 3_600_000 // ms, e.g. one hour\n *\n * const ipnsRecord = await createIPNSRecord(privateKey, value, sequenceNumber, lifetime)\n * ```\n *\n * @example Validate record against public key\n *\n * ```TypeScript\n * import { validate } from 'ipns/validator'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const privateKey = await generateKeyPair('Ed25519')\n * const publicKey = privateKey.publicKey\n * const marshalledRecord = Uint8Array.from([0, 1, 2, 3])\n *\n * await validate(publicKey, marshalledRecord)\n * // if no error thrown, the record is valid\n * ```\n *\n * @example Validate record against routing key\n *\n * This is useful when validating IPNS names that use RSA keys, whose public key is embedded in the record (rather than in the routing key as with Ed25519).\n *\n * ```TypeScript\n * import { ipnsValidator } from 'ipns/validator'\n * import { multihashToIPNSRoutingKey } from 'ipns'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const privateKey = await generateKeyPair('Ed25519')\n * const routingKey = multihashToIPNSRoutingKey(privateKey.publicKey.toMultihash())\n * const marshalledRecord = Uint8Array.from([0, 1, 2, 3])\n *\n * await ipnsValidator(routingKey, marshalledRecord)\n * ```\n *\n * @example Extract public key from record\n *\n * ```TypeScript\n * import { extractPublicKeyFromIPNSRecord, createIPNSRecord } from 'ipns'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const privateKey = await generateKeyPair('Ed25519')\n * const record = await createIPNSRecord(privateKey, 'hello world', 0, 3_600_000)\n *\n * const publicKey = await extractPublicKeyFromIPNSRecord(record)\n * ```\n *\n * @example Marshal data with proto buffer\n *\n * ```TypeScript\n * import { createIPNSRecord, marshalIPNSRecord } from 'ipns'\n * import { generateKeyPair } from '@libp2p/crypto/keys'\n *\n * const privateKey = await generateKeyPair('Ed25519')\n * const record = await createIPNSRecord(privateKey, 'hello world', 0, 3_600_000)\n * // ...\n * const marshalledData = marshalIPNSRecord(record)\n * // ...\n * ```\n *\n * Returns the record data serialized.\n *\n * @example Unmarshal data from proto buffer\n *\n * ```TypeScript\n * import { unmarshalIPNSRecord } from 'ipns'\n *\n * const storedData = Uint8Array.from([0, 1, 2, 3, 4])\n * const ipnsRecord = unmarshalIPNSRecord(storedData)\n * ```\n *\n * Returns the `IPNSRecord` after being deserialized.\n */\n\nimport { publicKeyToProtobuf } from '@libp2p/crypto/keys'\nimport { logger } from '@libp2p/logger'\nimport NanoDate from 'timestamp-nano'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { SignatureCreationError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport { createCborData, ipnsRecordDataForV1Sig, ipnsRecordDataForV2Sig, normalizeValue } from './utils.js'\nimport type { PrivateKey, PublicKey } from '@libp2p/interface'\nimport type { Key } from 'interface-datastore/key'\nimport type { CID } from 'multiformats/cid'\nimport type { MultihashDigest } from 'multiformats/hashes/interface'\n\nconst log = logger('ipns')\nconst DEFAULT_TTL_NS = 5 * 60 * 1e+9 // 5 Minutes or 300 Seconds, as suggested by https://specs.ipfs.tech/ipns/ipns-record/#ttl-uint64\n\nexport const namespace = '/ipns/'\nexport const namespaceLength = namespace.length\n\nexport interface IPNSRecordV1V2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * signature of the record\n */\n signatureV1: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * expiration datetime for the record in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport interface IPNSRecordV2 {\n /**\n * value of the record\n */\n value: string\n\n /**\n * the v2 signature of the record\n */\n signatureV2: Uint8Array\n\n /**\n * Type of validation being used\n */\n validityType: IpnsEntry.ValidityType\n\n /**\n * If the validity type is EOL, this is the expiration datetime for the record\n * in RFC3339 format\n */\n validity: string\n\n /**\n * number representing the version of the record\n */\n sequence: bigint\n\n /**\n * ttl in nanoseconds\n */\n ttl?: bigint\n\n /**\n * the public portion of the key that signed this record (only present if it was not embedded in the IPNS key)\n */\n pubKey?: Uint8Array\n\n /**\n * extensible data\n */\n data: Uint8Array\n}\n\nexport type IPNSRecord = IPNSRecordV1V2 | IPNSRecordV2\n\nexport interface IPNSRecordData {\n Value: Uint8Array\n Validity: Uint8Array\n ValidityType: IpnsEntry.ValidityType\n Sequence: bigint\n TTL: bigint\n}\n\nexport interface IDKeys {\n routingPubKey: Key\n pkKey: Key\n routingKey: Key\n ipnsKey: Key\n}\n\nexport interface CreateOptions {\n ttlNs?: number | bigint\n v1Compatible?: boolean\n}\n\nexport interface CreateV2OrV1Options {\n v1Compatible: true\n}\n\nexport interface CreateV2Options {\n v1Compatible: false\n}\n\nconst defaultCreateOptions: CreateOptions = {\n v1Compatible: true,\n ttlNs: DEFAULT_TTL_NS\n}\n\n/**\n * Creates a new IPNS record and signs it with the given private key.\n * The IPNS Record validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {number} lifetime - lifetime of the record (in milliseconds).\n * @param {CreateOptions} options - additional create options.\n */\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecord (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, lifetime: number, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n // Validity in ISOString with nanoseconds precision and validity type EOL\n const expirationDate = new NanoDate(Date.now() + Number(lifetime))\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\n/**\n * Same as create(), but instead of generating a new Date, it receives the intended expiration time\n * WARNING: nano precision is not standard, make sure the value in seconds is 9 orders of magnitude lesser than the one provided.\n *\n * The passed value can be a CID, a PublicKey or an arbitrary string path e.g. `/ipfs/...` or `/ipns/...`.\n *\n * CIDs will be converted to v1 and stored in the record as a string similar to: `/ipfs/${cid}`\n * PublicKeys will create recursive records, eg. the record value will be `/ipns/${cidV1Libp2pKey}`\n * String paths will be stored in the record as-is, but they must start with `\"/\"`\n *\n * @param {PrivateKey} privateKey - the private key for signing the record.\n * @param {CID | PublicKey | string} value - content to be stored in the record.\n * @param {number | bigint} seq - number representing the current version of the record.\n * @param {string} expiration - expiration datetime for record in the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.\n * @param {CreateOptions} options - additional creation options.\n */\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options?: CreateV2OrV1Options): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateV2Options): Promise<IPNSRecordV2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions): Promise<IPNSRecordV1V2>\nexport async function createIPNSRecordWithExpiration (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, expiration: string, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> {\n const expirationDate = NanoDate.fromString(expiration)\n const validityType = IpnsEntry.ValidityType.EOL\n const ttlNs = BigInt(options.ttlNs ?? DEFAULT_TTL_NS)\n\n return _create(privateKey, value, seq, validityType, expirationDate.toString(), ttlNs, options)\n}\n\nconst _create = async (privateKey: PrivateKey, value: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string, seq: number | bigint, validityType: IpnsEntry.ValidityType, validity: string, ttl: bigint, options: CreateOptions = defaultCreateOptions): Promise<IPNSRecord> => {\n seq = BigInt(seq)\n const isoValidity = uint8ArrayFromString(validity)\n const normalizedValue = normalizeValue(value)\n const encodedValue = uint8ArrayFromString(normalizedValue)\n const data = createCborData(encodedValue, validityType, isoValidity, seq, ttl)\n const sigData = ipnsRecordDataForV2Sig(data)\n const signatureV2 = await privateKey.sign(sigData)\n let pubKey: Uint8Array | undefined\n\n // if we cannot derive the public key from the PeerId (e.g. RSA PeerIDs),\n // we have to embed it in the IPNS record\n if (privateKey.type === 'RSA') {\n pubKey = publicKeyToProtobuf(privateKey.publicKey)\n }\n\n if (options.v1Compatible === true) {\n const signatureV1 = await signLegacyV1(privateKey, encodedValue, validityType, isoValidity)\n\n const record: IPNSRecord = {\n value: normalizedValue,\n signatureV1,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n } else {\n const record: IPNSRecordV2 = {\n value: normalizedValue,\n validity,\n validityType,\n sequence: seq,\n ttl,\n signatureV2,\n data\n }\n\n if (pubKey != null) {\n record.pubKey = pubKey\n }\n\n return record\n }\n}\n\nexport { unmarshalIPNSRecord } from './utils.js'\nexport { marshalIPNSRecord } from './utils.js'\nexport { multihashToIPNSRoutingKey } from './utils.js'\nexport { multihashFromIPNSRoutingKey } from './utils.js'\nexport { extractPublicKeyFromIPNSRecord } from './utils.js'\n\n/**\n * Sign ipns record data using the legacy V1 signature scheme\n */\nconst signLegacyV1 = async (privateKey: PrivateKey, value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Promise<Uint8Array> => {\n try {\n const dataForSignature = ipnsRecordDataForV1Sig(value, validityType, validity)\n\n return await privateKey.sign(dataForSignature)\n } catch (error: any) {\n log.error('record signature creation failed', error)\n throw new SignatureCreationError('Record signature creation failed')\n }\n}\n","export class SignatureCreationError extends Error {\n static name = 'SignatureCreationError'\n\n constructor (message = 'Record signature creation failed') {\n super(message)\n this.name = 'SignatureCreationError'\n }\n}\n\nexport class SignatureVerificationError extends Error {\n static name = 'SignatureVerificationError'\n\n constructor (message = 'Record signature verification failed') {\n super(message)\n this.name = 'SignatureVerificationError'\n }\n}\n\nexport class RecordExpiredError extends Error {\n static name = 'RecordExpiredError'\n\n constructor (message = 'Record has expired') {\n super(message)\n this.name = 'RecordExpiredError'\n }\n}\n\nexport class UnsupportedValidityError extends Error {\n static name = 'UnsupportedValidityError'\n\n constructor (message = 'The validity type is unsupported') {\n super(message)\n this.name = 'UnsupportedValidityError'\n }\n}\n\nexport class RecordTooLargeError extends Error {\n static name = 'RecordTooLargeError'\n\n constructor (message = 'The record is too large') {\n super(message)\n this.name = 'RecordTooLargeError'\n }\n}\n\nexport class InvalidValueError extends Error {\n static name = 'InvalidValueError'\n\n constructor (message = 'Value must be a valid content path starting with /') {\n super(message)\n this.name = 'InvalidValueError'\n }\n}\n\nexport class InvalidRecordDataError extends Error {\n static name = 'InvalidRecordDataError'\n\n constructor (message = 'Invalid record data') {\n super(message)\n this.name = 'InvalidRecordDataError'\n }\n}\n\nexport class InvalidEmbeddedPublicKeyError extends Error {\n static name = 'InvalidEmbeddedPublicKeyError'\n\n constructor (message = 'Invalid embedded public key') {\n super(message)\n this.name = 'InvalidEmbeddedPublicKeyError'\n }\n}\n","import { decodeMessage, encodeMessage, enumeration, message } from 'protons-runtime'\nimport type { Codec, DecodeOptions } from 'protons-runtime'\nimport type { Uint8ArrayList } from 'uint8arraylist'\n\nexport interface IpnsEntry {\n value?: Uint8Array\n signatureV1?: Uint8Array\n validityType?: IpnsEntry.ValidityType\n validity?: Uint8Array\n sequence?: bigint\n ttl?: bigint\n pubKey?: Uint8Array\n signatureV2?: Uint8Array\n data?: Uint8Array\n}\n\nexport namespace IpnsEntry {\n export enum ValidityType {\n EOL = 'EOL'\n }\n\n enum __ValidityTypeValues {\n EOL = 0\n }\n\n export namespace ValidityType {\n export const codec = (): Codec<ValidityType> => {\n return enumeration<ValidityType>(__ValidityTypeValues)\n }\n }\n\n let _codec: Codec<IpnsEntry>\n\n export const codec = (): Codec<IpnsEntry> => {\n if (_codec == null) {\n _codec = message<IpnsEntry>((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork()\n }\n\n if (obj.value != null) {\n w.uint32(10)\n w.bytes(obj.value)\n }\n\n if (obj.signatureV1 != null) {\n w.uint32(18)\n w.bytes(obj.signatureV1)\n }\n\n if (obj.validityType != null) {\n w.uint32(24)\n IpnsEntry.ValidityType.codec().encode(obj.validityType, w)\n }\n\n if (obj.validity != null) {\n w.uint32(34)\n w.bytes(obj.validity)\n }\n\n if (obj.sequence != null) {\n w.uint32(40)\n w.uint64(obj.sequence)\n }\n\n if (obj.ttl != null) {\n w.uint32(48)\n w.uint64(obj.ttl)\n }\n\n if (obj.pubKey != null) {\n w.uint32(58)\n w.bytes(obj.pubKey)\n }\n\n if (obj.signatureV2 != null) {\n w.uint32(66)\n w.bytes(obj.signatureV2)\n }\n\n if (obj.data != null) {\n w.uint32(74)\n w.bytes(obj.data)\n }\n\n if (opts.lengthDelimited !== false) {\n w.ldelim()\n }\n }, (reader, length, opts = {}) => {\n const obj: any = {}\n\n const end = length == null ? reader.len : reader.pos + length\n\n while (reader.pos < end) {\n const tag = reader.uint32()\n\n switch (tag >>> 3) {\n case 1: {\n obj.value = reader.bytes()\n break\n }\n case 2: {\n obj.signatureV1 = reader.bytes()\n break\n }\n case 3: {\n obj.validityType = IpnsEntry.ValidityType.codec().decode(reader)\n break\n }\n case 4: {\n obj.validity = reader.bytes()\n break\n }\n case 5: {\n obj.sequence = reader.uint64()\n break\n }\n case 6: {\n obj.ttl = reader.uint64()\n break\n }\n case 7: {\n obj.pubKey = reader.bytes()\n break\n }\n case 8: {\n obj.signatureV2 = reader.bytes()\n break\n }\n case 9: {\n obj.data = reader.bytes()\n break\n }\n default: {\n reader.skipType(tag & 7)\n break\n }\n }\n }\n\n return obj\n })\n }\n\n return _codec\n }\n\n export const encode = (obj: Partial<IpnsEntry>): Uint8Array => {\n return encodeMessage(obj, IpnsEntry.codec())\n }\n\n export const decode = (buf: Uint8Array | Uint8ArrayList, opts?: DecodeOptions<IpnsEntry>): IpnsEntry => {\n return decodeMessage(buf, IpnsEntry.codec(), opts)\n }\n}\n","import { publicKeyFromProtobuf } from '@libp2p/crypto/keys'\nimport { InvalidMultihashError } from '@libp2p/interface'\nimport { logger } from '@libp2p/logger'\nimport * as cborg from 'cborg'\nimport { base36 } from 'multiformats/bases/base36'\nimport { CID } from 'multiformats/cid'\nimport * as Digest from 'multiformats/hashes/digest'\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat'\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals'\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string'\nimport { InvalidRecordDataError, InvalidValueError, SignatureVerificationError, UnsupportedValidityError } from './errors.js'\nimport { IpnsEntry } from './pb/ipns.js'\nimport type { IPNSRecord, IPNSRecordV2, IPNSRecordData } from './index.js'\nimport type { PublicKey } from '@libp2p/interface'\nimport type { MultihashDigest } from 'multiformats/cid'\n\nconst log = logger('ipns:utils')\nconst IPNS_PREFIX = uint8ArrayFromString('/ipns/')\nconst LIBP2P_CID_CODEC = 0x72\nconst IDENTITY_CODEC = 0x0\nconst SHA2_256_CODEC = 0x12\n\n/**\n * Extracts a public key from the passed PeerId, falling back to the pubKey\n * embedded in the ipns record\n */\nexport function extractPublicKeyFromIPNSRecord (record: IPNSRecord | IPNSRecordV2): PublicKey | undefined {\n let pubKey: PublicKey | undefined\n\n if (record.pubKey != null) {\n try {\n pubKey = publicKeyFromProtobuf(record.pubKey)\n } catch (err) {\n log.error(err)\n throw err\n }\n }\n\n if (pubKey != null) {\n return pubKey\n }\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV1Sig (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array): Uint8Array {\n const validityTypeBuffer = uint8ArrayFromString(validityType)\n\n return uint8ArrayConcat([value, validity, validityTypeBuffer])\n}\n\n/**\n * Utility for creating the record data for being signed\n */\nexport function ipnsRecordDataForV2Sig (data: Uint8Array): Uint8Array {\n const entryData = uint8ArrayFromString('ipns-signature:')\n\n return uint8ArrayConcat([entryData, data])\n}\n\nexport function marshalIPNSRecord (obj: IPNSRecord | IPNSRecordV2): Uint8Array {\n if ('signatureV1' in obj) {\n return IpnsEntry.encode({\n value: uint8ArrayFromString(obj.value),\n signatureV1: obj.signatureV1,\n validityType: obj.validityType,\n validity: uint8ArrayFromString(obj.validity),\n sequence: obj.sequence,\n ttl: obj.ttl,\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n } else {\n return IpnsEntry.encode({\n pubKey: obj.pubKey,\n signatureV2: obj.signatureV2,\n data: obj.data\n })\n }\n}\n\nexport function unmarshalIPNSRecord (buf: Uint8Array): IPNSRecord {\n const message = IpnsEntry.decode(buf)\n\n // protobufjs returns bigints as numbers\n if (message.sequence != null) {\n message.sequence = BigInt(message.sequence)\n }\n\n // protobufjs returns bigints as numbers\n if (message.ttl != null) {\n message.ttl = BigInt(message.ttl)\n }\n\n // Check if we have the data field. If we don't, we fail. We've been producing\n // V1+V2 records for quite a while and we don't support V1-only records during\n // validation any more\n if (message.signatureV2 == null || message.data == null) {\n throw new SignatureVerificationError('Missing data or signatureV2')\n }\n\n const data = parseCborData(message.data)\n const value = normalizeByteValue(data.Value)\n const validity = uint8ArrayToString(data.Validity)\n\n if (message.value != null && message.signatureV1 != null) {\n // V1+V2\n validateCborDataMatchesPbData(message)\n\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV1: message.signatureV1,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else if (message.signatureV2 != null) {\n // V2-only\n return {\n value,\n validityType: IpnsEntry.ValidityType.EOL,\n validity,\n sequence: data.Sequence,\n ttl: data.TTL,\n pubKey: message.pubKey,\n signatureV2: message.signatureV2,\n data: message.data\n }\n } else {\n throw new Error('invalid record: does not include signatureV1 or signatureV2')\n }\n}\n\nexport function multihashToIPNSRoutingKey (digest: MultihashDigest<0x00 | 0x12>): Uint8Array {\n return uint8ArrayConcat([\n IPNS_PREFIX,\n digest.bytes\n ])\n}\n\nexport function multihashFromIPNSRoutingKey (key: Uint8Array): MultihashDigest<0x00 | 0x12> {\n const digest = Digest.decode(key.slice(IPNS_PREFIX.length))\n\n if (!isCodec(digest, IDENTITY_CODEC) && !isCodec(digest, SHA2_256_CODEC)) {\n throw new InvalidMultihashError('Multihash in IPNS key was not identity or sha2-256')\n }\n\n return digest\n}\n\nexport function createCborData (value: Uint8Array, validityType: IpnsEntry.ValidityType, validity: Uint8Array, sequence: bigint, ttl: bigint): Uint8Array {\n let ValidityType\n\n if (validityType === IpnsEntry.ValidityType.EOL) {\n ValidityType = 0\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n const data = {\n Value: value,\n Validity: validity,\n ValidityType,\n Sequence: sequence,\n TTL: ttl\n }\n\n return cborg.encode(data)\n}\n\nexport function parseCborData (buf: Uint8Array): IPNSRecordData {\n const data = cborg.decode(buf)\n\n if (data.ValidityType === 0) {\n data.ValidityType = IpnsEntry.ValidityType.EOL\n } else {\n throw new UnsupportedValidityError('The validity type is unsupported')\n }\n\n if (Number.isInteger(data.Sequence)) {\n // sequence must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.Sequence = BigInt(data.Sequence)\n }\n\n if (Number.isInteger(data.TTL)) {\n // ttl must be a BigInt, but DAG-CBOR doesn't preserve this for Numbers within the safe-integer range\n data.TTL = BigInt(data.TTL)\n }\n\n return data\n}\n\nexport function normalizeByteValue (value: Uint8Array): string {\n const string = uint8ArrayToString(value).trim()\n\n // if we have a path, check it is a valid path\n if (string.startsWith('/')) {\n return string\n }\n\n // try parsing what we have as CID bytes or a CID string\n try {\n return `/ipfs/${CID.decode(value).toV1().toString()}`\n } catch {\n // fall through\n }\n\n try {\n return `/ipfs/${CID.parse(string).toV1().toString()}`\n } catch {\n // fall through\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\n/**\n * Normalizes the given record value. It ensures it is a PeerID, a CID or a\n * string starting with '/'. PeerIDs become `/ipns/${cidV1Libp2pKey}`,\n * CIDs become `/ipfs/${cidAsV1}`.\n */\nexport function normalizeValue (value?: CID | PublicKey | MultihashDigest<0x00 | 0x12> | string): string {\n if (value != null) {\n const cid = asCID(value)\n\n // if we have a CID, turn it into an ipfs path\n if (cid != null) {\n // PeerID encoded as a CID\n if (cid.code === LIBP2P_CID_CODEC) {\n return `/ipns/${cid.toString(base36)}`\n }\n\n return `/ipfs/${cid.toV1().toString()}`\n }\n\n if (hasBytes(value)) {\n return `/ipns/${base36.encode(value.bytes)}`\n }\n\n // if we have a path, check it is a valid path\n const string = value.toString().trim()\n\n if (string.startsWith('/') && string.length > 1) {\n return string\n }\n }\n\n throw new InvalidValueError('Value must be a valid content path starting with /')\n}\n\nfunction validateCborDataMatchesPbData (entry: IpnsEntry): void {\n if (entry.data == null) {\n throw new InvalidRecordDataError('Record data is missing')\n }\n\n const data = parseCborData(entry.data)\n\n if (!uint8ArrayEquals(data.Value, entry.value ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"value\" did not match between protobuf and CBOR')\n }\n\n if (!uint8ArrayEquals(data.Validity, entry.validity ?? new Uint8Array(0))) {\n throw new SignatureVerificationError('Field \"validity\" did not match between protobuf and CBOR')\n }\n\n if (data.ValidityType !== entry.validityType) {\n throw new SignatureVerificationError('Field \"validityType\" did not match between protobuf and CBOR')\n }\n\n if (data.Sequence !== entry.sequence) {\n throw new SignatureVerificationError('Field \"sequence\" did not match between protobuf and CBOR')\n }\n\n if (data.TTL !== entry.ttl) {\n throw new SignatureVerificationError('Field \"ttl\" did not match between protobuf and CBOR')\n }\n}\n\nfunction hasBytes (obj?: any): obj is { bytes: Uint8Array } {\n return obj.bytes instanceof Uint8Array\n}\n\nfunction hasToCID (obj?: any): obj is { toCID(): CID } {\n return typeof obj?.toCID === 'function'\n}\n\nfunction asCID (obj?: any): CID | null {\n if (hasToCID(obj)) {\n return obj.toCID()\n }\n\n // try parsing as a CID string\n try {\n return CID.parse(obj)\n } catch {\n // fall through\n }\n\n return CID.asCID(obj)\n}\n\nexport function isCodec <T extends number> (digest: MultihashDigest, codec: T): digest is MultihashDigest<T> {\n return digest.code === codec\n}\n","import { 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 { createIPNSRecord, marshalIPNSRecord, unmarshalIPNSRecord } from 'ipns'\nimport { privateKeyFromRaw } from '@libp2p/crypto/keys'\nimport { base36 } from 'multiformats/bases/base36'\nimport { base64pad } from 'multiformats/bases/base64'\nimport type { CID } from 'multiformats/cid'\n\nexport interface SignedIPNSRecord {\n\trecordBytes: Uint8Array // marshalled protobuf, signed — the wire format\n\tipnsName: string // k51... string\n\tvalue: string // /ipfs/<cid>\n\tsequence: bigint\n}\n\n/** Derive IPNS name string (k51...) from Ed25519 private key bytes */\nexport function ipnsNameFromPrivateKey(privKeyBytes: Uint8Array): string {\n\tconst privKey = privateKeyFromRaw(privKeyBytes)\n\treturn privKey.publicKey.toCID().toString(base36)\n}\n\n/**\n * Create a signed IPNS record (protobuf wire format).\n * Same bytes can be published to any naming service.\n */\nexport async function createSignedIPNSRecord(\n\tprivateKey: Uint8Array,\n\tcid: CID,\n\tsequence: bigint,\n\tlifetimeMs = 365 * 24 * 60 * 60 * 1000, // 1 year\n): Promise<SignedIPNSRecord> {\n\tconst privKey = privateKeyFromRaw(privateKey)\n\tconst value = `/ipfs/${cid.toV1()}`\n\tconst record = await createIPNSRecord(privKey, value, sequence, lifetimeMs)\n\tconst recordBytes = marshalIPNSRecord(record)\n\tconst ipnsName = privKey.publicKey.toCID().toString(base36)\n\treturn { recordBytes, ipnsName, value, sequence }\n}\n\nexport { unmarshalIPNSRecord }\n\n/** A target that can receive a signed IPNS record */\nexport interface IPNSPublishTarget {\n\tname: string\n\tpublish(ipnsName: string, recordBytes: Uint8Array): Promise<void>\n}\n\n/**\n * Resolve current IPNS sequence number from a naming service.\n * Returns null if the name was never published (404).\n * Throws on network/server errors.\n */\nexport async function resolveIPNSSequence(\n\tnameServiceUrl: string,\n\tipnsName: string,\n): Promise<bigint | null> {\n\tconst url = `${nameServiceUrl}/name/${ipnsName}`\n\tlet response: Response\n\ttry {\n\t\tresponse = await fetch(url)\n\t} catch (err) {\n\t\tthrow new Error(`Network error resolving IPNS ${ipnsName}: ${err}`)\n\t}\n\n\tif (response.status === 404) return null\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP ${response.status} resolving IPNS ${ipnsName}: ${response.statusText}`)\n\t}\n\n\tconst { record, value } = await response.json()\n\tif (!record && !value) return null // never published\n\n\t// If raw record is available, unmarshal to get sequence\n\tif (record) {\n\t\tconst bytes = base64pad.baseDecode(record)\n\t\tconst entry = unmarshalIPNSRecord(bytes)\n\t\treturn entry.sequence\n\t}\n\n\t// Some servers return value but not raw record — can't get sequence\n\treturn 0n\n}\n\n/**\n * Create a signed IPNS record and publish to all configured targets.\n * Resolves sequence from sequenceServiceUrl, creates record once, fans out.\n * Throws if ALL targets fail; warns on partial failure.\n */\nexport async function publishIPNSRecord(\n\tprivateKey: Uint8Array,\n\tcid: CID,\n\ttargets: IPNSPublishTarget[],\n\tsequenceServiceUrl = 'https://name.web3.storage',\n): Promise<SignedIPNSRecord> {\n\tconst ipnsName = ipnsNameFromPrivateKey(privateKey)\n\tconst currentSeq = await resolveIPNSSequence(sequenceServiceUrl, ipnsName)\n\tconst sequence = currentSeq != null ? currentSeq + 1n : 0n\n\tconst signed = await createSignedIPNSRecord(privateKey, cid, sequence)\n\n\tconst results = await Promise.allSettled(\n\t\ttargets.map(t => t.publish(ipnsName, signed.recordBytes))\n\t)\n\tconst failures = results\n\t\t.map((r, i) => ({ r, name: targets[i].name }))\n\t\t.filter(({ r }) => r.status === 'rejected') as { r: PromiseRejectedResult; name: string }[]\n\n\tif (failures.length > 0 && failures.length < targets.length) {\n\t\t// Partial failure — log but don't throw\n\t\tfor (const { r, name } of failures) {\n\t\t\tconsole.warn(`[publishIPNSRecord] target '${name}' failed:`, r.reason)\n\t\t}\n\t} else if (failures.length === targets.length) {\n\t\tthrow new Error(`All IPNS publish targets failed: ${failures.map(({ r, name }) => `${name}: ${r.reason}`).join('; ')}`)\n\t}\n\n\treturn signed\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAI,aAAU,WAAU;AAAC,qBAAa,OAAO,WAAS,OAAO,UAAQA;AAAG,UAAIC,KAAE,OAAMC,KAAE,MAAK,IAAE,SAAOA,KAAE,KAAIC,KAAEF,KAAE,GAAEG,KAAE,MAAID,IAAEE,KAAE,QAAO,IAAE,YAAW,IAAE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AK;AACvC,WAAO,MAAM;AAAA,EACd;AAGA,SAAO;AACR;AAOA,eAAsB,kBACrB,YACA,KACA,SACA,qBAAqB,6BACO;AAC5B,QAAM,WAAW,uBAAuB,UAAU;AAClD,QAAM,aAAa,MAAM,oBAAoB,oBAAoB,QAAQ;AACzE,QAAM,WAAW,cAAc,OAAO,aAAa,KAAK;AACxD,QAAM,SAAS,MAAM,uBAAuB,YAAY,KAAK,QAAQ;AAErE,QAAM,UAAU,MAAM,QAAQ;AAAA,IAC7B,QAAQ,IAAI,CAAAC,OAAKA,GAAE,QAAQ,UAAU,OAAO,WAAW,CAAC;AAAA,EACzD;AACA,QAAM,WAAW,QACf,IAAI,CAACC,IAAGC,QAAO,EAAE,GAAAD,IAAG,MAAM,QAAQC,EAAC,EAAE,KAAK,EAAE,EAC5C,OAAO,CAAC,EAAE,GAAAD,GAAE,MAAMA,GAAE,WAAW,UAAU;AAE3C,MAAI,SAAS,SAAS,KAAK,SAAS,SAAS,QAAQ,QAAQ;AAE5D,eAAW,EAAE,GAAAA,IAAG,MAAAE,MAAK,KAAK,UAAU;AACnC,cAAQ,KAAK,+BAA+BA,KAAI,aAAaF,GAAE,MAAM;AAAA,IACtE;AAAA,EACD,WAAW,SAAS,WAAW,QAAQ,QAAQ;AAC9C,UAAM,IAAI,MAAM,oCAAoC,SAAS,IAAI,CAAC,EAAE,GAAAA,IAAG,MAAAE,MAAK,MAAM,GAAGA,KAAI,KAAKF,GAAE,MAAM,EAAE,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,EACvH;AAEA,SAAO;AACR;","names":["d","l","s","e","f","c","m","n","t","o","r","p","u","a","i","message","encode","a","i","length","length","i","c","p","c","i","encode","decode","identity_exports","identity","identity","sha256","sha512","name","sha256","from","sha512","identity_exports","name","encode","decode","string","i","fromString","string","toString","length","i","byte","message","d","toString","fromString","message","n","n","n","n","i","f","_0n","_1n","a","_0n","a","_1n","r","m","n","n2","i","c","t","p","d","n","_1n","zero","n","_0n","_1n","a","length","_1n","_0n","_1n","c","p","i","n","window","n","_0n","p","d","_1n","window","i","f","p","_0n","_0n","_1n","_2n","_8n","n","uvRatio","e","p","a","d","f","randomBytes","adjustScalarBytes","r","s","_1n","_1n","_2n","_5n","_8n","_2n","_1n","message","toString","hashAndSign","hashAndVerify","hashAndVerify","message","hashAndSign","privateKeyBytes","publicKeyBytes","length","string","c","i","t","length","i","size","alloc","fromString","message","CODEC_TYPES","createCodec","name","encode","decode","encode","decode","createCodec","encode","decode","createCodec","KeyType","__KeyTypeValues","PublicKey","length","PrivateKey","digest","hashAndVerify","message","hashAndSign","message","toString","fromString","digest","hashAndSign","hashAndVerify","fromString","i","message","_2n","n","_0n","_1n","m","t","length","_3n","_4n","p","a","endo","f","p2","l","s","randomBytes","hmac","_2n","_1n","r","_0n","message","d","e","m","_2n","_3n","PRIVATE_KEY_BYTE_LENGTH","hashAndSign","p","sha256","digest","hashAndVerify","hashAndVerify","message","hashAndSign","PRIVATE_KEY_BYTE_LENGTH","message","value: StringValue | number","options?: Options","e","t","str: string","s","c","l","d","f","ms: number","c","ms","options?: Options","t","msAbs: number","n: number","name: string","i","n","r","coerce","namespace","i","name","c","r","namespace","logger","name","r","n","message","message","message","IpnsEntry","ValidityType","__ValidityTypeValues","length","log","fromString","fromString","message","toString","string","toString","log","NanoDate","fromString","log","base64","rfc4648","base36","t","r","i","name"]}