{"version":3,"sources":["../../src/core/crypto/ed25519.ts"],"sourcesContent":["// Copyright © Aptos Foundation\n// SPDX-License-Identifier: Apache-2.0\n\nimport { ed25519 } from \"@noble/curves/ed25519\";\nimport { Deserializer } from \"../../bcs/deserializer\";\nimport { Serializable, Serializer } from \"../../bcs/serializer\";\nimport { AuthenticationKey } from \"../authenticationKey\";\nimport { Hex } from \"../hex\";\nimport { HexInput, SigningScheme as AuthenticationKeyScheme } from \"../../types\";\nimport { CKDPriv, deriveKey, HARDENED_OFFSET, isValidHardenedPath, mnemonicToSeed, splitPath } from \"./hdKey\";\nimport { PrivateKey } from \"./privateKey\";\nimport { AccountPublicKey, VerifySignatureArgs } from \"./publicKey\";\nimport { Signature } from \"./signature\";\nimport { convertSigningMessage } from \"./utils\";\n\n/**\n * L is the value that greater than or equal to will produce a non-canonical signature, and must be rejected\n */\nconst L: number[] = [\n  0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00,\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\n];\n\n/**\n * Represents the public key of an Ed25519 key pair.\n *\n * Since [AIP-55](https://github.com/aptos-foundation/AIPs/pull/263) Aptos supports\n * `Legacy` and `Unified` authentication keys.\n *\n * Ed25519 scheme is represented in the SDK as `Legacy authentication key` and also\n * as `AnyPublicKey` that represents any `Unified authentication key`\n */\nexport class Ed25519PublicKey extends AccountPublicKey {\n  /**\n   * Length of an Ed25519 public key\n   */\n  static readonly LENGTH: number = 32;\n\n  /**\n   * Bytes of the public key\n   * @private\n   */\n  private readonly key: Hex;\n\n  /**\n   * Create a new PublicKey instance from a Uint8Array or String.\n   *\n   * @param hexInput A HexInput (string or Uint8Array)\n   */\n  constructor(hexInput: HexInput) {\n    super();\n\n    const hex = Hex.fromHexInput(hexInput);\n    if (hex.toUint8Array().length !== Ed25519PublicKey.LENGTH) {\n      throw new Error(`PublicKey length should be ${Ed25519PublicKey.LENGTH}`);\n    }\n    this.key = hex;\n  }\n\n  // region AccountPublicKey\n\n  /**\n   * Verifies a signed data with a public key\n   * @param args.message a signed message as a Hex string or Uint8Array\n   * @param args.signature the signature of the message\n   */\n  verifySignature(args: VerifySignatureArgs): boolean {\n    const { message, signature } = args;\n    if (!(signature instanceof Ed25519Signature)) {\n      return false;\n    }\n    const messageToVerify = convertSigningMessage(message);\n    const messageBytes = Hex.fromHexInput(messageToVerify).toUint8Array();\n    const signatureBytes = signature.toUint8Array();\n    const publicKeyBytes = this.key.toUint8Array();\n    // Also verify malleability\n    if (!signature.isCanonicalSignature()) {\n      return false;\n    }\n\n    return ed25519.verify(signatureBytes, messageBytes, publicKeyBytes);\n  }\n\n  authKey(): AuthenticationKey {\n    return AuthenticationKey.fromSchemeAndBytes({\n      scheme: AuthenticationKeyScheme.Ed25519,\n      input: this.toUint8Array(),\n    });\n  }\n\n  /**\n   * Get the public key in bytes (Uint8Array).\n   *\n   * @returns Uint8Array representation of the public key\n   */\n  toUint8Array(): Uint8Array {\n    return this.key.toUint8Array();\n  }\n\n  // endregion\n\n  // region Serializable\n\n  serialize(serializer: Serializer): void {\n    serializer.serializeBytes(this.key.toUint8Array());\n  }\n\n  static deserialize(deserializer: Deserializer): Ed25519PublicKey {\n    const bytes = deserializer.deserializeBytes();\n    return new Ed25519PublicKey(bytes);\n  }\n\n  // endregion\n\n  /**\n   * @deprecated use `instanceof Ed25519PublicKey` instead.\n   */\n  static isPublicKey(publicKey: AccountPublicKey): publicKey is Ed25519PublicKey {\n    return publicKey instanceof Ed25519PublicKey;\n  }\n}\n\n/**\n * Represents the private key of an Ed25519 key pair.\n */\nexport class Ed25519PrivateKey extends Serializable implements PrivateKey {\n  /**\n   * Length of an Ed25519 private key\n   */\n  static readonly LENGTH: number = 32;\n\n  /**\n   * The Ed25519 key seed to use for BIP-32 compatibility\n   * See more {@link https://github.com/satoshilabs/slips/blob/master/slip-0010.md}\n   */\n  static readonly SLIP_0010_SEED = \"ed25519 seed\";\n\n  /**\n   * The Ed25519 signing key\n   * @private\n   */\n  private readonly signingKey: Hex;\n\n  // region Constructors\n\n  /**\n   * Create a new PrivateKey instance from a Uint8Array or String.\n   *\n   * @param hexInput HexInput (string or Uint8Array)\n   */\n  constructor(hexInput: HexInput) {\n    super();\n\n    const privateKeyHex = Hex.fromHexInput(hexInput);\n    if (privateKeyHex.toUint8Array().length !== Ed25519PrivateKey.LENGTH) {\n      throw new Error(`PrivateKey length should be ${Ed25519PrivateKey.LENGTH}`);\n    }\n\n    // Create keyPair from Private key in Uint8Array format\n    this.signingKey = privateKeyHex;\n  }\n\n  /**\n   * Generate a new random private key.\n   *\n   * @returns Ed25519PrivateKey\n   */\n  static generate(): Ed25519PrivateKey {\n    const keyPair = ed25519.utils.randomPrivateKey();\n    return new Ed25519PrivateKey(keyPair);\n  }\n\n  /**\n   * Derives a private key from a mnemonic seed phrase.\n   *\n   * To derive multiple keys from the same phrase, change the path\n   *\n   * IMPORTANT: Ed25519 supports hardened derivation only (since it lacks a key homomorphism,\n   * so non-hardened derivation cannot work)\n   *\n   * @param path the BIP44 path\n   * @param mnemonics the mnemonic seed phrase\n   */\n  static fromDerivationPath(path: string, mnemonics: string): Ed25519PrivateKey {\n    if (!isValidHardenedPath(path)) {\n      throw new Error(`Invalid derivation path ${path}`);\n    }\n    return Ed25519PrivateKey.fromDerivationPathInner(path, mnemonicToSeed(mnemonics));\n  }\n\n  /**\n   * A private inner function so we can separate from the main fromDerivationPath() method\n   * to add tests to verify we create the keys correctly.\n   *\n   * @param path the BIP44 path\n   * @param seed the seed phrase created by the mnemonics\n   * @param offset the offset used for key derivation, defaults to 0x80000000\n   * @returns\n   */\n  private static fromDerivationPathInner(path: string, seed: Uint8Array, offset = HARDENED_OFFSET): Ed25519PrivateKey {\n    const { key, chainCode } = deriveKey(Ed25519PrivateKey.SLIP_0010_SEED, seed);\n\n    const segments = splitPath(path).map((el) => parseInt(el, 10));\n\n    // Derive the child key based on the path\n    const { key: privateKey } = segments.reduce((parentKeys, segment) => CKDPriv(parentKeys, segment + offset), {\n      key,\n      chainCode,\n    });\n    return new Ed25519PrivateKey(privateKey);\n  }\n\n  // endregion\n\n  // region PrivateKey\n\n  /**\n   * Derive the Ed25519PublicKey for this private key.\n   *\n   * @returns Ed25519PublicKey\n   */\n  publicKey(): Ed25519PublicKey {\n    const bytes = ed25519.getPublicKey(this.signingKey.toUint8Array());\n    return new Ed25519PublicKey(bytes);\n  }\n\n  /**\n   * Sign the given message with the private key.\n   *\n   * @param message a message as a string or Uint8Array\n   * @returns Signature\n   */\n  sign(message: HexInput): Ed25519Signature {\n    const messageToSign = convertSigningMessage(message);\n    const messageBytes = Hex.fromHexInput(messageToSign).toUint8Array();\n    const signatureBytes = ed25519.sign(messageBytes, this.signingKey.toUint8Array());\n    return new Ed25519Signature(signatureBytes);\n  }\n\n  /**\n   * Get the private key in bytes (Uint8Array).\n   *\n   * @returns Uint8Array representation of the private key\n   */\n  toUint8Array(): Uint8Array {\n    return this.signingKey.toUint8Array();\n  }\n\n  /**\n   * Get the private key as a hex string with the 0x prefix.\n   *\n   * @returns string representation of the private key\n   */\n  toString(): string {\n    return this.signingKey.toString();\n  }\n\n  // endregion\n\n  // region Serializable\n\n  serialize(serializer: Serializer): void {\n    serializer.serializeBytes(this.toUint8Array());\n  }\n\n  static deserialize(deserializer: Deserializer): Ed25519PrivateKey {\n    const bytes = deserializer.deserializeBytes();\n    return new Ed25519PrivateKey(bytes);\n  }\n\n  // endregion\n\n  /**\n   * @deprecated use `instanceof Ed25519PrivateKey` instead.\n   */\n  static isPrivateKey(privateKey: PrivateKey): privateKey is Ed25519PrivateKey {\n    return privateKey instanceof Ed25519PrivateKey;\n  }\n}\n\n/**\n * A signature of a message signed using an Ed25519 private key\n */\nexport class Ed25519Signature extends Signature {\n  /**\n   * Length of an Ed25519 signature\n   */\n  static readonly LENGTH = 64;\n\n  /**\n   * The signature bytes\n   * @private\n   */\n  private readonly data: Hex;\n\n  // region Constructors\n\n  constructor(hexInput: HexInput) {\n    super();\n    const data = Hex.fromHexInput(hexInput);\n    if (data.toUint8Array().length !== Ed25519Signature.LENGTH) {\n      throw new Error(`Signature length should be ${Ed25519Signature.LENGTH}`);\n    }\n    this.data = data;\n  }\n\n  // endregion\n\n  // region Signature\n\n  toUint8Array(): Uint8Array {\n    return this.data.toUint8Array();\n  }\n\n  // endregion\n\n  // region Serializable\n\n  serialize(serializer: Serializer): void {\n    serializer.serializeBytes(this.data.toUint8Array());\n  }\n\n  static deserialize(deserializer: Deserializer): Ed25519Signature {\n    const bytes = deserializer.deserializeBytes();\n    return new Ed25519Signature(bytes);\n  }\n\n  /**\n   * Checks if an ED25519 signature is non-canonical.\n   *\n   * Comes from Aptos Core\n   * https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-crypto/src/ed25519/ed25519_sigs.rs#L47-L85\n   */\n  isCanonicalSignature(): boolean {\n    const s = this.toUint8Array().slice(32);\n\n    for (let i = s.length - 1; i >= 0; i -= 1) {\n      if (s[i] < L[i]) {\n        return true;\n      }\n      if (s[i] > L[i]) {\n        return false;\n      }\n    }\n    // As this stage S == L which implies a non-canonical S.\n    return false;\n  }\n\n  // endregion\n}\n"],"mappings":"kUAGA,OAAS,WAAAA,MAAe,wBAexB,IAAMC,EAAc,CAClB,IAAM,IAAM,IAAM,GAAM,GAAM,GAAM,GAAM,GAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,GAAM,EAAM,EAAM,EAC5G,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAAM,EAC1E,EAWaC,EAAN,MAAMA,UAAyBC,CAAiB,CAiBrD,YAAYC,EAAoB,CAC9B,MAAM,EAEN,IAAMC,EAAMC,EAAI,aAAaF,CAAQ,EACrC,GAAIC,EAAI,aAAa,EAAE,SAAWH,EAAiB,OACjD,M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AMsB,EAANtB,EA8JMuB,EAAN,MAAMA,UAAyBC,CAAU,CAc9C,YAAY3C,EAAoB,CAC9B,MAAM,EACN,IAAM4C,EAAO1C,EAAI,aAAaF,CAAQ,EACtC,GAAI4C,EAAK,aAAa,EAAE,SAAWF,EAAiB,OAClD,MAAM,IAAI,MAAM,8BAA8BA,EAAiB,MAAM,EAAE,EAEzE,KAAK,KAAOE,CACd,CAMA,cAA2B,CACzB,OAAO,KAAK,KAAK,aAAa,CAChC,CAMA,UAAU9B,EAA8B,CACtCA,EAAW,eAAe,KAAK,KAAK,aAAa,CAAC,CACpD,CAEA,OAAO,YAAYC,EAA8C,CAC/D,IAAMC,EAAQD,EAAa,iBAAiB,EAC5C,OAAO,IAAI2B,EAAiB1B,CAAK,CACnC,CAQA,sBAAgC,CAC9B,IAAM6B,EAAI,KAAK,aAAa,EAAE,MAAM,EAAE,EAEtC,QAASC,EAAID,EAAE,OAAS,EAAGC,GAAK,EAAGA,GAAK,EAAG,CACzC,GAAID,EAAEC,CAAC,EAAIjD,EAAEiD,CAAC,EACZ,MAAO,GAET,GAAID,EAAEC,CAAC,EAAIjD,EAAEiD,CAAC,EACZ,MAAO,EAEX,CAEA,MAAO,EACT,CAGF,EAlEaJ,EAIK,OAAS,GAJpB,IAAMpC,EAANoC","names":["ed25519","L","_Ed25519PublicKey","AccountPublicKey","hexInput","hex","Hex","args","message","signature","Ed25519Signature","messageToVerify","convertSigningMessage","messageBytes","signatureBytes","publicKeyBytes","ed25519","AuthenticationKey","serializer","deserializer","bytes","publicKey","Ed25519PublicKey","_Ed25519PrivateKey","Serializable","privateKeyHex","keyPair","path","mnemonics","isValidHardenedPath","mnemonicToSeed","seed","offset","HARDENED_OFFSET","key","chainCode","deriveKey","segments","splitPath","el","privateKey","parentKeys","segment","CKDPriv","messageToSign","Ed25519PrivateKey","_Ed25519Signature","Signature","data","s","i"]}