@metamask/snaps-rpc-methods 11.13.1 → 12.0.0

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 (50) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/restricted/getBip32Entropy.cjs +16 -3
  3. package/dist/restricted/getBip32Entropy.cjs.map +1 -1
  4. package/dist/restricted/getBip32Entropy.d.cts +11 -1
  5. package/dist/restricted/getBip32Entropy.d.cts.map +1 -1
  6. package/dist/restricted/getBip32Entropy.d.mts +11 -1
  7. package/dist/restricted/getBip32Entropy.d.mts.map +1 -1
  8. package/dist/restricted/getBip32Entropy.mjs +17 -4
  9. package/dist/restricted/getBip32Entropy.mjs.map +1 -1
  10. package/dist/restricted/getBip32PublicKey.cjs +19 -3
  11. package/dist/restricted/getBip32PublicKey.cjs.map +1 -1
  12. package/dist/restricted/getBip32PublicKey.d.cts +11 -1
  13. package/dist/restricted/getBip32PublicKey.d.cts.map +1 -1
  14. package/dist/restricted/getBip32PublicKey.d.mts +11 -1
  15. package/dist/restricted/getBip32PublicKey.d.mts.map +1 -1
  16. package/dist/restricted/getBip32PublicKey.mjs +20 -4
  17. package/dist/restricted/getBip32PublicKey.mjs.map +1 -1
  18. package/dist/restricted/getBip44Entropy.cjs +8 -5
  19. package/dist/restricted/getBip44Entropy.cjs.map +1 -1
  20. package/dist/restricted/getBip44Entropy.d.cts +6 -6
  21. package/dist/restricted/getBip44Entropy.d.cts.map +1 -1
  22. package/dist/restricted/getBip44Entropy.d.mts +6 -6
  23. package/dist/restricted/getBip44Entropy.d.mts.map +1 -1
  24. package/dist/restricted/getBip44Entropy.mjs +9 -6
  25. package/dist/restricted/getBip44Entropy.mjs.map +1 -1
  26. package/dist/restricted/getEntropy.cjs +7 -7
  27. package/dist/restricted/getEntropy.cjs.map +1 -1
  28. package/dist/restricted/getEntropy.d.cts +7 -7
  29. package/dist/restricted/getEntropy.d.cts.map +1 -1
  30. package/dist/restricted/getEntropy.d.mts +7 -7
  31. package/dist/restricted/getEntropy.d.mts.map +1 -1
  32. package/dist/restricted/getEntropy.mjs +8 -8
  33. package/dist/restricted/getEntropy.mjs.map +1 -1
  34. package/dist/restricted/manageState.cjs +4 -4
  35. package/dist/restricted/manageState.cjs.map +1 -1
  36. package/dist/restricted/manageState.d.cts +3 -3
  37. package/dist/restricted/manageState.d.cts.map +1 -1
  38. package/dist/restricted/manageState.d.mts +3 -3
  39. package/dist/restricted/manageState.d.mts.map +1 -1
  40. package/dist/restricted/manageState.mjs +5 -5
  41. package/dist/restricted/manageState.mjs.map +1 -1
  42. package/dist/utils.cjs +68 -23
  43. package/dist/utils.cjs.map +1 -1
  44. package/dist/utils.d.cts +40 -16
  45. package/dist/utils.d.cts.map +1 -1
  46. package/dist/utils.d.mts +40 -16
  47. package/dist/utils.d.mts.map +1 -1
  48. package/dist/utils.mjs +63 -19
  49. package/dist/utils.mjs.map +1 -1
  50. package/package.json +3 -3
package/dist/utils.mjs CHANGED
@@ -49,7 +49,7 @@ function getDerivationPathArray(hash) {
49
49
  return array;
50
50
  }
51
51
  /**
52
- * Derive entropy from the given mnemonic phrase and salt.
52
+ * Get the derivation path to use for entropy derivation.
53
53
  *
54
54
  * This is based on the reference implementation of
55
55
  * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).
@@ -57,27 +57,44 @@ function getDerivationPathArray(hash) {
57
57
  * @param options - The options for entropy derivation.
58
58
  * @param options.input - The input value to derive entropy from.
59
59
  * @param options.salt - An optional salt to use when deriving entropy.
60
- * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy
61
- * derivation.
62
60
  * @param options.magic - A hardened BIP-32 index, which is used to derive the
63
61
  * root key from the mnemonic phrase.
64
- * @param options.cryptographicFunctions - The cryptographic functions to use
65
- * for the derivation.
66
- * @returns The derived entropy.
62
+ * @returns The derivation path to be used for entropy key derivation.
67
63
  */
68
- export async function deriveEntropy({ input, salt = '', mnemonicPhrase, magic, cryptographicFunctions, }) {
64
+ function getEntropyDerivationPath({ input, salt, magic, }) {
69
65
  const inputBytes = stringToBytes(input);
70
66
  const saltBytes = stringToBytes(salt);
71
67
  // Get the derivation path from the snap ID.
72
68
  const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));
73
69
  const computedDerivationPath = getDerivationPathArray(hash);
70
+ return [`bip32:${magic}`, ...computedDerivationPath];
71
+ }
72
+ /**
73
+ * Derive entropy from the given mnemonic seed and salt.
74
+ *
75
+ * This is based on the reference implementation of
76
+ * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).
77
+ *
78
+ * @param options - The options for entropy derivation.
79
+ * @param options.input - The input value to derive entropy from.
80
+ * @param options.salt - An optional salt to use when deriving entropy.
81
+ * @param options.seed - The mnemonic seed to use for entropy
82
+ * derivation.
83
+ * @param options.magic - A hardened BIP-32 index, which is used to derive the
84
+ * root key from the mnemonic phrase.
85
+ * @param options.cryptographicFunctions - The cryptographic functions to use
86
+ * for the derivation.
87
+ * @returns The derived entropy.
88
+ */
89
+ export async function deriveEntropyFromSeed({ input, salt = '', seed, magic, cryptographicFunctions, }) {
90
+ const computedDerivationPath = getEntropyDerivationPath({
91
+ input,
92
+ salt,
93
+ magic,
94
+ });
74
95
  // Derive the private key using BIP-32.
75
- const { privateKey } = await SLIP10Node.fromDerivationPath({
76
- derivationPath: [
77
- mnemonicPhrase,
78
- `bip32:${magic}`,
79
- ...computedDerivationPath,
80
- ],
96
+ const { privateKey } = await SLIP10Node.fromSeed({
97
+ derivationPath: [seed, ...computedDerivationPath],
81
98
  curve: 'secp256k1',
82
99
  }, cryptographicFunctions);
83
100
  // This should never happen, but this keeps TypeScript happy.
@@ -127,7 +144,7 @@ export function getPathPrefix(curve) {
127
144
  * for the node.
128
145
  * @returns The `key-tree` SLIP-10 node.
129
146
  */
130
- export async function getNode({ curve, secretRecoveryPhrase, path, cryptographicFunctions, }) {
147
+ export async function getNodeFromMnemonic({ curve, secretRecoveryPhrase, path, cryptographicFunctions, }) {
131
148
  const prefix = getPathPrefix(curve);
132
149
  return await SLIP10Node.fromDerivationPath({
133
150
  curve,
@@ -137,6 +154,32 @@ export async function getNode({ curve, secretRecoveryPhrase, path, cryptographic
137
154
  ],
138
155
  }, cryptographicFunctions);
139
156
  }
157
+ /**
158
+ * Get a `key-tree`-compatible node.
159
+ *
160
+ * Note: This function assumes that all the parameters have been validated
161
+ * beforehand.
162
+ *
163
+ * @param options - The derivation options.
164
+ * @param options.curve - The curve to use for derivation.
165
+ * @param options.seed - The BIP-39 to use for
166
+ * derivation.
167
+ * @param options.path - The derivation path to use as array, starting with an
168
+ * "m" as the first item.
169
+ * @param options.cryptographicFunctions - The cryptographic functions to use
170
+ * for the node.
171
+ * @returns The `key-tree` SLIP-10 node.
172
+ */
173
+ export async function getNodeFromSeed({ curve, seed, path, cryptographicFunctions, }) {
174
+ const prefix = getPathPrefix(curve);
175
+ return await SLIP10Node.fromSeed({
176
+ curve,
177
+ derivationPath: [
178
+ seed,
179
+ ...path.slice(1).map((index) => `${prefix}:${index}`),
180
+ ],
181
+ }, cryptographicFunctions);
182
+ }
140
183
  /**
141
184
  * Validate the key of a state object.
142
185
  *
@@ -156,16 +199,17 @@ export const StateKeyStruct = refine(string(), 'state key', (value) => {
156
199
  return true;
157
200
  });
158
201
  /**
159
- * Get the secret recovery phrase of the user. This calls the `getMnemonic` hook
160
- * and handles any errors that occur, throwing formatted JSON-RPC errors.
202
+ * Get a value using the entropy source hooks: getMnemonic or getMnemonicSeed.
203
+ * This function calls the passed hook and handles any errors that occur,
204
+ * throwing formatted JSON-RPC errors.
161
205
  *
162
- * @param getMnemonic - The `getMnemonic` hook.
206
+ * @param hook - The hook.
163
207
  * @param source - The entropy source to use.
164
208
  * @returns The secret recovery phrase.
165
209
  */
166
- export async function getSecretRecoveryPhrase(getMnemonic, source) {
210
+ export async function getValueFromEntropySource(hook, source) {
167
211
  try {
168
- return await getMnemonic(source);
212
+ return await hook(source);
169
213
  }
170
214
  catch (error) {
171
215
  if (error instanceof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CAAC;QACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC3B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;QACL,CAAC;QAED,MAAM,SAAS,CAAC,QAAQ,CAAC;YACvB,OAAO,EAAE,4BAA4B;YACrC,IAAI,EAAE;gBACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;aACxB;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport type { Hex } from '@metamask/utils';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n cryptographicFunctions,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath(\n {\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype GetNodeArgs = {\n curve: SupportedCurve;\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n\n/**\n * Get the secret recovery phrase of the user. This calls the `getMnemonic` hook\n * and handles any errors that occur, throwing formatted JSON-RPC errors.\n *\n * @param getMnemonic - The `getMnemonic` hook.\n * @param source - The entropy source to use.\n * @returns The secret recovery phrase.\n */\nexport async function getSecretRecoveryPhrase(\n getMnemonic: (source?: string | undefined) => Promise<Uint8Array>,\n source?: string | undefined,\n): Promise<Uint8Array> {\n try {\n return await getMnemonic(source);\n } catch (error) {\n if (error instanceof Error) {\n throw rpcErrors.invalidParams({\n message: error.message,\n });\n }\n\n throw rpcErrors.internal({\n message: 'An unknown error occurred.',\n data: {\n error: error.toString(),\n },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,2BAA2B;AAChD,OAAO,EAAE,SAAS,EAAE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GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE;IACpE,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,4DAA4D,CAAC;IACtE,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,IAA0D,EAC1D,MAA2B;IAE3B,IAAI,CAAC;QACH,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC3B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;aACvB,CAAC,CAAC;QACL,CAAC;QAED,MAAM,SAAS,CAAC,QAAQ,CAAC;YACvB,OAAO,EAAE,4BAA4B;YACrC,IAAI,EAAE;gBACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;aACxB;SACF,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n SupportedCurve,\n CryptographicFunctions,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport { refine, string } from '@metamask/superstruct';\nimport {\n assertExhaustive,\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\nexport const FORBIDDEN_KEYS = ['constructor', '__proto__', 'prototype'];\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype BaseDeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n\n /**\n * The cryptographic functions to use for the derivation.\n */\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\ntype SeedDeriveEntropyOptions = BaseDeriveEntropyOptions & {\n /**\n * The mnemonic seed to use for entropy derivation.\n */\n seed: Uint8Array;\n};\n\n/**\n * Get the derivation path to use for entropy derivation.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @returns The derivation path to be used for entropy key derivation.\n */\nfunction getEntropyDerivationPath({\n input,\n salt,\n magic,\n}: Required<Omit<BaseDeriveEntropyOptions, 'cryptographicFunctions'>>):\n | BIP32Node[]\n | SLIP10PathNode[] {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n return [`bip32:${magic}`, ...computedDerivationPath];\n}\n\n/**\n * Derive entropy from the given mnemonic seed and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.seed - The mnemonic seed to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the derivation.\n * @returns The derived entropy.\n */\nexport async function deriveEntropyFromSeed({\n input,\n salt = '',\n seed,\n magic,\n cryptographicFunctions,\n}: SeedDeriveEntropyOptions) {\n const computedDerivationPath = getEntropyDerivationPath({\n input,\n salt,\n magic,\n });\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromSeed(\n {\n derivationPath: [seed, ...computedDerivationPath],\n curve: 'secp256k1',\n },\n cryptographicFunctions,\n );\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always uses the BIP-32 specification.\n * - The Ed25519 curve always uses the SLIP-10 specification.\n * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `bip32` or `slip10`.\n */\nexport function getPathPrefix(\n curve: SupportedCurve,\n): 'bip32' | 'slip10' | 'cip3' {\n switch (curve) {\n case 'secp256k1':\n return 'bip32';\n case 'ed25519':\n return 'slip10';\n case 'ed25519Bip32':\n return 'cip3';\n default:\n return assertExhaustive(curve);\n }\n}\n\ntype BaseGetNodeArgs = {\n curve: SupportedCurve;\n path: string[];\n cryptographicFunctions: CryptographicFunctions | undefined;\n};\n\ntype GetNodeArgsMnemonic = BaseGetNodeArgs & {\n secretRecoveryPhrase: Uint8Array;\n};\n\ntype GetNodeArgsSeed = BaseGetNodeArgs & {\n seed: Uint8Array;\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNodeFromMnemonic({\n curve,\n secretRecoveryPhrase,\n path,\n cryptographicFunctions,\n}: GetNodeArgsMnemonic) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromDerivationPath(\n {\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.seed - The BIP-39 to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n * @param options.cryptographicFunctions - The cryptographic functions to use\n * for the node.\n * @returns The `key-tree` SLIP-10 node.\n */\nexport async function getNodeFromSeed({\n curve,\n seed,\n path,\n cryptographicFunctions,\n}: GetNodeArgsSeed) {\n const prefix = getPathPrefix(curve);\n\n return await SLIP10Node.fromSeed(\n {\n curve,\n derivationPath: [\n seed,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n },\n cryptographicFunctions,\n );\n}\n\n/**\n * Validate the key of a state object.\n *\n * @param key - The key to validate.\n * @returns `true` if the key is valid, `false` otherwise.\n */\nexport function isValidStateKey(key: string | undefined) {\n if (key === undefined) {\n return true;\n }\n\n return key.split('.').every((part) => part.length > 0);\n}\n\nexport const StateKeyStruct = refine(string(), 'state key', (value) => {\n if (!isValidStateKey(value)) {\n return 'Invalid state key. Each part of the key must be non-empty.';\n }\n\n return true;\n});\n\n/**\n * Get a value using the entropy source hooks: getMnemonic or getMnemonicSeed.\n * This function calls the passed hook and handles any errors that occur,\n * throwing formatted JSON-RPC errors.\n *\n * @param hook - The hook.\n * @param source - The entropy source to use.\n * @returns The secret recovery phrase.\n */\nexport async function getValueFromEntropySource(\n hook: (source?: string | undefined) => Promise<Uint8Array>,\n source?: string | undefined,\n): Promise<Uint8Array> {\n try {\n return await hook(source);\n } catch (error) {\n if (error instanceof Error) {\n throw rpcErrors.invalidParams({\n message: error.message,\n });\n }\n\n throw rpcErrors.internal({\n message: 'An unknown error occurred.',\n data: {\n error: error.toString(),\n },\n });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-rpc-methods",
3
- "version": "11.13.1",
3
+ "version": "12.0.0",
4
4
  "description": "MetaMask Snaps JSON-RPC method implementations",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -55,14 +55,14 @@
55
55
  "test:watch": "jest --watch"
56
56
  },
57
57
  "dependencies": {
58
- "@metamask/key-tree": "^10.0.2",
58
+ "@metamask/key-tree": "^10.1.0",
59
59
  "@metamask/permission-controller": "^11.0.6",
60
60
  "@metamask/rpc-errors": "^7.0.2",
61
61
  "@metamask/snaps-sdk": "^6.19.0",
62
62
  "@metamask/snaps-utils": "^9.0.1",
63
63
  "@metamask/superstruct": "^3.1.0",
64
64
  "@metamask/utils": "^11.2.0",
65
- "@noble/hashes": "^1.3.1",
65
+ "@noble/hashes": "^1.7.1",
66
66
  "luxon": "^3.5.0"
67
67
  },
68
68
  "devDependencies": {