UNPKG

@scure/starknet

Version:

Audited & minimal implementation of Starknet cryptography including Pedersen and Stark Curve

372 lines 16.2 kB
/*! scure-starknet - MIT License (c) 2022 Paul Miller (paulmillr.com) */ import { type IField } from '@noble/curves/abstract/modular.js'; import { poseidon } from '@noble/curves/abstract/poseidon.js'; import { type ECDSASignature, type ECDSASignatureCons, type ECDSASignatureFormat, type ECDSASignOpts, type WeierstrassPoint, type WeierstrassPointCons } from '@noble/curves/abstract/weierstrass.js'; import { type TArg, type TRet } from '@noble/hashes/utils.js'; type Hex = Uint8Array | string; type PrivKey = Hex | bigint; type SignOpts = Omit<ECDSASignOpts, 'prehash'> & { prehash?: false; }; type VerifyOpts = { format?: ECDSASignatureFormat; }; /** Upper bound for Stark message hashes and `Signature.r` values. */ export declare const MAX_VALUE: bigint; /** * Stark-friendly short Weierstrass point constructor. * @example * Reach for the curve point constructor when you need low-level Stark curve math. * ```ts * Point.BASE.toBytes(true); * ``` */ declare const Point: WeierstrassPointCons<bigint>; /** * Normalizes a Stark private key into a 32-byte lowercase hex string without `0x`. * @param privKey - private key as bytes or hex * @returns Zero-padded private key hex. * Assumes `privKey` encodes at most 32 bytes. * Longer inputs are preserved here and rejected later by curve operations. * @example * Normalize a short hex string into the canonical 32-byte Stark private key form. * ```ts * normalizePrivateKey('1'); * ``` */ export declare function normalizePrivateKey(privKey: TArg<Hex>): string; /** * Derives a Stark public key from a private key. * @param privKey - private key as bytes or hex * @param isCompressed - whether to return the compressed public key format * @returns Encoded Stark public key bytes. * @example * Derive the Stark public key from a private key. * ```ts * getPublicKey('1'); * ``` */ export declare function getPublicKey(privKey: TArg<Hex>, isCompressed?: boolean): TRet<Uint8Array>; /** * Computes the Stark ECDH shared secret for a private key and peer public key. * @param privKeyA - local private key as bytes or hex * @param pubKeyB - peer public key as bytes or hex * @returns Compressed shared point bytes. * Intentional API-compatibility behavior for existing callers. * This mirrors noble-curves' ECDH helper and returns the compressed shared curve * point, not the SEC 1 raw x-coordinate or KDF input. * @example * Compute the shared secret from one private key and the peer public key. * ```ts * import { getPublicKey, getSharedSecret } from '@scure/starknet'; * getSharedSecret('1', getPublicKey('2')); * ``` */ export declare function getSharedSecret(privKeyA: TArg<Hex>, pubKeyB: TArg<Hex>): TRet<Uint8Array>; /** * Signs a Stark message hash without prehashing it first. * @param msgHash - message hash inside the Stark field range * @param privKey - private key as bytes or hex * @param opts - Optional ECDSA signing overrides. See {@link SignOpts}; `prehash: true` is not exposed because this wrapper signs a prehashed Stark message. Explicit `format` values are accepted and decoded back into the returned `Signature`. * @returns Parsed Stark ECDSA signature. * If `opts.format` is `'recovered'`, the returned `Signature` preserves the recovery bit. * @throws On unsupported `opts.prehash` overrides. {@link TypeError} * @throws On Stark message hashes or signature values outside the Stark field range. {@link RangeError} * @example * Sign a prehashed Stark message with a private key. * ```ts * sign('1', '2'); * ``` */ export declare function sign(msgHash: TArg<Hex>, privKey: TArg<Hex>, opts?: TArg<SignOpts>): ECDSASignature; /** * Verifies a Stark signature against a message hash and public key. * @param signature - signature object or encoded signature bytes/hex * @param msgHash - message hash inside the Stark field range * @param pubKey - public key as bytes or hex * @param opts - Optional byte-signature decode options. See {@link VerifyOpts}; pass `format` to bypass legacy DER-first fallback and decode compact, recovered, or DER explicitly. * @returns Whether the signature is valid for the message hash. * @throws On Stark message hashes or signature values outside the Stark field range. {@link RangeError} * @example * Verify a Stark signature against the message hash and public key. * ```ts * import { getPublicKey, sign, verify } from '@scure/starknet'; * const msgHash = '1'; * const privKey = '2'; * verify(sign(msgHash, privKey), msgHash, getPublicKey(privKey)); * ``` */ export declare function verify(signature: TArg<ECDSASignature | Hex>, msgHash: TArg<Hex>, pubKey: TArg<Hex>, opts?: VerifyOpts): boolean; /** * Stark ECDSA signature constructor and byte decoders. * Direct alias of noble's signature class: validates `r`/`s` and supports compact, DER, and * recovered encodings. * @example * Construct a Stark signature object and serialize it back to hex. * ```ts * new Signature(1n, 2n).toHex(); * ``` */ declare const Signature: ECDSASignatureCons; /** * Helper methods for Stark private keys and point precomputation. * Private-key helpers treat string/Uint8Array inputs as raw secret-key bytes; `precompute()` * mutates and returns the supplied point. * @example * Check whether a candidate private key lies in the Stark scalar field. * ```ts * utils.isValidPrivateKey('01'); * ``` */ declare const utils: { normPrivateKeyToScalar: (key: TArg<PrivKey>) => bigint; isValidPrivateKey(privateKey: PrivKey): boolean; randomPrivateKey: () => Uint8Array; precompute: (windowSize?: number, point?: WeierstrassPoint<bigint>) => WeierstrassPoint<bigint>; }; export { Point, Signature, utils }; /** * Derives a Stark private key from arbitrary seed material with rejection sampling. * @param seed - seed bytes or hex * @returns Hex private key suitable for Stark signatures. * Returns lowercase hex without `0x` or left padding; callers that need the canonical 32-byte form * should normalize it separately. * @throws If rejection sampling does not find a valid Stark private key within the retry limit. {@link Error} * @example * Grind arbitrary seed material into a Stark private key. * ```ts * grindKey('01'); * ``` */ export declare function grindKey(seed: TArg<Hex>): string; /** * Derives the Stark key x-coordinate for a private key. * @param privateKey - private key as bytes or hex * @returns Stark key hex string with `0x` prefix. * Returns only the canonical unpadded x-coordinate string, not the SEC 1 compressed point bytes. * @example * Extract the Stark public key x-coordinate as a hex string. * ```ts * getStarkKey('1'); * ``` */ export declare function getStarkKey(privateKey: TArg<Hex>): string; /** * Turns a 65-byte Ethereum signature into a Stark private key. * @param signature - Ethereum signature hex with `0x` prefix * @returns Stark private key hex. * Uses the signature's 32-byte `r` component as the grinding seed. * @throws If grinding the Ethereum signature fails to produce a Stark private key within the retry limit. {@link Error} * @throws On wrong Ethereum signature type. {@link TypeError} * @throws On wrong Ethereum signature length. {@link RangeError} * @example * Convert an Ethereum signature into deterministic Stark key material. * ```ts * ethSigToPrivate( * '0x21fbf0696d5e0aa2ef41a2b4ffb623bcaf070461d61cf7251c74161f82fec3a43' + * '70854bc0a34b3ab487c1bc021cd318c734c51ae29374f2beb0e6f2dd49b4bf41c' * ); * ``` */ export declare function ethSigToPrivate(signature: string): string; /** * Builds the StarkEx account derivation path for a layer, application, address, and index. * @param layer - StarkEx layer name * @param application - StarkEx application name * @param ethereumAddress - Ethereum address used in derivation * @param index - Final unhardened BIP32 child index inside the derived subtree; should be an integer in `[0, 2^31)`. * @returns BIP32 derivation path string. * @throws On wrong index types. {@link TypeError} * @throws On invalid index ranges or values. {@link RangeError} * @example * Derive the StarkEx account path for one wallet and account index. * ```ts * getAccountPath('starkex', 'starkdeployement', '0x1', 0); * ``` */ export declare function getAccountPath(layer: string, application: string, ethereumAddress: string, index: number): string; type PedersenArg = Hex | bigint | number; /** * Computes the Starknet Pedersen hash of two field elements. * @param x - first field element as bytes, hex, bigint, or safe integer * @param y - second field element as bytes, hex, bigint, or safe integer * @returns Pedersen hash as `0x`-prefixed hex. * Returns the canonical unpadded x-coordinate string of the final Pedersen point, not a full point * encoding. * @throws If Pedersen point encoding fails unexpectedly. {@link Error} * @throws On Pedersen inputs outside the Stark field range. {@link RangeError} * @example * Compute the Pedersen hash of two Stark field elements. * ```ts * pedersen(1, 2); * ``` */ export declare function pedersen(x: TArg<PedersenArg>, y: TArg<PedersenArg>): string; /** * Hashes a list of elements with Pedersen while preserving input order and appending the length. * @param data - elements to hash * @param fn - Pairwise fold function, called as `fn(acc, next)` for each * element and once more with `data.length`. * @returns Folded hash result. * @example * Hash an ordered list of elements with the Starknet Pedersen fold. * ```ts * computeHashOnElements([1, 2, 3]); * ``` */ export declare const computeHashOnElements: (data: TArg<PedersenArg[]>, fn?: typeof pedersen) => TRet<PedersenArg>; /** * Computes Starknet keccak by truncating Keccak-256 to 250 bits. * @param data - bytes to hash * @returns Hash as a bigint field element. * Keeps the low 250 bits of the Keccak-256 digest; it does not right-shift or reduce modulo * the Stark field. * @example * Compute Starknet keccak for raw bytes. * ```ts * keccak(new Uint8Array([1, 2, 3])); * ``` */ export declare const keccak: (data: TArg<Uint8Array>) => bigint; /** * Prime field used by Starknet Poseidon: `2^251 + 17 * 2^192 + 1`. * Despite the name, canonical encodings still occupy 32 big-endian bytes because `p > 2^251`. * @example * Construct one field element in the Starknet Poseidon field. * ```ts * Fp251.create(1n); * ``` */ export declare const Fp251: Readonly<IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>>; export declare function _poseidonMDS(Fp: IField<bigint>, name: string, m: number, attempt?: number): bigint[][]; /** Poseidon permutation configuration. */ export type PoseidonOpts = { /** Prime field used by the permutation. */ Fp: IField<bigint>; /** Number of message elements absorbed per permutation. */ rate: number; /** Number of capacity elements reserved for domain separation. */ capacity: number; /** Count of full rounds with a nonlinear layer on every lane; must be even so Poseidon can * split them around the partial rounds. */ roundsFull: number; /** Count of partial rounds with a nonlinear layer on one lane. */ roundsPartial: number; }; /** Poseidon permutation instance returned by the Starknet helpers. */ export type PoseidonFn = ReturnType<typeof poseidon> & { /** Total permutation width (`rate + capacity`). */ m: number; /** Number of message elements absorbed per permutation. */ rate: number; /** Number of capacity elements reserved for domain separation. */ capacity: number; }; /** * Creates a Poseidon permutation from explicit parameters and an MDS matrix. * @param opts - Poseidon permutation parameters. See {@link PoseidonOpts}. * @param mds - MDS matrix used by the permutation * @returns Poseidon permutation with Starknet metadata. * @throws On wrong Poseidon option types. {@link TypeError} * @throws On invalid Poseidon option ranges. {@link RangeError} * @example * Create a Poseidon permutation from explicit parameters and an MDS matrix. * ```ts * import { Fp251, poseidonBasic } from '@scure/starknet'; * poseidonBasic( * { Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }, * [ * [3n, 1n, 1n], * [1n, -1n, 1n], * [1n, 1n, -2n], * ] * ); * ``` */ export declare function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]): PoseidonFn; /** * Creates a Starknet-compatible Poseidon permutation from parameters and an MDS attempt index. * @param opts - Poseidon permutation parameters. See {@link PoseidonOpts}. * @param mdsAttempt - attempt index used to derive the MDS matrix * @returns Poseidon permutation with Starknet metadata. * @throws If the derived Poseidon MDS matrix is invalid. {@link Error} * @throws On wrong Poseidon option or attempt types. {@link TypeError} * @throws On invalid Poseidon option or attempt ranges. {@link RangeError} * @example * Create the default Starknet-compatible Poseidon permutation from parameters alone. * ```ts * import { Fp251, poseidonCreate } from '@scure/starknet'; * poseidonCreate({ Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }); * ``` */ export declare function poseidonCreate(opts: PoseidonOpts, mdsAttempt?: number): PoseidonFn; /** * Default Starknet Poseidon permutation. * Uses the fixed width-3 vector-backed MDS matrix, not the generated `HadesMDS` path from {@link poseidonCreate}. * @param values - Poseidon state vector to permute. * @returns Permuted Poseidon state vector. * @example * Feed the default Starknet permutation into the standard 2-input hash helper. * ```ts * import { poseidonHash, poseidonSmall } from '@scure/starknet'; * poseidonHash(1n, 2n, poseidonSmall); * ``` */ export declare const poseidonSmall: PoseidonFn; /** * Hashes two field elements with the default Starknet Poseidon permutation. * Applies the 2-input Starknet padding/domain-separation rule `fn([x, y, 2n])[0]`. * @param x - first field element * @param y - second field element * @param fn - Poseidon permutation to use * @returns Poseidon hash result. * @example * Hash two field elements with Starknet Poseidon. * ```ts * poseidonHash(1n, 2n); * ``` */ export declare function poseidonHash(x: bigint, y: bigint, fn?: PoseidonFn): bigint; /** * Hashes two byte arrays with Poseidon and returns the encoded bytes. * Interprets inputs as unsigned big-endian integers and returns a minimal big-endian byte string, not a fixed 32-byte field encoding. * @param x - first byte array * @param y - second byte array * @param fn - Poseidon permutation to use * @returns Poseidon hash encoded as big-endian bytes. * @example * Hash two byte arrays and return the Poseidon result as bytes. * ```ts * poseidonHashFunc(new Uint8Array([1]), new Uint8Array([2])); * ``` */ export declare function poseidonHashFunc(x: TArg<Uint8Array>, y: TArg<Uint8Array>, fn?: PoseidonFn): TRet<Uint8Array>; /** * Hashes a single field element with Poseidon. * Applies the 1-input Starknet padding/domain-separation rule `fn([x, 0n, 1n])[0]`. * @param x - field element to hash * @param fn - Poseidon permutation to use * @returns Poseidon hash result. * @example * Hash one field element with Poseidon. * ```ts * poseidonHashSingle(1n); * ``` */ export declare function poseidonHashSingle(x: bigint, fn?: PoseidonFn): bigint; /** * Hashes a list of field elements with Poseidon sponge padding. * Appends `1n`, zero-pads to a multiple of the permutation rate, then absorbs each rate-sized block into the zero state. * @param values - field elements to hash * @param fn - Poseidon permutation to use; custom functions are trusted to return a valid state vector * @returns Poseidon hash result. * @throws If internal Poseidon sponge sizing invariants fail unexpectedly. {@link Error} * @throws On wrong `values` argument types. {@link TypeError} * @example * Hash a list of field elements with Poseidon sponge padding. * ```ts * poseidonHashMany([1n, 2n, 3n]); * ``` */ export declare function poseidonHashMany(values: bigint[], fn?: PoseidonFn): bigint; //# sourceMappingURL=index.d.ts.map