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AC,IAAI,EAAE,SAAS,CAAC,EACjC,MAAM,CAAC,MAAM,CACd,CAAC;QAEF,MAAM,IAAI,GAAG,MAAM,IAAA,2BAAmB,EAAC;YACrC,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,oBAAoB;YACpB,sBAAsB,EAAE,qBAAqB,EAAE;SAChD,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,mBAAmB,CAAC;QAClC,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC,CAAC;AACJ,CAAC;AAzDD,0EAyDC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\n  PermissionSpecificationBuilder,\n  PermissionValidatorConstraint,\n  RestrictedMethodOptions,\n  ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n  GetBip32PublicKeyParams,\n  GetBip32PublicKeyResult,\n} from '@metamask/snaps-sdk';\nimport {\n  bip32entropy,\n  Bip32PathStruct,\n  CurveStruct,\n  SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport { boolean, object, optional, string } from '@metamask/superstruct';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\n\nimport type { KeyringControllerWithKeyringV2UnsafeAction } from '../types';\nimport type { MethodHooksObject } from '../utils';\nimport {\n  getMnemonic,\n  getMnemonicSeed,\n  getNodeFromMnemonic,\n  getNodeFromSeed,\n  getValueFromEntropySource,\n} from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\n  /**\n   * Waits for the extension to be unlocked.\n   *\n   * @returns A promise that resolves once the extension is unlocked.\n   */\n  getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n  /**\n   * Get the cryptographic functions to use for the client. This may return an\n   * empty object or `undefined` to fall back to the default cryptographic\n   * functions.\n   *\n   * @returns The cryptographic functions to use for the client.\n   */\n  getClientCryptography: () => CryptographicFunctions | undefined;\n};\n\nexport type GetBip32PublicKeyMessengerActions =\n  KeyringControllerWithKeyringV2UnsafeAction;\n\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n  methodHooks: GetBip32PublicKeyMethodHooks;\n  messenger: Messenger<string, GetBip32PublicKeyMessengerActions>;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n  permissionType: PermissionType.RestrictedMethod;\n  targetName: typeof targetName;\n  methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n  allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n  validator: PermissionValidatorConstraint;\n}>;\n\nexport const Bip32PublicKeyArgsStruct = bip32entropy(\n  object({\n    path: Bip32PathStruct,\n    curve: CurveStruct,\n    compressed: optional(boolean()),\n    source: optional(string()),\n  }),\n);\n\n/**\n * The specification builder for the `snap_getBip32PublicKey` permission.\n * `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular\n * BIP-32 node.\n *\n * @param options - The specification builder options.\n * @param options.messenger - The messenger.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getBip32PublicKey` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n  PermissionType.RestrictedMethod,\n  GetBip32PublicKeySpecificationBuilderOptions,\n  GetBip32PublicKeySpecification\n> = ({\n  methodHooks,\n  messenger,\n}: GetBip32PublicKeySpecificationBuilderOptions) => {\n  return {\n    permissionType: PermissionType.RestrictedMethod,\n    targetName,\n    allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n    methodImplementation: getBip32PublicKeyImplementation({\n      methodHooks,\n      messenger,\n    }),\n    validator: ({ caveats }) => {\n      if (\n        caveats?.length !== 1 ||\n        caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n      ) {\n        throw rpcErrors.invalidParams({\n          message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n        });\n      }\n    },\n    subjectTypes: [SubjectType.Snap],\n  };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32PublicKeyMethodHooks> = {\n  getUnlockPromise: true,\n  getClientCryptography: true,\n};\n\n/**\n * Gets the [BIP-32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)\n * public key for the derivation path specified by the `path` parameter. Note\n * that this returns the public key, not the extended public key (`xpub`), or\n * Ethereum address.\n *\n * @example\n * ```json name=\"Manifest\"\n * {\n *   \"initialPermissions\": {\n *     \"snap_getBip32PublicKey\": [\n *       {\n *         \"path\": [\"m\", \"44'\", \"3'\", \"0'\", \"0\", \"0\"],\n *         \"curve\": \"secp256k1\"\n *       }\n *     ]\n *   }\n * }\n * ```\n * ```ts name=\"Usage\"\n * // This example uses Dogecoin, which has a derivation path starting with\n * // \"m / 44' / 3'\".\n * const dogecoinPublicKey = await snap.request({\n *   method: 'snap_getBip32PublicKey',\n *   params: {\n *     // The path and curve must be specified in the initial permissions.\n *     path: ['m', \"44'\", \"3'\", \"0'\", \"0\", \"0\"],\n *     curve: 'secp256k1',\n *     compressed: false,\n *   },\n * })\n *\n * // '0x...'\n * console.log(dogecoinPublicKey)\n * ```\n */\nexport const getBip32PublicKeyBuilder = Object.freeze({\n  targetName,\n  specificationBuilder,\n  methodHooks,\n  actionNames: ['KeyringController:withKeyringV2Unsafe'],\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32PublicKey`.\n *\n * @param options - The options.\n * @param options.messenger - The messenger.\n * @param options.methodHooks - The RPC method hooks.\n * @param options.methodHooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @param options.methodHooks.getClientCryptography - A function to retrieve the cryptographic\n * functions to use for the client.\n * @returns The method implementation which returns a public key.\n * @throws If the params are invalid.\n */\nexport function getBip32PublicKeyImplementation({\n  methodHooks: { getUnlockPromise, getClientCryptography },\n  messenger,\n}: GetBip32PublicKeySpecificationBuilderOptions) {\n  return async function getBip32PublicKey(\n    args: RestrictedMethodOptions<GetBip32PublicKeyParams>,\n  ): Promise<GetBip32PublicKeyResult> {\n    await getUnlockPromise(true);\n\n    assertStruct(\n      args.params,\n      Bip32PublicKeyArgsStruct,\n      'Invalid BIP-32 public key params',\n      rpcErrors.invalidParams,\n    );\n\n    const { params } = args;\n\n    // Using the seed is much faster, but we can only do it for these specific curves.\n    if (params.curve === 'secp256k1' || params.curve === 'ed25519') {\n      const seed = await getValueFromEntropySource(\n        getMnemonicSeed.bind(null, messenger),\n        params.source,\n      );\n\n      const node = await getNodeFromSeed({\n        curve: params.curve,\n        path: params.path,\n        seed,\n        cryptographicFunctions: getClientCryptography(),\n      });\n\n      if (params.compressed) {\n        return node.compressedPublicKey;\n      }\n\n      return node.publicKey;\n    }\n\n    const secretRecoveryPhrase = await getValueFromEntropySource(\n      getMnemonic.bind(null, messenger),\n      params.source,\n    );\n\n    const node = await getNodeFromMnemonic({\n      curve: params.curve,\n      path: params.path,\n      secretRecoveryPhrase,\n      cryptographicFunctions: getClientCryptography(),\n    });\n\n    if (params.compressed) {\n      return node.compressedPublicKey;\n    }\n\n    return node.publicKey;\n  };\n}\n"]}