@umbra-privacy/sdk 1.0.0 → 2.0.1

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 (181) hide show
  1. package/README.md +104 -25
  2. package/dist/{addresses-Brzgurv_.d.ts → addresses-B7HybtbJ.d.ts} +2 -1
  3. package/dist/{addresses-D_0YAS6B.d.cts → addresses-CTVY1oi7.d.cts} +2 -1
  4. package/dist/arcium-BXXlryfe.d.cts +20 -0
  5. package/dist/arcium-BXXlryfe.d.ts +20 -0
  6. package/dist/chunk-3LS5P32X.cjs +10892 -0
  7. package/dist/chunk-3LS5P32X.cjs.map +1 -0
  8. package/dist/chunk-4RHXVBNI.js +203 -0
  9. package/dist/chunk-4RHXVBNI.js.map +1 -0
  10. package/dist/chunk-4TZVXB5G.js +324 -0
  11. package/dist/chunk-4TZVXB5G.js.map +1 -0
  12. package/dist/chunk-5GUSMQ74.cjs +549 -0
  13. package/dist/chunk-5GUSMQ74.cjs.map +1 -0
  14. package/dist/chunk-5KPQXPQM.js +36 -0
  15. package/dist/chunk-5KPQXPQM.js.map +1 -0
  16. package/dist/chunk-AXD7LXYY.cjs +405 -0
  17. package/dist/chunk-AXD7LXYY.cjs.map +1 -0
  18. package/dist/{chunk-HOEXDXRC.cjs → chunk-BL6WXLPV.cjs} +32 -360
  19. package/dist/chunk-BL6WXLPV.cjs.map +1 -0
  20. package/dist/chunk-CFFLOE7D.cjs +598 -0
  21. package/dist/chunk-CFFLOE7D.cjs.map +1 -0
  22. package/dist/{chunk-BM7N6N7E.js → chunk-CFTW5WNG.js} +3 -325
  23. package/dist/chunk-CFTW5WNG.js.map +1 -0
  24. package/dist/chunk-DD2WCK4C.js +327 -0
  25. package/dist/chunk-DD2WCK4C.js.map +1 -0
  26. package/dist/chunk-DMPMQ74B.cjs +246 -0
  27. package/dist/chunk-DMPMQ74B.cjs.map +1 -0
  28. package/dist/{chunk-2Q75CQQJ.js → chunk-EEKF4553.js} +2 -2
  29. package/dist/chunk-EEKF4553.js.map +1 -0
  30. package/dist/chunk-ENVYYEM4.cjs +113 -0
  31. package/dist/chunk-ENVYYEM4.cjs.map +1 -0
  32. package/dist/chunk-FQX6ZYGJ.js +500 -0
  33. package/dist/chunk-FQX6ZYGJ.js.map +1 -0
  34. package/dist/chunk-FSK2ICMB.cjs +39 -0
  35. package/dist/chunk-FSK2ICMB.cjs.map +1 -0
  36. package/dist/chunk-FZYWLQAF.cjs +355 -0
  37. package/dist/chunk-FZYWLQAF.cjs.map +1 -0
  38. package/dist/chunk-GP26R377.js +436 -0
  39. package/dist/chunk-GP26R377.js.map +1 -0
  40. package/dist/chunk-HA5FLM63.js +393 -0
  41. package/dist/chunk-HA5FLM63.js.map +1 -0
  42. package/dist/chunk-INJ73LXQ.js +1107 -0
  43. package/dist/chunk-INJ73LXQ.js.map +1 -0
  44. package/dist/chunk-KMRROOME.js +10750 -0
  45. package/dist/chunk-KMRROOME.js.map +1 -0
  46. package/dist/{chunk-MDFSBU5W.cjs → chunk-LTCKPTZC.cjs} +2 -351
  47. package/dist/chunk-LTCKPTZC.cjs.map +1 -0
  48. package/dist/chunk-MKNCBUFA.js +564 -0
  49. package/dist/chunk-MKNCBUFA.js.map +1 -0
  50. package/dist/chunk-NKVMSABR.cjs +207 -0
  51. package/dist/chunk-NKVMSABR.cjs.map +1 -0
  52. package/dist/chunk-OFDWNWCL.js +70 -0
  53. package/dist/chunk-OFDWNWCL.js.map +1 -0
  54. package/dist/chunk-QJAUUYZU.cjs +331 -0
  55. package/dist/chunk-QJAUUYZU.cjs.map +1 -0
  56. package/dist/chunk-TLR7A64G.js +103 -0
  57. package/dist/chunk-TLR7A64G.js.map +1 -0
  58. package/dist/{chunk-MVKTV3FT.cjs → chunk-TQQZGNOI.cjs} +2 -2
  59. package/dist/chunk-TQQZGNOI.cjs.map +1 -0
  60. package/dist/chunk-UOFYS6M3.js +219 -0
  61. package/dist/chunk-UOFYS6M3.js.map +1 -0
  62. package/dist/chunk-UXMQI6B7.js +2406 -0
  63. package/dist/chunk-UXMQI6B7.js.map +1 -0
  64. package/dist/chunk-WN75ORDT.js +571 -0
  65. package/dist/chunk-WN75ORDT.js.map +1 -0
  66. package/dist/chunk-Y55PYKXH.cjs +595 -0
  67. package/dist/chunk-Y55PYKXH.cjs.map +1 -0
  68. package/dist/chunk-YEZBTYCP.cjs +77 -0
  69. package/dist/chunk-YEZBTYCP.cjs.map +1 -0
  70. package/dist/chunk-ZQOIYCGA.cjs +1126 -0
  71. package/dist/chunk-ZQOIYCGA.cjs.map +1 -0
  72. package/dist/chunk-ZY3TSHMJ.cjs +2665 -0
  73. package/dist/chunk-ZY3TSHMJ.cjs.map +1 -0
  74. package/dist/client-DkVBHMWb.d.cts +2613 -0
  75. package/dist/client-V4AF6Bz9.d.ts +2613 -0
  76. package/dist/common/pda/index.cjs +145 -0
  77. package/dist/common/pda/index.cjs.map +1 -0
  78. package/dist/common/pda/index.d.cts +1250 -0
  79. package/dist/common/pda/index.d.ts +1250 -0
  80. package/dist/common/pda/index.js +8 -0
  81. package/dist/common/pda/index.js.map +1 -0
  82. package/dist/constants/index.cjs +38 -164
  83. package/dist/constants/index.cjs.map +1 -1
  84. package/dist/constants/index.d.cts +8 -425
  85. package/dist/constants/index.d.ts +8 -425
  86. package/dist/constants/index.js +15 -124
  87. package/dist/constants/index.js.map +1 -1
  88. package/dist/crypto/index.cjs +583 -0
  89. package/dist/crypto/index.cjs.map +1 -0
  90. package/dist/crypto/index.d.cts +6731 -0
  91. package/dist/crypto/index.d.ts +6731 -0
  92. package/dist/crypto/index.js +14 -0
  93. package/dist/crypto/index.js.map +1 -0
  94. package/dist/{cryptography-BTGC72u-.d.ts → cryptography-BFSJcvi6.d.ts} +3 -2465
  95. package/dist/{cryptography-BTGC72u-.d.cts → cryptography-D6tPDh-Y.d.cts} +3 -2465
  96. package/dist/errors/index.cjs +64 -54
  97. package/dist/errors/index.d.cts +7 -797
  98. package/dist/errors/index.d.ts +7 -797
  99. package/dist/errors/index.js +3 -1
  100. package/dist/errors-B9EoPeWV.d.cts +593 -0
  101. package/dist/errors-B9EoPeWV.d.ts +593 -0
  102. package/dist/errors-DAIrstEL.d.cts +300 -0
  103. package/dist/errors-DPNMfyh0.d.ts +300 -0
  104. package/dist/index-BG0yjL7C.d.cts +6006 -0
  105. package/dist/index-ByynoyBO.d.ts +6006 -0
  106. package/dist/index.cjs +5133 -16116
  107. package/dist/index.cjs.map +1 -1
  108. package/dist/index.d.cts +1031 -7685
  109. package/dist/index.d.ts +1031 -7685
  110. package/dist/index.js +3228 -14905
  111. package/dist/index.js.map +1 -1
  112. package/dist/interfaces/index.d.cts +14 -6
  113. package/dist/interfaces/index.d.ts +14 -6
  114. package/dist/interfaces-43cReBcS.d.cts +3346 -0
  115. package/dist/interfaces-B8xKNl_6.d.ts +997 -0
  116. package/dist/interfaces-D2NO6kDD.d.cts +997 -0
  117. package/dist/interfaces-z_xYJlgV.d.ts +3346 -0
  118. package/dist/math/index.cjs +115 -0
  119. package/dist/math/index.cjs.map +1 -0
  120. package/dist/math/index.d.cts +1327 -0
  121. package/dist/math/index.d.ts +1327 -0
  122. package/dist/math/index.js +10 -0
  123. package/dist/math/index.js.map +1 -0
  124. package/dist/networks-RMd3abPE.d.ts +44 -0
  125. package/dist/networks-yAoO8peQ.d.cts +44 -0
  126. package/dist/relayer-NRRMSMNB.js +4 -0
  127. package/dist/relayer-NRRMSMNB.js.map +1 -0
  128. package/dist/relayer-RJHEIXJG.cjs +21 -0
  129. package/dist/relayer-RJHEIXJG.cjs.map +1 -0
  130. package/dist/solana/index.cjs +56 -0
  131. package/dist/solana/index.cjs.map +1 -0
  132. package/dist/solana/index.d.cts +105 -0
  133. package/dist/solana/index.d.ts +105 -0
  134. package/dist/solana/index.js +7 -0
  135. package/dist/solana/index.js.map +1 -0
  136. package/dist/{index-CLj_zWSD.d.ts → temporal-BbRaEPoO.d.ts} +1 -1
  137. package/dist/{index-CX6_pIRS.d.cts → temporal-oUj7iCaq.d.cts} +1 -1
  138. package/dist/transaction-forwarder-5mAMTjw6.d.ts +1155 -0
  139. package/dist/transaction-forwarder-C6gMUG7a.d.cts +1155 -0
  140. package/dist/types/index.cjs +232 -231
  141. package/dist/types/index.d.cts +15 -1485
  142. package/dist/types/index.d.ts +15 -1485
  143. package/dist/types/index.js +2 -1
  144. package/dist/types-BohhvPth.d.cts +87 -0
  145. package/dist/types-CW0oTT0j.d.ts +87 -0
  146. package/dist/types-C_V_CaKK.d.cts +2468 -0
  147. package/dist/types-C_V_CaKK.d.ts +2468 -0
  148. package/dist/types-Ca7frykr.d.ts +793 -0
  149. package/dist/types-CuKeoI19.d.cts +1296 -0
  150. package/dist/types-CxfTIpN9.d.ts +1052 -0
  151. package/dist/{types-n-sHFcgr.d.ts → types-D1jDUjfN.d.ts} +2 -2
  152. package/dist/types-DKEDUlH9.d.ts +1296 -0
  153. package/dist/types-EKuIfxTz.d.cts +1052 -0
  154. package/dist/{types-BBuELtY8.d.cts → types-IMGYmlv-.d.cts} +2 -2
  155. package/dist/types-PwNLi_2k.d.cts +793 -0
  156. package/dist/utils/index.cjs +823 -525
  157. package/dist/utils/index.d.cts +1711 -4021
  158. package/dist/utils/index.d.ts +1711 -4021
  159. package/dist/utils/index.js +9 -3
  160. package/dist/{versions-D9PqsEvj.d.cts → versions-BRlR36EA.d.cts} +1 -0
  161. package/dist/{versions-D9PqsEvj.d.ts → versions-BRlR36EA.d.ts} +1 -0
  162. package/package.json +79 -18
  163. package/dist/chunk-2Q75CQQJ.js.map +0 -1
  164. package/dist/chunk-BM7N6N7E.js.map +0 -1
  165. package/dist/chunk-GXKSUB2U.cjs +0 -4416
  166. package/dist/chunk-GXKSUB2U.cjs.map +0 -1
  167. package/dist/chunk-HOEXDXRC.cjs.map +0 -1
  168. package/dist/chunk-MDFSBU5W.cjs.map +0 -1
  169. package/dist/chunk-MQY7HDIA.js +0 -600
  170. package/dist/chunk-MQY7HDIA.js.map +0 -1
  171. package/dist/chunk-MVKTV3FT.cjs.map +0 -1
  172. package/dist/chunk-PG2J6V6Y.js +0 -4094
  173. package/dist/chunk-PG2J6V6Y.js.map +0 -1
  174. package/dist/chunk-VEGLTTYQ.cjs +0 -621
  175. package/dist/chunk-VEGLTTYQ.cjs.map +0 -1
  176. package/dist/chunk-WVHQ46DD.js +0 -758
  177. package/dist/chunk-WVHQ46DD.js.map +0 -1
  178. package/dist/index-B9pDY73x.d.ts +0 -12933
  179. package/dist/index-D33yo0qB.d.cts +0 -12933
  180. package/dist/networks-C-orpSFW.d.ts +0 -65
  181. package/dist/networks-FxYERGD1.d.cts +0 -65
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/math/bn254/types.ts","../src/math/bn254/field-arithmetic.ts","../src/math/bn254/field-element-sampler.ts","../src/math/curve25519/types.ts","../src/math/curve25519/field-arithmetic.ts"],"names":["N64","MASK64","P_LIMBS","ctSelect","bigintToLimbs","limbsToBigint","addModuleLimbs","subModuleLimbs"],"mappings":";;;;;;;AAiEO,IAAM,iBAAA,GACX;AAoHK,SAAS,uBAAA,CACd,KAAA,EACA,IAAA,GAAO,OAAA,EAC6B;AACpC,EAAA,MAAM,YAAA,GAAe,IAAA;AACrB,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,MAAM,IAAI,0BAAA,CAA2B,CAAA,EAAG,YAAY,CAAA,uBAAA,EAA0B,OAAO,KAAK,CAAA,CAAA,EAAI;AAAA,MAC5F,KAAA;AAAA,MACA,YAAA,EAAc;AAAA,KACf,CAAA;AAAA,EACH;AACA,EAAA,IAAI,QAAQ,EAAA,EAAI;AACd,IAAA,MAAM,IAAI,2BAA2B,CAAA,EAAG,YAAY,WAAW,MAAA,CAAO,KAAK,CAAC,CAAA,YAAA,CAAA,EAAgB;AAAA,MAC1F,KAAA;AAAA,MACA,YAAA,EAAc,mBAAA;AAAA,MACd,UAAA,EAAY;AAAA,KACb,CAAA;AAAA,EACH;AACA,EAAA,IAAI,SAAS,iBAAA,EAAmB;AAC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MAAM,WAAA,GAAc,oBAAoB,IAAI,CAAA;AAI5C,IAAA,MAAM,UAAA,GAAa,SAAA,CAAU,WAAA,EAAa,kBAAkB,CAAA;AAC5D,IAAA,MAAM,MAAA,GAAS,SAAA,CAAU,UAAA,EAAY,UAAU,CAAA;AAE/C,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AACF;AA1BgB,MAAA,CAAA,gCAAA,EAAA,kCAAA,CAAA;AA2ET,IAAM,gCACX,gCAAA","file":"chunk-WN75ORDT.js","sourcesContent":["/**\n * BN254 Field Element Types\n *\n * This module defines the foundational type primitives for working with elements\n * of the BN254 (alt_bn128) prime field. BN254 is a pairing-friendly elliptic curve\n * widely used in zero-knowledge proof systems, including Groth16, PLONK, and the\n * Circom/SnarkJS toolchain. Ethereum natively supports BN254 via the EIP-196 and\n * EIP-197 precompiles.\n *\n * @remarks\n * The BN254 scalar field F_r is the prime field whose order is the `r`-order of\n * points on the curve — i.e., the number of points on the curve's cyclic group.\n * All arithmetic in ZK circuits (Circom constraints, Groth16 witness values, etc.)\n * is performed modulo this prime. The prime has approximately 254 significant bits,\n * providing roughly 127 bits of symmetric security.\n *\n * The branded type system used here (`SubSubBrandedType`) enforces at compile time\n * that raw `bigint` values have been validated and reduced into the field. This\n * prevents accidentally passing an unreduced value (e.g., a product before modular\n * reduction) where a field element is expected.\n *\n * @see {@link https://eips.ethereum.org/EIPS/eip-196} EIP-196: Precompile for elliptic curve addition and scalar multiplication on alt_bn128\n * @see {@link https://eips.ethereum.org/EIPS/eip-197} EIP-197: Precompile for optimal ate pairing check on alt_bn128\n * @see {@link https://eprint.iacr.org/2010/354} Original BN curve construction paper\n *\n * @packageDocumentation\n * @module math/bn254/types\n */\n\nimport type { SubSubBrandedType } from \"../../common/branded\";\nimport type { U256 } from \"../../common/types\";\nimport { CryptographyAssertionError } from \"../../common/errors\";\n\n/**\n * The prime field modulus for the BN254 (alt_bn128) scalar field F_r.\n *\n * @remarks\n * This is the order `r` of the prime-order subgroup of points on the BN254\n * elliptic curve, also known as the BN254 scalar field prime. Every arithmetic\n * operation in Groth16 proofs, Circom circuits, and Poseidon hashes operates\n * modulo this value.\n *\n * Hexadecimal: `0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001`\n *\n * The decimal representation is:\n * `21888242871839275222246405745257275088548364400416034343698204186575808495617`\n *\n * Properties:\n * - Bit length: 254 bits\n * - Security level: approximately 127 bits\n * - Used by Ethereum precompiles EIP-196, EIP-197\n * - The lowest limb (64-bit) is `0x43e1f593f0000001`\n *\n * @example\n * ```typescript\n * import { BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Reduce an arbitrary bigint into the field\n * const arbitrary = 99999999999999999999999999999999999999999999999999999999999999999999999999999n;\n * const reduced = arbitrary % BN254_FIELD_PRIME;\n * // reduced is now in [0, BN254_FIELD_PRIME - 1]\n * ```\n *\n * @public\n */\nexport const BN254_FIELD_PRIME =\n 21_888_242_871_839_275_222_246_405_745_257_275_088_548_364_400_416_034_343_698_204_186_575_808_495_617n;\n\n/**\n * A type-safe branded representation of a BN254 (alt_bn128) scalar field element.\n *\n * BN254 is a pairing-friendly elliptic curve that is the foundation of Ethereum's\n * SNARK precompiles and the Circom/Groth16 ecosystem. The scalar field F_r consists\n * of all integers in the range `[0, BN254_FIELD_PRIME - 1]`.\n *\n * @remarks\n * ## Why a Branded Type?\n *\n * A `bigint` can represent any integer, including values outside the field range.\n * Using a branded type ensures that:\n * 1. Only values that have been explicitly validated (via `assertBn254FieldElement`)\n * can be assigned to this type.\n * 2. The TypeScript compiler will reject attempts to pass an arbitrary `bigint` where\n * a `Bn254FieldElement` is expected, catching a whole class of cryptographic bugs.\n * 3. Intermediate values produced by field operations (e.g., `a * b` before reduction)\n * cannot be accidentally used as field elements.\n *\n * ## BN254 Curve Properties\n *\n * - Curve equation: `y^2 = x^3 + 3` over F_p (where p is the base field prime)\n * - Scalar field order: `r = 21888242871839275222246405745257275088548364400416034343698204186575808495617`\n * - Embedding degree: 12 (makes it pairing-friendly)\n * - Security level: ~100 bits (conservative estimate accounting for NFS attacks on pairings)\n * - Supported operations: Groth16 verification, Poseidon hashing, EdDSA (Baby Jubjub)\n *\n * ## Usage\n *\n * Values of this type are inputs and outputs of all field arithmetic functions in\n * this module (`bn254Add`, `bn254Mul`, etc.) and the Poseidon hash functions.\n *\n * @see {@link assertBn254FieldElement} The assertion function that produces values of this type\n * @see {@link BN254_FIELD_PRIME} The modulus that defines the field\n * @see {@link https://eips.ethereum.org/EIPS/eip-196} EIP-196\n *\n * @example\n * ```typescript\n * import { type Bn254FieldElement, assertBn254FieldElement, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Validate and brand a known constant\n * const one = 1n;\n * assertBn254FieldElement(one, \"one\");\n * // one is now typed as Bn254FieldElement\n *\n * // The type prevents mixing with plain bigint in function signatures\n * function requiresFieldElement(x: Bn254FieldElement): void { /* ... *\\/ }\n * requiresFieldElement(42n); // TypeScript compile error\n * requiresFieldElement(one); // OK\n * ```\n *\n * @public\n */\nexport type Bn254FieldElement = SubSubBrandedType<U256, \"Bn254FieldElement\">;\n\n/**\n * Asserts that a `bigint` value is a valid element of the BN254 scalar field F_r,\n * narrowing its TypeScript type to `Bn254FieldElement` upon success.\n *\n * @remarks\n * A value is considered a valid BN254 field element if and only if:\n * 1. It is of type `bigint` (not `number`, `string`, etc.)\n * 2. It is non-negative: `value >= 0n`\n * 3. It is strictly less than the field prime: `value < BN254_FIELD_PRIME`\n *\n * This function uses the TypeScript assertion signature pattern (`asserts value is T`)\n * so that after a successful call, the narrowed type flows through to subsequent code\n * without any explicit cast.\n *\n * ## When to Use\n *\n * Call this function at the boundary between unvalidated external data and your\n * internal cryptographic logic. For example:\n * - When deserializing a field element from bytes\n * - When accepting user input that will be used as a circuit witness\n * - After computing a value from external sources before passing it to field operations\n *\n * Internally, all field arithmetic functions in this module automatically produce\n * validated `Bn254FieldElement` values, so you do not need to re-validate their outputs.\n *\n * @param value - The `bigint` to validate. Must satisfy `0 <= value < BN254_FIELD_PRIME`.\n * @param name - A descriptive name for the value, used in error messages to aid debugging.\n * Defaults to `\"value\"` if not provided.\n * @defaultValue `name` defaults to `\"value\"`\n *\n * @throws {CryptographyAssertionError} If `value` is not a `bigint`.\n * @throws {CryptographyAssertionError} If `value` is negative (i.e., `value < 0n`).\n * @throws {CryptographyAssertionError} If `value` is greater than or equal to the field prime.\n *\n * @example\n * ```typescript\n * import { assertBn254FieldElement, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Valid usage\n * const raw = 12345n;\n * assertBn254FieldElement(raw, \"raw\");\n * // After this line, `raw` is typed as Bn254FieldElement\n *\n * // The maximum valid field element is BN254_FIELD_PRIME - 1n\n * const maxElement = BN254_FIELD_PRIME - 1n;\n * assertBn254FieldElement(maxElement, \"maxElement\"); // OK\n *\n * // These all throw CryptographyAssertionError:\n * assertBn254FieldElement(-1n, \"negativeValue\"); // Throws: negativeValue is negative\n * assertBn254FieldElement(BN254_FIELD_PRIME, \"atPrime\"); // Throws: atPrime exceeds field prime\n * assertBn254FieldElement(42 as unknown as bigint, \"notBigint\"); // Throws: expected bigint\n * ```\n *\n * @see {@link Bn254FieldElement} The branded type this function produces\n * @see {@link BN254_FIELD_PRIME} The field modulus used for range checking\n * @see {@link CryptographyAssertionError} The error type thrown on validation failure\n *\n * @public\n */\nexport function assertBn254FieldElement(\n value: bigint,\n name = \"value\",\n): asserts value is Bn254FieldElement {\n const variableName = name;\n if (typeof value !== \"bigint\") {\n throw new CryptographyAssertionError(`${variableName}: Expected bigint, got ${typeof value}`, {\n value,\n expectedType: \"Bn254FieldElement\",\n });\n }\n if (value < 0n) {\n throw new CryptographyAssertionError(`${variableName}: Value ${String(value)} is negative`, {\n value,\n expectedType: \"Bn254FieldElement\",\n constraint: \"value >= 0\",\n });\n }\n if (value >= BN254_FIELD_PRIME) {\n throw new CryptographyAssertionError(`${variableName}: Value exceeds BN254 field prime`, {\n value,\n expectedType: \"Bn254FieldElement\",\n constraint: `value < ${String(BN254_FIELD_PRIME)}`,\n });\n }\n}\n","/**\n * BN254 Field Arithmetic — Constant-Time Montgomery Implementation\n *\n * This module provides the core constant-time modular arithmetic operations for\n * the BN254 (alt_bn128) scalar prime field F_r. It is the cryptographic foundation\n * of the BN254 math layer and implements all five field operations:\n *\n * - Addition: `(a + b) mod p`\n * - Subtraction: `(a - b) mod p`\n * - Multiplication: `(a * b) mod p` (via Montgomery multiplication)\n * - Negation: `-a mod p`\n * - Multiplicative inverse: `a^(-1) mod p` (via Fermat + Montgomery exponentiation)\n *\n * Additionally, it exports getter functions that return stable cached instances of\n * each operation, and a utility for computing the modular inverse of a Base85 limb sum.\n *\n * @remarks\n * ## BN254 Scalar Field\n *\n * The BN254 elliptic curve (also called alt_bn128 in the Ethereum context) has a\n * cyclic group of prime order:\n * ```\n * p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n * = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001\n * ```\n * This prime has approximately 254 significant bits. Every arithmetic operation in\n * Circom circuits, Groth16 proofs, and Poseidon hashes works modulo `p`.\n *\n * ## Constant-Time Design\n *\n * These implementations target *constant-operation-count* behavior, which is the\n * achievable standard in JavaScript:\n * - No data-dependent branching on secret values\n * - All 4 limbs are always processed uniformly\n * - Conditional selection uses bitwise masking (`ctSelect`)\n * - Montgomery multiplication processes all iterations unconditionally\n *\n * True hardware-level constant time (immune to microarchitectural attacks such as\n * cache-timing, branch prediction, and power analysis) is not achievable in JavaScript\n * due to the JIT compiler and BigInt internals. However, this implementation avoids\n * the most obvious timing leaks.\n *\n * ## 4-Limb (64-bit) Representation\n *\n * Values are stored as `[limb0, limb1, limb2, limb3]` in little-endian order:\n * - `limb0`: bits 0–63 (least significant)\n * - `limb1`: bits 64–127\n * - `limb2`: bits 128–191\n * - `limb3`: bits 192–255 (most significant)\n *\n * The reconstruction formula is:\n * ```\n * value = limb0 + limb1 * 2^64 + limb2 * 2^128 + limb3 * 2^192\n * ```\n *\n * ## Montgomery Multiplication\n *\n * Multiplication uses the CIOS (Coarsely Integrated Operand Scanning) variant of\n * Montgomery multiplication. Working in \"Montgomery domain\" (where each value `a`\n * is stored as `aR mod p` for `R = 2^256`) allows the inner multiplication-and-reduction\n * loop to avoid a full division by `p`. Instead, it uses a precomputed constant\n * `p' = -p^(-1) mod 2^64` to make each output limb divisible by `2^64`, enabling\n * a right-shift instead of a division.\n *\n * @see {@link ./types} BN254 field element types and validation\n * @see {@link ./operations} Higher-level field operations (non-constant-time)\n * @see {@link ./interfaces} Function type interfaces implemented here\n * @see {@link ./field-element-sampler} Sampler that depends on this module\n *\n * @packageDocumentation\n * @module math/bn254/field-arithmetic\n */\n\nimport type {\n Bn254FieldElementLimb,\n ModuloAddFunction as ModuleAddFunction,\n ModuloInvFunction as ModuleInvFunction,\n ModuloMulFunction as ModuleMulFunction,\n ModuloNegFunction as ModuleNegFunction,\n ModuloSubFunction as ModuleSubFunction,\n} from \"./interfaces\";\nimport { type Bn254FieldElement, BN254_FIELD_PRIME, assertBn254FieldElement } from \"./types\";\nimport type { Base85LimbTuple } from \"../../crypto/poseidon/types\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * Number of bits per 64-bit limb, as a `bigint` for use in shift operations.\n *\n * @remarks\n * All bit-shift operations in this module use `bigint` arithmetic, so `N64 = 64n`\n * avoids repeated `BigInt(64)` conversions. This is used in `bigintToLimbs`,\n * `limbsToBigint`, `addModuleLimbs`, `subModuleLimbs`, and `montgomeryMulLimbs`.\n *\n * @internal\n */\nconst N64 = 64n;\n\n/**\n * Bit mask for extracting the lower 64 bits of a `bigint`.\n *\n * @remarks\n * Equal to `2^64 - 1 = 0xFFFFFFFFFFFFFFFF`. Applied via bitwise AND (`& MASK64`)\n * after additions and multiplications that may produce values wider than 64 bits,\n * to isolate the current limb value and separate it from any carry.\n *\n * @internal\n */\nconst MASK64 = 0xff_ff_ff_ff_ff_ff_ff_ffn;\n\n/**\n * The BN254 scalar field prime `p` in 4-limb little-endian representation.\n *\n * @remarks\n * The prime is:\n * `p = 21888242871839275222246405745257275088548364400416034343698204186575808495617`\n * In hexadecimal: `0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001`\n *\n * Decomposed into four 64-bit little-endian limbs:\n * - `P_LIMBS[0] = 0x43e1f593f0000001` — bits 0–63\n * - `P_LIMBS[1] = 0x2833e84879b97091` — bits 64–127\n * - `P_LIMBS[2] = 0xb85045b68181585d` — bits 128–191\n * - `P_LIMBS[3] = 0x30644e72e131a029` — bits 192–255\n *\n * This constant is referenced in every limb-level operation: addition (trial subtraction),\n * subtraction (correction add), Montgomery reduction (multiplication by `m * p`), and\n * negation (`p - a`).\n *\n * @internal\n */\nconst P_LIMBS: Bn254FieldElementLimb = [\n 0x43_e1_f5_93_f0_00_00_01n, // limb 0 (bits 0-63)\n 0x28_33_e8_48_79_b9_70_91n, // limb 1 (bits 64-127)\n 0xb8_50_45_b6_81_81_58_5dn, // limb 2 (bits 128-191)\n 0x30_64_4e_72_e1_31_a0_29n, // limb 3 (bits 192-255)\n];\n\n/**\n * The Montgomery constant `p' = -p^(-1) mod 2^64`.\n *\n * @remarks\n * This constant is the core of the Montgomery reduction step. After accumulating\n * partial products in the CIOS loop, the reduction computes:\n * ```\n * m = (t[i] * P_PRIME) mod 2^64\n * ```\n * and then adds `m * p` to the accumulator, making `t[i]` divisible by `2^64`.\n * The key property is:\n * ```\n * p0 * P_PRIME ≡ -1 (mod 2^64)\n * ```\n * where `p0 = P_LIMBS[0] = 0x43e1f593f0000001` is the least significant limb of `p`.\n *\n * Value: `0xc2e1f593effffffF`\n *\n * This was derived using the Extended Euclidean Algorithm:\n * ```\n * P_PRIME = modular_inverse(p0, 2^64) negated mod 2^64\n * ```\n *\n * @privateRemarks\n * The formula is sometimes written as `mu = -p^(-1) mod b` where `b = 2^64`.\n * Since `p * P_PRIME ≡ -1 (mod 2^64)`, we have `p * (-P_PRIME) ≡ 1 (mod 2^64)`,\n * confirming that `P_PRIME` is indeed the negated modular inverse of `p` (mod 2^64).\n *\n * @internal\n */\nconst P_PRIME = 0xc2_e1_f5_93_ef_ff_ff_ffn;\n\n/**\n * The value `R^2 mod p` for converting standard-form values to Montgomery form.\n *\n * @remarks\n * In Montgomery arithmetic with modulus `p` and Montgomery constant `R = 2^256`:\n * - The Montgomery form of `a` is `aR mod p`.\n * - Conversion from standard form uses: `toMontgomery(a) = MontMul(a, R^2 mod p)`\n *\n * Because `MontMul(a, R^2) = a * R^2 * R^(-1) mod p = aR mod p`, multiplying by\n * the precomputed constant `R^2 mod p` (via a single Montgomery multiplication)\n * achieves the conversion without a full multi-precision division.\n *\n * `R^2 mod p = (2^256)^2 mod p = 2^512 mod p`\n *\n * Stored in 4-limb little-endian form:\n * - `R2_LIMBS[0] = 0x1bb8e645ae216da7`\n * - `R2_LIMBS[1] = 0x53fe3ab1e35c59e3`\n * - `R2_LIMBS[2] = 0x8c49833d53bb8085`\n * - `R2_LIMBS[3] = 0x0216d0b17f4e44a5`\n *\n * @internal\n */\nconst R2_LIMBS: Bn254FieldElementLimb = [\n 0x1b_b8_e6_45_ae_21_6d_a7n,\n 0x53_fe_3a_b1_e3_5c_59_e3n,\n 0x8c_49_83_3d_53_bb_80_85n,\n 0x02_16_d0_b1_7f_4e_44_a5n,\n];\n\n/**\n * The value `1` in Montgomery domain, i.e., `R mod p = 2^256 mod p`.\n *\n * @remarks\n * The multiplicative identity element in the Montgomery domain is not `1` but\n * `R mod p`. When Montgomery exponentiation initializes the result accumulator to\n * \"1\", it must use this Montgomery-form representation.\n *\n * `ONE_MONT = R mod p = 2^256 mod p`\n *\n * Stored in 4-limb little-endian form:\n * - `ONE_MONT[0] = 0xac96341c4ffffffb`\n * - `ONE_MONT[1] = 0x36fc76959f60cd29`\n * - `ONE_MONT[2] = 0x666ea36f7879462e`\n * - `ONE_MONT[3] = 0x0e0a77c19a07df2f`\n *\n * @internal\n */\nconst ONE_MONT: Bn254FieldElementLimb = [\n 0xac_96_34_1c_4f_ff_ff_fbn,\n 0x36_fc_76_95_9f_60_cd_29n,\n 0x66_6e_a3_6f_78_79_46_2en,\n 0x0e_0a_77_c1_9a_07_df_2fn,\n];\n\n// =============================================================================\n// Internal Helper Functions\n// =============================================================================\n\n/**\n * Performs a constant-time conditional select between two `bigint` values.\n *\n * Returns `x` if `bit === 1n`, or `y` if `bit === 0n`, using bitwise masking\n * to avoid any data-dependent branch.\n *\n * @remarks\n * ## Implementation\n *\n * JavaScript's `bigint` supports arbitrary-precision two's complement. For `bit`:\n * - `bit === 1n` → `mask = -1n` (infinite sequence of set bits) → `(x & mask) | (y & ~mask) = x | 0 = x`\n * - `bit === 0n` → `mask = 0n` (no bits set) → `(x & mask) | (y & ~mask) = 0 | y = y`\n *\n * This idiom is used throughout the limb-arithmetic functions wherever a conditional\n * selection must occur without branching.\n *\n * @param bit - Selection bit. Must be exactly `0n` or `1n`. Passing any other value\n * yields undefined results.\n * @param x - The value returned when `bit === 1n`.\n * @param y - The value returned when `bit === 0n`.\n * @returns `x` if `bit === 1n`; `y` otherwise.\n *\n * @example\n * ```typescript\n * // Internal usage — always branch-free:\n * const borrow = 1n; // pretend subtraction underflowed\n * const corrected = ctSelect(borrow, original + P, original);\n * // equivalent to: borrow ? original + P : original\n * ```\n *\n * @internal\n */\nfunction ctSelect(bit: bigint, x: bigint, y: bigint): bigint {\n // If bit is 1, mask is all 1s (-1n in two's complement)\n // If bit is 0, mask is 0n\n const mask = -bit;\n return (x & mask) | (y & ~mask);\n}\n\n/**\n * Converts a `bigint` to a 4-element little-endian 64-bit limb tuple.\n *\n * @remarks\n * Each element of the output holds exactly 64 bits of the input:\n * ```\n * output[k] = (value >> (64 * k)) & MASK64\n * ```\n * Bits above position 255 are silently truncated. The input should be\n * in `[0, 2^256 - 1]` for meaningful results.\n *\n * @param value - The `bigint` to decompose. Should satisfy `0 <= value < 2^256`.\n * @returns A 4-tuple `[limb0, limb1, limb2, limb3]` in little-endian order,\n * each limb in `[0, 2^64 - 1]`.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * bigintToLimbs(1n); // [1n, 0n, 0n, 0n]\n * bigintToLimbs(2n ** 64n); // [0n, 1n, 0n, 0n]\n * bigintToLimbs(2n ** 128n); // [0n, 0n, 1n, 0n]\n * ```\n *\n * @internal\n */\nfunction bigintToLimbs(value: bigint): Bn254FieldElementLimb {\n return [\n value & MASK64,\n (value >> N64) & MASK64,\n (value >> (N64 * 2n)) & MASK64,\n (value >> (N64 * 3n)) & MASK64,\n ];\n}\n\n/**\n * Reconstructs a `bigint` from a 4-element little-endian 64-bit limb tuple.\n *\n * @remarks\n * Applies the positional formula:\n * ```\n * value = limbs[0] + limbs[1] * 2^64 + limbs[2] * 2^128 + limbs[3] * 2^192\n * ```\n * The result is in `[0, 2^256 - 1]` when all limbs are in `[0, 2^64 - 1]`.\n * This is the exact inverse of `bigintToLimbs`.\n *\n * @param limbs - A 4-tuple `[limb0, limb1, limb2, limb3]` in little-endian order.\n * @returns The reconstructed `bigint` value.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * limbsToBigint([1n, 0n, 0n, 0n]); // 1n\n * limbsToBigint([0n, 1n, 0n, 0n]); // 2^64\n * limbsToBigint([0n, 0n, 0n, 1n]); // 2^192\n * ```\n *\n * @internal\n */\nfunction limbsToBigint(limbs: Bn254FieldElementLimb): bigint {\n return limbs[0] + (limbs[1] << N64) + (limbs[2] << (N64 * 2n)) + (limbs[3] << (N64 * 3n));\n}\n\n/**\n * Computes `(a + b) mod p` on 4-limb representations using constant-time arithmetic.\n *\n * @remarks\n * ## Algorithm\n *\n * 1. **Raw addition** with carry propagation across all 4 limbs. The final carry\n * (`tCarry`) is `1n` if the sum `a + b` exceeded `2^256 - 1`, `0n` otherwise.\n * 2. **Trial subtraction** of `p` with borrow propagation across all 4 limbs.\n * The final borrow (`borrow`) is `1n` if `(a + b) < p` (no reduction needed),\n * `0n` if `(a + b) >= p` (reduction needed).\n * 3. **Constant-time selection**:\n * - If `tCarry === 1n` (sum overflowed 256 bits), the sum is definitely `>= p`,\n * so use the subtracted result `d`.\n * - Otherwise, if `borrow === 0n` (no underflow in trial subtraction), the sum\n * is `>= p`, so use `d`.\n * - If `borrow === 1n` and `tCarry === 0n`, the sum is `< p`, so keep `t`.\n * The combined condition `useD = tCarry | (1n - borrow)` covers both cases.\n *\n * @param a - First operand in 4-limb form, representing a value in `[0, p-1]`.\n * @param b - Second operand in 4-limb form, representing a value in `[0, p-1]`.\n * @returns The sum `(a + b) mod p` in 4-limb form.\n *\n * @example\n * ```typescript\n * // Internal usage (all via bigintToLimbs/limbsToBigint wrapper in bn254ModuloAdd):\n * const aLimbs = bigintToLimbs(BN254_FIELD_PRIME - 1n);\n * const bLimbs = bigintToLimbs(2n);\n * const result = addModuleLimbs(aLimbs, bLimbs);\n * limbsToBigint(result); // 1n (wrapped around)\n * ```\n *\n * @internal\n */\nfunction addModuleLimbs(a: Bn254FieldElementLimb, b: Bn254FieldElementLimb): Bn254FieldElementLimb {\n // 1. Raw Addition: t = a + b\n const t: bigint[] = [0n, 0n, 0n, 0n];\n let carry = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sum = a[index] + b[index] + carry;\n t[index] = sum & MASK64;\n carry = sum >> N64;\n }\n const tCarry = carry; // 1n if a+b overflowed 256 bits\n\n // 2. Trial Subtraction: d = t - p\n const d: bigint[] = [0n, 0n, 0n, 0n];\n let borrow = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sub = t[index] - P_LIMBS[index] - borrow;\n d[index] = sub & MASK64;\n borrow = -(sub >> N64); // 1n if borrowed, 0n otherwise\n }\n\n // 3. Selection\n // Use d if: addition overflowed (tCarry == 1) OR subtraction didn't underflow (borrow == 0)\n const useD = tCarry | (1n - borrow);\n\n return [\n ctSelect(useD, d[0], t[0]),\n ctSelect(useD, d[1], t[1]),\n ctSelect(useD, d[2], t[2]),\n ctSelect(useD, d[3], t[3]),\n ];\n}\n\n/**\n * Computes `(a - b) mod p` on 4-limb representations using constant-time arithmetic.\n *\n * @remarks\n * ## Algorithm\n *\n * 1. **Raw subtraction** `diff = a - b` with borrow propagation across all 4 limbs.\n * The final borrow is `1n` if `a < b` (underflow occurred), `0n` if `a >= b`.\n * 2. **Conditional correction**: if `borrow === 1n`, add `p` back to the result\n * to wrap around correctly. The addition of `p` is applied via a bitmask derived\n * from `borrow`: `mask = -borrow` (all 1s if borrow, all 0s otherwise). Each\n * limb of `p` is AND-masked before being added, so the addition only occurs\n * when there was an underflow.\n *\n * @param a - Minuend in 4-limb form, representing a value in `[0, p-1]`.\n * @param b - Subtrahend in 4-limb form, representing a value in `[0, p-1]`.\n * @returns The difference `(a - b) mod p` in 4-limb form.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const aLimbs = bigintToLimbs(5n);\n * const bLimbs = bigintToLimbs(10n);\n * const result = subModuleLimbs(aLimbs, bLimbs);\n * limbsToBigint(result); // BN254_FIELD_PRIME - 5n\n * ```\n *\n * @internal\n */\nfunction subModuleLimbs(a: Bn254FieldElementLimb, b: Bn254FieldElementLimb): Bn254FieldElementLimb {\n // 1. Calculate diff = a - b\n const out: bigint[] = [0n, 0n, 0n, 0n];\n let borrow = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sub = a[index] - b[index] - borrow;\n out[index] = sub & MASK64;\n borrow = -(sub >> N64); // 1n if underflow happened\n }\n\n // 2. If we borrowed, add P back using masking\n const mask = -borrow;\n let carry = 0n;\n\n for (let index = 0; index < 4; index++) {\n const addValue = P_LIMBS[index] & mask;\n\n const sum = out[index] + addValue + carry;\n out[index] = sum & MASK64;\n carry = sum >> N64;\n }\n\n return [out[0], out[1], out[2], out[3]];\n}\n\n/**\n * Computes `(a * b * R^(-1)) mod p` using the CIOS (Coarsely Integrated Operand\n * Scanning) Montgomery multiplication algorithm on 4-limb representations.\n *\n * @remarks\n * ## Montgomery Multiplication Background\n *\n * Montgomery multiplication computes `MontMul(a, b) = a * b * R^(-1) mod p`,\n * where `R = 2^256`. When `a` and `b` are both in Montgomery form (`a = x * R mod p`\n * and `b = y * R mod p`), the result is:\n * ```\n * MontMul(xR, yR) = xR * yR * R^(-1) mod p = xyR mod p\n * ```\n * which is also in Montgomery form. This makes Montgomery multiplication closed\n * under composition: chains of multiplications stay in the Montgomery domain.\n *\n * ## CIOS Algorithm\n *\n * The CIOS variant integrates the multiplication and reduction into a single loop:\n * for each limb `i` of `a`:\n * 1. Accumulate partial products: `t += a[i] * b` (inner 4-limb loop with carry)\n * 2. Compute the Montgomery reduction factor: `m = (t[i] * P_PRIME) mod 2^64`\n * 3. Eliminate the lowest accumulated limb: add `m * p` to `t` (inner 4-limb loop),\n * which makes `t[i]` divisible by `2^64` and can be discarded\n *\n * After 4 outer iterations, the 512-bit accumulator `t` holds `a * b * R^(-1) mod p`\n * in its upper 256 bits (`t[4]...t[7]`). A final conditional subtraction reduces\n * this to `[0, p-1]`.\n *\n * ## Why Montgomery?\n *\n * The naive `(a * b) % p` requires a multi-precision division by `p`, which has\n * variable execution time. Montgomery reduction replaces the division with a\n * multiply-and-shift, enabling constant-operation-count multiplication.\n *\n * @param a - First factor in Montgomery form (4-limb little-endian, value `xR mod p`).\n * @param b - Second factor in Montgomery form (4-limb little-endian, value `yR mod p`).\n * @returns The Montgomery product `(a * b * R^(-1)) mod p` in 4-limb form.\n *\n * @example\n * ```typescript\n * // Internal usage (not called directly; use bn254ModuloMul instead):\n * const aM = toMontgomery(bigintToLimbs(7n));\n * const bM = toMontgomery(bigintToLimbs(8n));\n * const productM = montgomeryMulLimbs(aM, bM);\n * const product = limbsToBigint(fromMontgomery(productM)); // 56n\n * ```\n *\n * @internal\n */\nfunction montgomeryMulLimbs(\n a: Bn254FieldElementLimb,\n b: Bn254FieldElementLimb,\n): Bn254FieldElementLimb {\n // Accumulator array (9 limbs: 8 for 512-bit intermediate + 1 for carry overflow)\n const t: bigint[] = [0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n, 0n];\n\n for (let index = 0; index < 4; index++) {\n // 1. Inner loop: t = t + a[i] * b\n let carry = 0n;\n for (let innerIndex = 0; innerIndex < 4; innerIndex++) {\n const sum = t[index + innerIndex] + a[index] * b[innerIndex] + carry;\n t[index + innerIndex] = sum & MASK64;\n carry = sum >> N64;\n }\n t[index + 4] = t[index + 4] + carry;\n\n // 2. Montgomery reduction step\n // m = (t[i] * p_prime) mod 2^64\n const m = (t[index] * P_PRIME) & MASK64;\n\n // Add m * p to t (this makes t[i] divisible by 2^64)\n let carryRed = 0n;\n for (let innerIndex = 0; innerIndex < 4; innerIndex++) {\n const sum = t[index + innerIndex] + m * P_LIMBS[innerIndex] + carryRed;\n t[index + innerIndex] = sum & MASK64;\n carryRed = sum >> N64;\n }\n\n // Propagate carry\n const sumUp = t[index + 4] + carryRed;\n t[index + 4] = sumUp & MASK64;\n t[index + 5] = t[index + 5] + (sumUp >> N64);\n }\n\n // Result is in t[4]...t[7]\n const result: bigint[] = [t[4], t[5], t[6], t[7]];\n\n // Conditional subtraction if result >= p\n const subResult: bigint[] = [0n, 0n, 0n, 0n];\n let borrow = 0n;\n for (let k = 0; k < 4; k++) {\n const s = result[k] - P_LIMBS[k] - borrow;\n subResult[k] = s & MASK64;\n borrow = -(s >> N64);\n }\n\n // If borrow is 0, result >= p, so use subResult\n // If borrow is 1, result < p, so keep result\n const useSub = 1n - borrow;\n\n return [\n ctSelect(useSub, subResult[0], result[0]),\n ctSelect(useSub, subResult[1], result[1]),\n ctSelect(useSub, subResult[2], result[2]),\n ctSelect(useSub, subResult[3], result[3]),\n ];\n}\n\n/**\n * Converts a field element from standard form to Montgomery form: `a -> aR mod p`.\n *\n * @remarks\n * Computed as `MontMul(a, R^2 mod p)`:\n * ```\n * toMontgomery(a) = MontMul(a, R^2) = a * R^2 * R^(-1) mod p = a * R mod p\n * ```\n * where the precomputed `R2_LIMBS` constant holds `R^2 mod p = 2^512 mod p`.\n *\n * This conversion must be performed before any Montgomery multiplication. After\n * conversion, all field arithmetic happens in the Montgomery domain until the\n * final result is converted back via `fromMontgomery`.\n *\n * @param a - A field element in standard form (4-limb, value `a` in `[0, p-1]`).\n * @returns The Montgomery form `aR mod p` in 4-limb representation.\n *\n * @example\n * ```typescript\n * // Internal usage in bn254ModuloMul:\n * const aM = toMontgomery(bigintToLimbs(7n));\n * // aM now represents 7 * R mod p in the Montgomery domain\n * ```\n *\n * @internal\n */\nfunction toMontgomery(a: Bn254FieldElementLimb): Bn254FieldElementLimb {\n return montgomeryMulLimbs(a, R2_LIMBS);\n}\n\n/**\n * Converts a field element from Montgomery form back to standard form: `aR -> a mod p`.\n *\n * @remarks\n * Computed as `MontMul(aR, 1)` where `1` is the standard (non-Montgomery) integer 1:\n * ```\n * fromMontgomery(aR) = MontMul(aR, 1) = aR * 1 * R^(-1) mod p = a mod p\n * ```\n * The standard-form `1` is the limb tuple `[1n, 0n, 0n, 0n]`.\n *\n * @param a - A field element in Montgomery form (4-limb, value `aR mod p`).\n * @returns The standard form `a mod p` in 4-limb representation.\n *\n * @example\n * ```typescript\n * // Internal usage in bn254ModuloMul:\n * const aM = toMontgomery(bigintToLimbs(7n));\n * const bM = toMontgomery(bigintToLimbs(8n));\n * const productM = montgomeryMulLimbs(aM, bM);\n * const product = fromMontgomery(productM);\n * limbsToBigint(product); // 56n\n * ```\n *\n * @internal\n */\nfunction fromMontgomery(a: Bn254FieldElementLimb): Bn254FieldElementLimb {\n // Multiply by 1 (in standard limb form, not Montgomery form)\n const one: Bn254FieldElementLimb = [1n, 0n, 0n, 0n];\n return montgomeryMulLimbs(a, one);\n}\n\n/**\n * Computes the additive inverse `-a mod p` in 4-limb representation.\n *\n * @remarks\n * ## Algorithm\n *\n * The additive inverse of `a` is `p - a` when `a != 0`, and `0` when `a == 0`.\n * The zero check is performed in constant time by OR-ing all limbs:\n * ```\n * isZero = (a[0] | a[1] | a[2] | a[3]) === 0n ? 1n : 0n\n * ```\n * The subtraction `p - a` is computed unconditionally via `subModuleLimbs(P_LIMBS, a)`.\n * The final result is then selected using `ctSelect`:\n * - If `isZero === 1n`: return `[0n, 0n, 0n, 0n]`\n * - If `isZero === 0n`: return `p - a`\n *\n * @param a - The field element to negate, in 4-limb form, value in `[0, p-1]`.\n * @returns The negation `-a mod p` in 4-limb form.\n *\n * @example\n * ```typescript\n * // Internal usage in bn254ModuloNeg:\n * const aLimbs = bigintToLimbs(10n);\n * const negLimbs = negModuleLimbs(aLimbs);\n * limbsToBigint(negLimbs); // BN254_FIELD_PRIME - 10n\n *\n * const zeroLimbs = bigintToLimbs(0n);\n * const negZero = negModuleLimbs(zeroLimbs);\n * limbsToBigint(negZero); // 0n\n * ```\n *\n * @internal\n */\nfunction negModuleLimbs(a: Bn254FieldElementLimb): Bn254FieldElementLimb {\n // Check if a is zero (constant-time)\n const isZero = (a[0] | a[1] | a[2] | a[3]) === 0n ? 1n : 0n;\n\n // Compute p - a\n const result = subModuleLimbs(P_LIMBS, a);\n\n // If a was zero, return zero; else return p - a\n return [\n ctSelect(isZero, 0n, result[0]),\n ctSelect(isZero, 0n, result[1]),\n ctSelect(isZero, 0n, result[2]),\n ctSelect(isZero, 0n, result[3]),\n ];\n}\n\n/**\n * Computes `base^exp mod p` using the square-and-multiply algorithm entirely in\n * the Montgomery domain.\n *\n * @remarks\n * ## Algorithm: Square-and-Multiply in Montgomery Domain\n *\n * 1. Initialize `result = ONE_MONT` (the Montgomery form of `1`, i.e., `R mod p`).\n * 2. For each bit of `exp` from least significant to most significant:\n * - If the bit is set: `result = MontMul(result, current)`\n * - Square: `current = MontMul(current, current)`\n * 3. Return `result`, which is `base^exp * R mod p` in Montgomery form.\n * The caller (`bn254ModuloInv`) converts back via `fromMontgomery`.\n *\n * ## Note on Constant Time\n *\n * This function branches on bits of `exp`. When `exp = p - 2` (for Fermat inversion),\n * `p` is a public constant, so leaking bits of `exp` via timing does NOT compromise\n * secret data. The branching is therefore acceptable.\n *\n * @param base - The base in Montgomery form (4-limb, value `base * R mod p`).\n * @param exp - The exponent as a `bigint` (standard non-negative integer, not in Montgomery form).\n * @returns `base^exp * R mod p` in 4-limb Montgomery form.\n *\n * @example\n * ```typescript\n * // Internal usage in bn254ModuloInv:\n * const aM = toMontgomery(bigintToLimbs(7n));\n * const invM = moduleExpMontgomery(aM, BN254_FIELD_PRIME - 2n);\n * const inv = fromMontgomery(invM);\n * limbsToBigint(inv); // 7^(-1) mod p\n * ```\n *\n * @internal\n */\nfunction moduleExpMontgomery(base: Bn254FieldElementLimb, exp: bigint): Bn254FieldElementLimb {\n let result = ONE_MONT; // 1 in Montgomery form\n let current = base;\n\n while (exp > 0n) {\n if ((exp & 1n) === 1n) {\n result = montgomeryMulLimbs(result, current);\n }\n current = montgomeryMulLimbs(current, current);\n exp >>= 1n;\n }\n\n return result;\n}\n\n// =============================================================================\n// Exported Functions\n// =============================================================================\n\n/**\n * Constant-time modular addition over the BN254 scalar field.\n *\n * Computes `(a + b) mod p` where `p = BN254_FIELD_PRIME`.\n *\n * @param a - First addend. Must be in the canonical range `[0, p-1]`.\n * @param b - Second addend. Must be in the canonical range `[0, p-1]`.\n * @returns The sum `(a + b) mod p` in the canonical range `[0, p-1]`.\n *\n * @remarks\n * This is the production constant-time implementation of `ModuloAddFunction`.\n * Internally, it converts both inputs to 4-limb form, runs `addModuleLimbs`\n * (which performs carry propagation and a conditional trial subtraction),\n * and reconstructs the output bigint.\n *\n * The function processes all 4 limbs uniformly with no early exit, ensuring\n * constant-operation-count execution.\n *\n * @example\n * ```typescript\n * import { bn254ModuloAdd, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Basic addition\n * const sum = bn254ModuloAdd(10n, 20n); // 30n\n *\n * // Wrap-around at the field boundary\n * const nearPrime = BN254_FIELD_PRIME - 1n;\n * const wrapped = bn254ModuloAdd(nearPrime, 2n); // 1n\n *\n * // Additive identity\n * const identity = bn254ModuloAdd(42n, 0n); // 42n\n * ```\n *\n * @see {@link getBn254ModularAdder} Cached getter for this function\n * @see {@link bn254ModuloSub} For modular subtraction\n * @see {@link ModuloAddFunction} The interface type this satisfies\n *\n * @public\n */\nexport const bn254ModuloAdd: ModuleAddFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n const resultLimbs = addModuleLimbs(aLimbs, bLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Constant-time modular subtraction over the BN254 scalar field.\n *\n * Computes `(a - b) mod p` where `p = BN254_FIELD_PRIME`.\n *\n * @param a - Minuend. Must be in the canonical range `[0, p-1]`.\n * @param b - Subtrahend. Must be in the canonical range `[0, p-1]`.\n * @returns The difference `(a - b) mod p` in the canonical range `[0, p-1]`.\n *\n * @remarks\n * This is the production constant-time implementation of `ModuloSubFunction`.\n * Internally, it converts both inputs to 4-limb form, runs `subModuleLimbs`\n * (raw subtraction with borrow propagation followed by conditional addition of `p`),\n * and reconstructs the output bigint.\n *\n * When `a < b`, the result wraps around by adding `p`, giving `p - (b - a)`.\n *\n * @example\n * ```typescript\n * import { bn254ModuloSub, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Basic subtraction\n * const diff = bn254ModuloSub(30n, 10n); // 20n\n *\n * // Underflow wraps around the field boundary\n * const wrapped = bn254ModuloSub(5n, 10n); // BN254_FIELD_PRIME - 5n\n *\n * // Self-subtraction gives zero\n * const zero = bn254ModuloSub(42n, 42n); // 0n\n * ```\n *\n * @see {@link getBn254ModularSubtractor} Cached getter for this function\n * @see {@link bn254ModuloAdd} For modular addition\n * @see {@link bn254ModuloNeg} For modular negation\n * @see {@link ModuloSubFunction} The interface type this satisfies\n *\n * @public\n */\nexport const bn254ModuloSub: ModuleSubFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n const resultLimbs = subModuleLimbs(aLimbs, bLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Constant-time modular multiplication over the BN254 scalar field using\n * Montgomery multiplication.\n *\n * Computes `(a * b) mod p` where `p = BN254_FIELD_PRIME`.\n *\n * @param a - First factor. Must be in the canonical range `[0, p-1]`.\n * @param b - Second factor. Must be in the canonical range `[0, p-1]`.\n * @returns The product `(a * b) mod p` in the canonical range `[0, p-1]`.\n *\n * @remarks\n * This is the production constant-time implementation of `ModuloMulFunction`.\n * It performs three Montgomery operations:\n * 1. `toMontgomery(a)` — convert `a` to Montgomery form\n * 2. `toMontgomery(b)` — convert `b` to Montgomery form\n * 3. `montgomeryMulLimbs(aM, bM)` — multiply in Montgomery domain\n * 4. `fromMontgomery(resultM)` — convert result back to standard form\n *\n * ## Performance Note\n *\n * Each Montgomery conversion internally calls `montgomeryMulLimbs`, so the total\n * cost is 3 Montgomery multiplications per call to `bn254ModuloMul`. This is\n * acceptable for correctness and security, but for performance-critical paths\n * (e.g., exponentiation), consider keeping values in Montgomery form throughout\n * and only converting back at the end.\n *\n * @example\n * ```typescript\n * import { bn254ModuloMul, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * // Basic multiplication\n * const product = bn254ModuloMul(7n, 8n); // 56n\n *\n * // All results reduced mod p\n * const large = bn254ModuloMul(BN254_FIELD_PRIME - 1n, 2n); // p - 2n\n *\n * // Multiplicative identity\n * const identity = bn254ModuloMul(42n, 1n); // 42n\n * ```\n *\n * @see {@link getBn254ModularMultiplier} Cached getter for this function\n * @see {@link bn254ModuloInv} For multiplicative inverse\n * @see {@link ModuloMulFunction} The interface type this satisfies\n *\n * @public\n */\nexport const bn254ModuloMul: ModuleMulFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n\n // Convert to Montgomery form\n const aMont = toMontgomery(aLimbs);\n const bMont = toMontgomery(bLimbs);\n\n // Multiply in Montgomery form\n const resultMont = montgomeryMulLimbs(aMont, bMont);\n\n // Convert back from Montgomery form\n const resultLimbs = fromMontgomery(resultMont);\n\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Constant-time modular negation over the BN254 scalar field.\n *\n * Computes `-a mod p`, equal to `p - a` for non-zero `a`, and `0` for `a == 0`.\n *\n * @param a - The value to negate. Must be in the canonical range `[0, p-1]`.\n * @returns `-a mod p` in the canonical range `[0, p-1]`.\n *\n * @remarks\n * This is the production constant-time implementation of `ModuloNegFunction`.\n * Internally, it converts the input to 4-limb form and calls `negModuleLimbs`,\n * which:\n * 1. Detects zero via bitwise OR of all limbs (constant-time zero check)\n * 2. Unconditionally computes `p - a` via `subModuleLimbs(P_LIMBS, a)`\n * 3. Selects `0` or `p - a` using `ctSelect` based on the zero flag\n *\n * @example\n * ```typescript\n * import { bn254ModuloNeg, bn254ModuloAdd, BN254_FIELD_PRIME } from \"@umbra/sdk\";\n *\n * const a = 10n;\n * const negA = bn254ModuloNeg(a); // BN254_FIELD_PRIME - 10n\n *\n * // Verify: a + (-a) = 0 (mod p)\n * const sum = bn254ModuloAdd(a, negA); // 0n\n *\n * // Negation of zero is zero\n * console.log(bn254ModuloNeg(0n) === 0n); // true\n * ```\n *\n * @see {@link getBn254ModularNegator} Cached getter for this function\n * @see {@link bn254ModuloSub} Subtraction as a + (-b)\n * @see {@link ModuloNegFunction} The interface type this satisfies\n *\n * @public\n */\nexport const bn254ModuloNeg: ModuleNegFunction = (a: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const resultLimbs = negModuleLimbs(aLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Constant-time modular multiplicative inverse over the BN254 scalar field\n * using Fermat's Little Theorem and Montgomery exponentiation.\n *\n * Computes `a^(-1) mod p` such that `a * a^(-1) ≡ 1 (mod p)`.\n *\n * @param a - The value to invert. Must be non-zero and in `[1, p-1]`.\n * @returns `a^(-1) mod p` in the canonical range `[1, p-1]`.\n * @throws {Error} If `a === 0n`, since zero has no multiplicative inverse.\n *\n * @remarks\n * This is the production implementation of `ModuloInvFunction`.\n *\n * ## Algorithm\n *\n * By Fermat's Little Theorem: `a^(p-1) ≡ 1 (mod p)` for prime `p` and `a != 0`.\n * Therefore: `a^(-1) ≡ a^(p-2) (mod p)`.\n *\n * This function computes `a^(p-2) mod p` via:\n * 1. Convert `a` to Montgomery form: `aM = toMontgomery(a)`\n * 2. Compute `aM^(p-2)` via `moduleExpMontgomery(aM, p-2)` (square-and-multiply)\n * 3. Convert back: `inv = fromMontgomery(resultM)`\n *\n * ## Complexity\n *\n * The exponent `p - 2` has 254 bits. The square-and-multiply algorithm requires\n * at most 254 squarings and at most 254 multiplications (one per set bit).\n * Each Montgomery multiplication is O(4^2) = O(16) 64-bit operations plus\n * carry/borrow propagation.\n *\n * ## Zero Handling\n *\n * An explicit zero check is performed before entering the Montgomery path.\n * This is an early branch on `a === 0n` (the *public* exceptional case), so\n * it does not leak timing information about secret inputs (unless the caller\n * passes a secret zero, which would be a protocol error).\n *\n * @example\n * ```typescript\n * import { bn254ModuloInv, bn254ModuloMul } from \"@umbra/sdk\";\n *\n * const a = 7n;\n * const invA = bn254ModuloInv(a);\n *\n * // Verify: a * a^(-1) = 1 (mod p)\n * const product = bn254ModuloMul(a, invA); // 1n\n *\n * // Division: 42 / 7 = 6 (mod p)\n * const quotient = bn254ModuloMul(42n, invA); // 6n\n *\n * // This throws:\n * bn254ModuloInv(0n); // Error: Cannot compute modular inverse of zero\n * ```\n *\n * @see {@link getBn254ModularInverter} Cached getter for this function\n * @see {@link bn254ModuloMul} For multiplication (use to verify the inverse)\n * @see {@link ModuloInvFunction} The interface type this satisfies\n * @see {@link computeBn254LimbwiseSumInverse} For inverting a Base85 limb sum\n *\n * @public\n */\nexport const bn254ModuloInv: ModuleInvFunction = (a: bigint): bigint => {\n if (a === 0n) {\n throw new Error(\"Cannot compute modular inverse of zero\");\n }\n\n const aLimbs = bigintToLimbs(a);\n\n // Convert to Montgomery form\n const aMont = toMontgomery(aLimbs);\n\n // Compute a^(p-2) in Montgomery form using Fermat's Little Theorem\n const exp = BN254_FIELD_PRIME - 2n;\n const resultMont = moduleExpMontgomery(aMont, exp);\n\n // Convert back from Montgomery form\n const resultLimbs = fromMontgomery(resultMont);\n\n return limbsToBigint(resultLimbs);\n};\n\n// =============================================================================\n// Cached Getter Functions\n// =============================================================================\n\n/**\n * Cached instance of the modular addition function, populated lazily on first call.\n *\n * @remarks\n * This mutable module-level variable holds the singleton reference to `bn254ModuloAdd`.\n * It is initialized to `null` and populated on the first call to `getBn254ModularAdder`.\n * Nullish coalescing assignment (`??=`) ensures the assignment happens at most once,\n * making subsequent calls a single null-check + dereference.\n *\n * @internal\n */\nlet cachedModuleAdder: ModuleAddFunction | null = null;\n\n/**\n * Cached instance of the modular subtraction function, populated lazily on first call.\n *\n * @internal\n */\nlet cachedModuleSubtractor: ModuleSubFunction | null = null;\n\n/**\n * Cached instance of the modular multiplication function, populated lazily on first call.\n *\n * @internal\n */\nlet cachedModuleMultiplier: ModuleMulFunction | null = null;\n\n/**\n * Cached instance of the modular negation function, populated lazily on first call.\n *\n * @internal\n */\nlet cachedModuleNegator: ModuleNegFunction | null = null;\n\n/**\n * Cached instance of the modular inverse function, populated lazily on first call.\n *\n * @internal\n */\nlet cachedModuleInverter: ModuleInvFunction | null = null;\n\n/**\n * Returns a stable, cached reference to the BN254 constant-time modular addition function.\n *\n * @remarks\n * This getter exists to enable patterns where a function reference is stored once\n * and passed around by reference (e.g., stored in a closure, passed as a dependency,\n * or compared by identity). Every call returns the same `ModuloAddFunction` instance,\n * avoiding unnecessary object allocation.\n *\n * Internally uses nullish coalescing assignment (`??=`) for lazy initialization:\n * the cached value is set on the first call and reused on all subsequent calls.\n *\n * @returns The singleton `bn254ModuloAdd` function instance.\n *\n * @example\n * ```typescript\n * import { getBn254ModularAdder } from \"@umbra/sdk\";\n *\n * const modAdd = getBn254ModularAdder();\n *\n * // Use as a named function\n * const sum = modAdd(10n, 20n); // 30n\n *\n * // Same instance on every call — useful for referential equality checks\n * const modAdd2 = getBn254ModularAdder();\n * console.log(modAdd === modAdd2); // true\n *\n * // Pass as a dependency\n * const sampler = getBn254FieldElementSampler({ modAdd });\n * ```\n *\n * @see {@link bn254ModuloAdd} The underlying function\n *\n * @public\n */\nexport function getBn254ModularAdder(): ModuleAddFunction {\n cachedModuleAdder ??= bn254ModuloAdd;\n return cachedModuleAdder;\n}\n\n/**\n * Returns a stable, cached reference to the BN254 constant-time modular subtraction function.\n *\n * @remarks\n * Uses the same lazy-initialization pattern as `getBn254ModularAdder`. Returns the\n * same `bn254ModuloSub` instance on every call, enabling referential equality checks\n * and efficient dependency injection.\n *\n * @returns The singleton `bn254ModuloSub` function instance.\n *\n * @example\n * ```typescript\n * import { getBn254ModularSubtractor } from \"@umbra/sdk\";\n *\n * const modSub = getBn254ModularSubtractor();\n * const diff = modSub(30n, 10n); // 20n\n *\n * // Referential equality guaranteed\n * const modSub2 = getBn254ModularSubtractor();\n * console.log(modSub === modSub2); // true\n * ```\n *\n * @see {@link bn254ModuloSub} The underlying function\n *\n * @public\n */\nexport function getBn254ModularSubtractor(): ModuleSubFunction {\n cachedModuleSubtractor ??= bn254ModuloSub;\n return cachedModuleSubtractor;\n}\n\n/**\n * Returns a stable, cached reference to the BN254 constant-time modular multiplication function.\n *\n * @remarks\n * Uses the same lazy-initialization pattern as `getBn254ModularAdder`. Returns the\n * same `bn254ModuloMul` instance on every call. The underlying function uses\n * Montgomery multiplication internally.\n *\n * @returns The singleton `bn254ModuloMul` function instance.\n *\n * @example\n * ```typescript\n * import { getBn254ModularMultiplier } from \"@umbra/sdk\";\n *\n * const modMul = getBn254ModularMultiplier();\n * const product = modMul(7n, 8n); // 56n\n *\n * // Referential equality guaranteed\n * const modMul2 = getBn254ModularMultiplier();\n * console.log(modMul === modMul2); // true\n *\n * // Pass as a dependency to the sampler\n * const sampler = getBn254FieldElementSampler({ modMul });\n * ```\n *\n * @see {@link bn254ModuloMul} The underlying Montgomery multiplication function\n *\n * @public\n */\nexport function getBn254ModularMultiplier(): ModuleMulFunction {\n cachedModuleMultiplier ??= bn254ModuloMul;\n return cachedModuleMultiplier;\n}\n\n/**\n * Returns a stable, cached reference to the BN254 constant-time modular negation function.\n *\n * @remarks\n * Uses the same lazy-initialization pattern as `getBn254ModularAdder`. Returns the\n * same `bn254ModuloNeg` instance on every call.\n *\n * @returns The singleton `bn254ModuloNeg` function instance.\n *\n * @example\n * ```typescript\n * import { getBn254ModularNegator, getBn254ModularAdder } from \"@umbra/sdk\";\n *\n * const modNeg = getBn254ModularNegator();\n * const negated = modNeg(10n); // BN254_FIELD_PRIME - 10n\n *\n * // Verify: 10 + (-10) = 0\n * const modAdd = getBn254ModularAdder();\n * console.log(modAdd(10n, negated) === 0n); // true\n *\n * // Referential equality guaranteed\n * const modNeg2 = getBn254ModularNegator();\n * console.log(modNeg === modNeg2); // true\n * ```\n *\n * @see {@link bn254ModuloNeg} The underlying function\n *\n * @public\n */\nexport function getBn254ModularNegator(): ModuleNegFunction {\n cachedModuleNegator ??= bn254ModuloNeg;\n return cachedModuleNegator;\n}\n\n/**\n * Returns a stable, cached reference to the BN254 modular multiplicative inverse function.\n *\n * @remarks\n * Uses the same lazy-initialization pattern as `getBn254ModularAdder`. Returns the\n * same `bn254ModuloInv` instance on every call. Note that `bn254ModuloInv` uses\n * Fermat's Little Theorem with Montgomery exponentiation — it is significantly\n * more expensive than addition, subtraction, or a single multiplication.\n *\n * @returns The singleton `bn254ModuloInv` function instance.\n *\n * @example\n * ```typescript\n * import { getBn254ModularInverter, getBn254ModularMultiplier } from \"@umbra/sdk\";\n *\n * const modInv = getBn254ModularInverter();\n * const inverse = modInv(7n);\n *\n * // Verify: 7 * 7^(-1) = 1\n * const modMul = getBn254ModularMultiplier();\n * console.log(modMul(7n, inverse) === 1n); // true\n *\n * // Referential equality guaranteed\n * const modInv2 = getBn254ModularInverter();\n * console.log(modInv === modInv2); // true\n * ```\n *\n * @see {@link bn254ModuloInv} The underlying Fermat-based inversion function\n *\n * @public\n */\nexport function getBn254ModularInverter(): ModuleInvFunction {\n cachedModuleInverter ??= bn254ModuloInv;\n return cachedModuleInverter;\n}\n\n// =============================================================================\n// Base85 Limb Operations\n// =============================================================================\n\n/**\n * Computes the modular multiplicative inverse of the sum of a `Base85LimbTuple`\n * in the BN254 scalar field.\n *\n * Given a `Base85LimbTuple` with fields `low`, `middle`, and `high`, computes:\n * ```\n * (low + middle + high)^(-1) mod p\n * ```\n *\n * @param limbs - A `Base85LimbTuple` containing three 85-bit limbs:\n * `low` (bits 0–84), `middle` (bits 85–169), and `high` (bits 170–255).\n * @returns The modular inverse of the sum as a `Bn254FieldElement` in `[1, p-1]`.\n * @throws {Error} If the sum `low + middle + high ≡ 0 (mod p)`, meaning no\n * multiplicative inverse exists.\n *\n * @remarks\n * ## Context: ZK Non-Zero Witness\n *\n * In Circom/Groth16 zero-knowledge circuits, proving that a value is non-zero\n * requires the prover to supply the multiplicative inverse of that value as an\n * auxiliary witness input. The circuit then verifies:\n * ```\n * value * witness_inv = 1\n * ```\n * which can only be satisfied if `value != 0`.\n *\n * For values represented as three 85-bit limbs (Base85 format, common in\n * Poseidon hash inputs), the circuit may require the inverse of the *sum of limbs*\n * rather than the inverse of the fully reconstructed value. This is because:\n * 1. If all limbs are zero, the full value is zero (and the sum is also zero).\n * 2. If any limb is non-zero, the sum is non-zero (given the limb range constraints).\n * 3. Computing the sum is cheaper in the circuit than the full positional reconstruction.\n *\n * ## Security\n *\n * The inversion is performed via `bn254ModuloInv`, which uses Fermat's Little Theorem\n * and Montgomery form — the same constant-time path as all other inversions in this\n * module.\n *\n * @example\n * ```typescript\n * import {\n * computeBn254LimbwiseSumInverse,\n * bn254ModuloMul,\n * } from \"@umbra/sdk\";\n * import { assertBase85Limb } from \"@umbra/sdk\";\n *\n * const low = 1000n;\n * const middle = 2000n;\n * const high = 3000n;\n * assertBase85Limb(low, \"low\");\n * assertBase85Limb(middle, \"middle\");\n * assertBase85Limb(high, \"high\");\n *\n * // Computes (1000 + 2000 + 3000)^(-1) mod p = 6000^(-1) mod p\n * const inverse = computeBn254LimbwiseSumInverse({ low, middle, high });\n *\n * // Verify: sum * inverse = 1 (mod p)\n * const sum = (low + middle + high) % BN254_FIELD_PRIME;\n * assertBn254FieldElement(sum);\n * const check = bn254ModuloMul(sum, inverse);\n * console.log(check === 1n); // true\n * ```\n *\n * @see {@link bn254ModuloInv} The underlying inversion function\n * @see {@link Base85LimbTuple} The input type from `crypto/poseidon/types`\n * @see {@link ./operations.computeBn254LimbwiseSumInverse} The non-CT version in `operations.ts`\n *\n * @public\n */\nexport function computeBn254LimbwiseSumInverse(limbs: Base85LimbTuple): Bn254FieldElement {\n // Sum the limbs (each limb is < 2^85, so sum fits well within bigint)\n const sum = (limbs.low + limbs.middle + limbs.high) % BN254_FIELD_PRIME;\n\n if (sum === 0n) {\n throw new Error(\n \"Cannot compute modular inverse of zero sum. \" + \"The sum of Base85 limbs must be non-zero.\",\n );\n }\n\n // Compute modular inverse using Fermat's Little Theorem\n const inverse = bn254ModuloInv(sum);\n\n assertBn254FieldElement(inverse);\n return inverse;\n}\n","/**\n * BN254 Field Element Sampler Implementation\n *\n * This module provides a constant-time implementation for sampling BN254 scalar\n * field elements from 512-bit big-endian byte arrays. The primary use case is\n * deriving field elements from hash outputs (e.g., SHA-512, Keccak-512) or from\n * concatenated CSPRNG outputs, as required by Fiat-Shamir transformations and\n * key derivation in ZK proof systems.\n *\n * @remarks\n * ## Why 512 Bits?\n *\n * The BN254 scalar field prime `p` is approximately `2^254`. If a 256-bit\n * random value were mapped directly into the field via `value mod p`, there would\n * be a statistical bias: the values in `[0, 2^256 mod p - 1]` would appear with\n * probability `2/(floor(2^256 / p) + 1)`, while higher values appear with\n * probability `1/(floor(2^256 / p) + 1)`. This bias is approximately `2^(-127)`,\n * which is borderline for cryptographic applications.\n *\n * Using a 512-bit input reduces the maximum bias to approximately `2^(-254)`,\n * which is cryptographically negligible for any practical security level.\n *\n * ## Algorithm\n *\n * Given a 512-bit big-endian input `h`, the module:\n * 1. Splits `h` into two 256-bit halves (`high = h[0..31]`, `low = h[32..63]`)\n * 2. Reduces both halves to `[0, p)` using constant-time trial subtraction (`reduce256`)\n * 3. Computes `result = (high * R + low) mod p` where `R = 2^256 mod p`\n * (the Montgomery constant for converting from 512-bit to field element)\n *\n * This is equivalent to interpreting the 512-bit value as an integer and reducing\n * it modulo `p` in a constant-time manner.\n *\n * ## Constant-Time Guarantees\n *\n * All internal operations are constant-operation-count:\n * - `ctSelect`: bitwise masking instead of branching\n * - `bigintToLimbs` / `limbsToBigint`: fixed 4-limb operations\n * - `conditionalSubtractP`: always subtracts and always selects (via mask)\n * - `reduce256`: exactly 5 conditional subtractions, no early exit\n *\n * True hardware-level constant time cannot be guaranteed in JavaScript due to JIT\n * compilation and BigInt internals, but the implementation avoids all data-dependent\n * control flow.\n *\n * @see {@link ./interfaces.U512BasedBn254FieldElementSamplerFunction} Interface type\n * @see {@link ./interfaces.U512BasedBn254FieldElementSamplerDeps} Dependency injection type\n * @see {@link ./field-arithmetic} The constant-time modular arithmetic layer\n *\n * @packageDocumentation\n * @module math/bn254/field-element-sampler\n */\n\nimport type {\n U512BasedBn254FieldElementSamplerFunction as U512BasedBn254FieldElementSamplerFunction,\n U512BasedBn254FieldElementSamplerDeps,\n} from \"./interfaces\";\nimport { type U512BeBytes, U256_BYTE_LENGTH } from \"../../common/types\";\nimport { createU256BeBytes } from \"../../common/converters/branded\";\nimport { decodeU256BeBytesToU256 } from \"../../common/converters/mathematics\";\nimport {\n bn254ModuloAdd as bn254ModuleAdd,\n bn254ModuloMul as bn254ModuleMul,\n} from \"./field-arithmetic\";\n\n/* =============================================================================\n * CONSTANTS\n * ============================================================================= */\n\n/**\n * Number of bits per 64-bit limb, as a `bigint` for use in shift operations.\n *\n * @remarks\n * Used throughout the limb arithmetic to shift values by 64-bit positions.\n * Storing as a `bigint` avoids repeated conversions in hot paths.\n *\n * @internal\n */\nconst N64 = 64n;\n\n/**\n * Bit mask for extracting the lower 64 bits of a `bigint`.\n *\n * @remarks\n * Equal to `2^64 - 1 = 0xFFFFFFFFFFFFFFFF`. Applied via bitwise AND to\n * isolate the 64-bit limb after addition or shift operations that may\n * produce values wider than 64 bits.\n *\n * @internal\n */\nconst MASK64 = 0xff_ff_ff_ff_ff_ff_ff_ffn;\n\n/**\n * The BN254 scalar field prime `p` decomposed into four 64-bit little-endian limbs.\n *\n * @remarks\n * The prime is:\n * `p = 21888242871839275222246405745257275088548364400416034343698204186575808495617`\n * In hexadecimal: `0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001`\n *\n * Limb decomposition (little-endian, each limb is 64 bits):\n * - `P_LIMBS[0]` = `0x43e1f593f0000001` (bits 0–63)\n * - `P_LIMBS[1]` = `0x2833e84879b97091` (bits 64–127)\n * - `P_LIMBS[2]` = `0xb85045b68181585d` (bits 128–191)\n * - `P_LIMBS[3]` = `0x30644e72e131a029` (bits 192–255)\n *\n * This representation mirrors that used in `field-arithmetic.ts` and is required\n * for the constant-time `conditionalSubtractP` function below.\n *\n * @internal\n */\nconst P_LIMBS: readonly [bigint, bigint, bigint, bigint] = [\n 0x43_e1_f5_93_f0_00_00_01n, // limb 0 (bits 0-63)\n 0x28_33_e8_48_79_b9_70_91n, // limb 1 (bits 64-127)\n 0xb8_50_45_b6_81_81_58_5dn, // limb 2 (bits 128-191)\n 0x30_64_4e_72_e1_31_a0_29n, // limb 3 (bits 192-255)\n];\n\n/**\n * The Montgomery constant `R = 2^256 mod p`.\n *\n * @remarks\n * This value is used to map a 512-bit integer into the field by computing:\n * ```\n * result = (high * R + low) mod p\n * ```\n * where `high` and `low` are the two 256-bit halves of the 512-bit input.\n *\n * Derivation:\n * `R = 2^256 mod p`\n * ` = 6350874878119819312338956282401532410528162663560392320966563075034087161851`\n *\n * This value was computed as:\n * `(2n ** 256n) % 21888242871839275222246405745257275088548364400416034343698204186575808495617n`\n *\n * @internal\n */\nconst R_MOD_P =\n 6_350_874_878_119_819_312_338_956_282_401_532_410_528_162_663_560_392_320_966_563_075_034_087_161_851n;\n\n/* =============================================================================\n * INTERNAL HELPER FUNCTIONS\n * ============================================================================= */\n\n/**\n * Performs a constant-time conditional select between two `bigint` values.\n *\n * Returns `x` if `bit === 1n`, or `y` if `bit === 0n`, using bitwise masking\n * instead of a conditional branch.\n *\n * @remarks\n * ## How It Works\n *\n * In two's complement arithmetic, `-1n` has all bits set (`0xFFFF...FFFF`).\n * The mask is computed as `-bit`:\n * - If `bit === 1n`: `mask = -1n` (all bits set), so `(x & mask) | (y & ~mask) = x | 0 = x`\n * - If `bit === 0n`: `mask = 0n` (no bits set), so `(x & mask) | (y & ~mask) = 0 | y = y`\n *\n * Note: JavaScript's `bigint` supports arbitrary-precision two's complement, so\n * `-1n` in `bigint` arithmetic behaves as an infinite sequence of set bits, making\n * this idiom well-defined and safe.\n *\n * @param bit - Selection bit: must be exactly `0n` or `1n`.\n * @param x - Value returned when `bit === 1n`.\n * @param y - Value returned when `bit === 0n`.\n * @returns `x` if `bit === 1n`; `y` otherwise.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const chosen = ctSelect(1n, 42n, 99n); // 42n\n * const other = ctSelect(0n, 42n, 99n); // 99n\n * ```\n *\n * @internal\n */\nfunction ctSelect(bit: bigint, x: bigint, y: bigint): bigint {\n const mask = -bit;\n return (x & mask) | (y & ~mask);\n}\n\n/**\n * Converts a `bigint` value to a 4-element little-endian 64-bit limb array.\n *\n * @remarks\n * Each limb is isolated via a right shift and a 64-bit mask:\n * ```\n * limb[k] = (value >> (64 * k)) & MASK64\n * ```\n * The input `value` should be in the range `[0, 2^256 - 1]` for a meaningful\n * 4-limb representation; higher bits are silently truncated.\n *\n * @param value - The `bigint` to decompose into 64-bit limbs.\n * @returns A 4-tuple `[limb0, limb1, limb2, limb3]` in little-endian order.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const limbs = bigintToLimbs(1n); // [1n, 0n, 0n, 0n]\n * const shifted = bigintToLimbs(2n ** 64n); // [0n, 1n, 0n, 0n]\n * ```\n *\n * @internal\n */\nfunction bigintToLimbs(value: bigint): readonly [bigint, bigint, bigint, bigint] {\n return [\n value & MASK64,\n (value >> N64) & MASK64,\n (value >> (N64 * 2n)) & MASK64,\n (value >> (N64 * 3n)) & MASK64,\n ];\n}\n\n/**\n * Reconstructs a `bigint` from a 4-element little-endian 64-bit limb array.\n *\n * @remarks\n * Applies the positional formula:\n * ```\n * value = limbs[0] + limbs[1] * 2^64 + limbs[2] * 2^128 + limbs[3] * 2^192\n * ```\n * This is the inverse of `bigintToLimbs`. The result is in the range\n * `[0, 2^256 - 1]` when all limbs are in `[0, 2^64 - 1]`.\n *\n * @param limbs - A 4-tuple `[limb0, limb1, limb2, limb3]` in little-endian order.\n * @returns The reconstructed `bigint` value.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const val = limbsToBigint([1n, 0n, 0n, 0n]); // 1n\n * const large = limbsToBigint([0n, 1n, 0n, 0n]); // 2^64\n * ```\n *\n * @internal\n */\nfunction limbsToBigint(limbs: readonly [bigint, bigint, bigint, bigint]): bigint {\n return limbs[0] + (limbs[1] << N64) + (limbs[2] << (N64 * 2n)) + (limbs[3] << (N64 * 3n));\n}\n\n/**\n * Performs a single constant-time conditional subtraction of the field prime `p`.\n *\n * If `value >= p`, returns `value - p`. Otherwise returns `value` unchanged.\n * The selection between the two outcomes is performed using constant-time bitwise\n * masking to avoid data-dependent branching.\n *\n * @remarks\n * ## Algorithm\n *\n * 1. Perform a trial subtraction `d = value - p` across all 4 limbs with borrow\n * propagation, tracking the final borrow bit (`borrow3`).\n * 2. `borrow3 === 1n` means `value < p` (subtraction underflowed); use original `value`.\n * 3. `borrow3 === 0n` means `value >= p` (no underflow); use the subtracted result `d`.\n * 4. Each limb of the output is selected via `ctSelect(useOriginal, original[k], d[k])`.\n *\n * This function is called up to 5 times by `reduce256` to fully reduce a 256-bit\n * value into the range `[0, p-1]`.\n *\n * @param limbs - The value to conditionally reduce, as a 4-tuple of 64-bit limbs.\n * @returns The conditionally subtracted result, still as a 4-tuple of 64-bit limbs.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const pLimbs = bigintToLimbs(BN254_FIELD_PRIME);\n * const reduced = conditionalSubtractP(pLimbs);\n * // reduced represents 0n (p - p = 0)\n *\n * const smallLimbs = bigintToLimbs(5n);\n * const unchanged = conditionalSubtractP(smallLimbs);\n * // unchanged still represents 5n (5 < p, no subtraction)\n * ```\n *\n * @internal\n */\nfunction conditionalSubtractP(\n limbs: readonly [bigint, bigint, bigint, bigint],\n): readonly [bigint, bigint, bigint, bigint] {\n const [l0, l1, l2, l3] = limbs;\n const [p0, p1, p2, p3] = P_LIMBS;\n\n // Trial subtraction: d = value - p\n const sub0 = l0 - p0;\n const d0 = sub0 & MASK64;\n const borrow0 = -(sub0 >> N64) & 1n;\n\n const sub1 = l1 - p1 - borrow0;\n const d1 = sub1 & MASK64;\n const borrow1 = -(sub1 >> N64) & 1n;\n\n const sub2 = l2 - p2 - borrow1;\n const d2 = sub2 & MASK64;\n const borrow2 = -(sub2 >> N64) & 1n;\n\n const sub3 = l3 - p3 - borrow2;\n const d3 = sub3 & MASK64;\n const borrow3 = -(sub3 >> N64) & 1n;\n\n // If borrow3 is 0, value >= p, so use d (the subtracted value)\n // If borrow3 is 1, value < p, so use original value\n const useOriginal = borrow3;\n\n return [\n ctSelect(useOriginal, l0, d0),\n ctSelect(useOriginal, l1, d1),\n ctSelect(useOriginal, l2, d2),\n ctSelect(useOriginal, l3, d3),\n ];\n}\n\n/**\n * Constant-time reduction of an arbitrary 256-bit integer to the canonical\n * representative in `[0, p)`.\n *\n * @remarks\n * ## Why 5 Subtractions?\n *\n * For a 256-bit value `v` in the range `[0, 2^256 - 1]`, the maximum number of\n * times `p` must be subtracted to reach the canonical range is:\n * ```\n * floor((2^256 - 1) / p) = floor(2^256 / p) ≈ 5.29\n * ```\n * Therefore, at most 6 subtractions are needed, but in practice 5 suffice for\n * any value strictly less than `2^256`. This function performs exactly 5\n * conditional subtractions unconditionally (constant-operation-count), ensuring\n * no data-dependent early termination.\n *\n * @param value - A 256-bit non-negative integer (`0 <= value < 2^256`).\n * @returns The unique representative of `value mod p` in `[0, p-1]`.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const bigValue = 2n ** 256n - 1n; // maximum 256-bit value\n * const reduced = reduce256(bigValue); // some value in [0, p-1]\n *\n * const alreadyReduced = 42n;\n * const same = reduce256(alreadyReduced); // 42n (unchanged)\n * ```\n *\n * @internal\n */\nfunction reduce256(value: bigint): bigint {\n let limbs = bigintToLimbs(value);\n\n // Perform 5 conditional subtractions (constant-time)\n // This handles values up to ~5.29p (the maximum for 256-bit inputs)\n limbs = conditionalSubtractP(limbs);\n limbs = conditionalSubtractP(limbs);\n limbs = conditionalSubtractP(limbs);\n limbs = conditionalSubtractP(limbs);\n limbs = conditionalSubtractP(limbs);\n\n return limbsToBigint(limbs);\n}\n\n/**\n * Reads 32 bytes from `bytes` starting at `offset` and decodes them as a\n * big-endian unsigned 256-bit integer.\n *\n * @remarks\n * This is a thin adapter that extracts a 32-byte slice and delegates to the\n * project's canonical `decodeU256BeBytesToU256` converter. It exists to centralize\n * the slice-and-decode pattern used twice in the sampler (once for `high`, once\n * for `low`).\n *\n * @param bytes - The source byte array. Must have at least `offset + 32` bytes.\n * @param offset - The zero-based byte index at which to begin reading.\n * @returns The big-endian integer value of `bytes[offset .. offset + 32)`.\n *\n * @example\n * ```typescript\n * // Internal usage:\n * const input = new Uint8Array(64); // 64 zero bytes\n * const high = bytesToBigintBE(input, 0); // 0n (bytes 0-31)\n * const low = bytesToBigintBE(input, 32); // 0n (bytes 32-63)\n * ```\n *\n * @internal\n */\nfunction bytesToBigintBE(bytes: Uint8Array, offset: number): bigint {\n const slice = bytes.slice(offset, offset + U256_BYTE_LENGTH);\n const u256BeBytes = createU256BeBytes(slice);\n return decodeU256BeBytesToU256(u256BeBytes);\n}\n\n/* =============================================================================\n * SAMPLER FACTORY\n * ============================================================================= */\n\n/**\n * Creates a factory-configured U512-based BN254 field element sampler.\n *\n * Returns a closure that accepts a 64-byte big-endian byte array (`U512BeBytes`)\n * and produces a uniformly distributed element of the BN254 scalar field.\n *\n * @param deps - Optional dependency injection for custom modular arithmetic.\n * When omitted, uses the production constant-time implementations from\n * `field-arithmetic.ts` (`bn254ModuloAdd` and `bn254ModuloMul`).\n * @returns A `U512BasedBn254FieldElementSamplerFunction` closure bound to the\n * provided (or default) arithmetic functions.\n *\n * @remarks\n * ## Algorithm\n *\n * The returned sampler function, when invoked with a 64-byte input `h`:\n *\n * 1. **Split**: reads `high = h[0..31]` and `low = h[32..63]` as big-endian integers.\n * 2. **Reduce**: calls `reduce256(high)` and `reduce256(low)` to bring both halves\n * into `[0, p-1]` using constant-time trial subtraction.\n * 3. **Combine**: computes `result = modMul(highReduced, R) + modAdd(lowReduced)`\n * — i.e., `(high * R + low) mod p` — where `R = 2^256 mod p`.\n *\n * This is mathematically equivalent to:\n * ```\n * result = (h interpreted as a 512-bit big-endian integer) mod p\n * ```\n *\n * ## Dependency Injection\n *\n * The `opts.modAdd` and `opts.modMul` overrides are applied to the final combine\n * step (step 3). The `reduce256` step always uses the internal constant-time\n * `conditionalSubtractP` regardless of injection. This design ensures that\n * tests can substitute the combine arithmetic while keeping the reduction step\n * deterministic.\n *\n * @example\n * ```typescript\n * import { getBn254FieldElementSampler } from \"@umbra/sdk\";\n *\n * // Default constant-time arithmetic\n * const sampler = getBn254FieldElementSampler();\n * const fieldElement = sampler(someU512Input);\n *\n * // Custom arithmetic for testing\n * const testSampler = getBn254FieldElementSampler({\n * modAdd: (a, b) => (a + b) % BN254_FIELD_PRIME,\n * modMul: (a, b) => (a * b) % BN254_FIELD_PRIME,\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Deriving a field element from two concatenated SHA-256 hashes\n * const hash1 = sha256(someData); // 32 bytes\n * const hash2 = sha256(someOtherData); // 32 bytes\n * const combined = new Uint8Array(64);\n * combined.set(hash1, 0);\n * combined.set(hash2, 32);\n * assertU512BeBytes(combined);\n *\n * const sampler = getBn254FieldElementSampler();\n * const fieldElement = sampler(combined);\n * // fieldElement is a well-distributed BN254 field element derived from the hashes\n * ```\n *\n * @see {@link bn254FieldElementSampler} Pre-instantiated default sampler\n * @see {@link U512BasedBn254FieldElementSamplerDeps} Dependency injection interface\n * @see {@link U512BasedBn254FieldElementSamplerFunction} The returned function type\n *\n * @public\n */\nexport function getBn254FieldElementSampler(\n deps?: U512BasedBn254FieldElementSamplerDeps,\n): U512BasedBn254FieldElementSamplerFunction {\n // Use provided functions or fall back to defaults\n const { modAdd: moduleAdd = bn254ModuleAdd, modMul: moduleMul = bn254ModuleMul } = deps ?? {};\n\n return (input: U512BeBytes): bigint => {\n // Extract high and low 256-bit halves (big-endian)\n // bytes 0-31 = high (most significant)\n // bytes 32-63 = low (least significant)\n const high = bytesToBigintBE(input, 0); // bytes 0-31\n const low = bytesToBigintBE(input, 32); // bytes 32-63\n\n // Reduce both halves to [0, p)\n // This is necessary because 256-bit values can be >= p\n const lowReduced = reduce256(low);\n const highReduced = reduce256(high);\n\n // Compute: result = (high × R + low) mod p\n // where R = 2^256 mod p\n const highTimesR = moduleMul(highReduced, R_MOD_P);\n const result = moduleAdd(highTimesR, lowReduced);\n\n return result;\n };\n}\n\n/**\n * The pre-instantiated default U512-based BN254 field element sampler.\n *\n * This is a convenience export of `getBn254FieldElementSampler()` with\n * no arguments — using the default constant-time `bn254ModuloAdd` and\n * `bn254ModuloMul` implementations from `field-arithmetic.ts`.\n *\n * @remarks\n * Use this export directly when you do not need to inject custom arithmetic.\n * It avoids the overhead of calling the factory function on every use.\n *\n * The sampler is stateless (it is a pure function of its input), so sharing this\n * instance across multiple call sites is safe.\n *\n * @example\n * ```typescript\n * import { bn254FieldElementSampler } from \"@umbra/sdk\";\n *\n * // Produce a field element from a 64-byte CSPRNG output\n * const randomBytes = crypto.getRandomValues(new Uint8Array(64));\n * assertU512BeBytes(randomBytes);\n * const fieldElement = bn254FieldElementSampler(randomBytes);\n * // fieldElement is a uniformly distributed BN254 scalar field element\n * ```\n *\n * @see {@link getBn254FieldElementSampler} The factory for custom configurations\n * @see {@link U512BasedBn254FieldElementSamplerFunction} The function type\n *\n * @public\n */\nexport const bn254FieldElementSampler: U512BasedBn254FieldElementSamplerFunction =\n getBn254FieldElementSampler();\n","/**\n * Curve25519 Base Field Types\n *\n * This module defines the branded type and validation primitives for elements\n * of the Curve25519 base field, whose prime modulus is p = 2^255 - 19.\n *\n * ## What is Curve25519?\n *\n * Curve25519 is a Montgomery-form elliptic curve designed by Daniel J. Bernstein\n * for high-performance, side-channel-resistant Diffie-Hellman key exchange. It is\n * specified in RFC 7748 and underlies two widely deployed cryptographic primitives:\n *\n * - **X25519** — Diffie-Hellman key agreement. Used in Umbra for encrypted token\n * account key registration (users register an X25519 public key so MXE-encrypted\n * balances can be shared with them).\n * - **Ed25519** — Digital signatures (uses the twisted-Edwards form of the same\n * underlying field).\n *\n * ## The Base Field GF(p)\n *\n * All Curve25519 point coordinates are elements of the prime field GF(p) where:\n * ```\n * p = 2^255 - 19\n * = 57896044618658097711785492504343953926634992332820282019728792003956564819949\n * ```\n *\n * The near-power-of-two structure of p makes modular reduction especially\n * efficient: because p ≡ -19 (mod 2^255), any reduction can be expressed as a\n * small multiply-and-add rather than a full division.\n *\n * ## Rescue-XLIX Cipher\n *\n * Within the Umbra SDK, field arithmetic over GF(p) is used primarily by the\n * **Rescue-XLIX block cipher** (see `crypto/rescue-cipher/`). Rescue-XLIX operates\n * over this same field and is the symmetric cipher used inside Arcium MPC\n * computations to produce and verify ciphertexts for encrypted Umbra token accounts.\n *\n * ## Contrast with BN254\n *\n * The SDK also provides `math/bn254/` for the BN254 scalar field\n * (p ≈ 2^254, ~100-bit security, pairing-friendly). That field is used for\n * Groth16 ZK proofs and Poseidon hashes. The two fields are **not interchangeable**:\n * elements of one field are not valid elements of the other.\n *\n * ## Branded Types\n *\n * `Curve25519FieldElement` is a branded `bigint` subtype. The branding enforces\n * at compile time that only validated, in-range values are passed to field\n * arithmetic functions, preventing silent truncation bugs.\n *\n * @module math/curve25519/types\n * @packageDocumentation\n */\n\nimport type { SubSubBrandedType } from \"../../common/branded\";\nimport type { U256 } from \"../../common/types\";\nimport { CryptographyAssertionError } from \"../../common/errors\";\n\n/**\n * The prime field modulus for the Curve25519 base field.\n *\n * @remarks\n * Defined as p = 2^255 - 19. In decimal:\n * ```\n * 57896044618658097711785492504343953926634992332820282019728792003956564819949\n * ```\n *\n * The near-power-of-two form is critical for efficient modular reduction: since\n * 2^255 ≡ 19 (mod p), a 256-bit product can be reduced using a single\n * multiplication by 19 and an addition, rather than a general division.\n *\n * This constant is shared by all field arithmetic operations in this module and\n * by the Rescue-XLIX cipher implementation in `crypto/rescue-cipher/`.\n *\n * @example\n * ```typescript\n * import { CURVE25519_FIELD_PRIME } from \"@umbra-privacy/sdk\";\n *\n * // Verify the prime is 2^255 - 19\n * const expected = (1n << 255n) - 19n;\n * console.log(CURVE25519_FIELD_PRIME === expected); // true\n *\n * // Manual modular reduction\n * const x = 2n ** 300n;\n * const reduced = x % CURVE25519_FIELD_PRIME;\n * ```\n *\n * @public\n */\nexport const CURVE25519_FIELD_PRIME = (1n << 255n) - 19n;\n\n/**\n * Branded type representing a validated element of the Curve25519 base field\n * GF(2^255 - 19).\n *\n * @remarks\n * A `Curve25519FieldElement` is a `bigint` that has been verified to lie in the\n * canonical range [0, p-1] where p = 2^255 - 19. The branding is a\n * compile-time phantom that prevents unvalidated bigints from being passed\n * to functions that expect field elements.\n *\n * The type sits at the third level of the branded-type hierarchy:\n * ```\n * bigint\n * └── U256 (branded bigint: 0 ≤ value < 2^256)\n * └── Curve25519FieldElement (branded U256: 0 ≤ value < p)\n * ```\n *\n * Unlike BN254FieldElement (used for Groth16 proofs / Poseidon hashes),\n * Curve25519FieldElement operates over a **different prime** and must not be\n * mixed with BN254 arithmetic. Field elements from the two curves are\n * structurally identical at runtime (both are `bigint`) but semantically\n * incompatible; the branded type hierarchy enforces this distinction\n * statically.\n *\n * ## Security Properties\n *\n * - Provides approximately 128 bits of security for discrete-logarithm problems.\n * - Curve25519 is designed to resist timing attacks: the prime's structure\n * permits implementations with uniform execution paths.\n * - Used in X25519 (ECDH) for Umbra encrypted token account key registration\n * and in Rescue-XLIX for MPC-layer symmetric encryption.\n *\n * @example\n * ```typescript\n * import {\n * assertCurve25519FieldElement,\n * type Curve25519FieldElement,\n * } from \"@umbra-privacy/sdk\";\n *\n * // Obtain a branded field element after validation\n * const raw = 12345n;\n * assertCurve25519FieldElement(raw, \"raw\");\n * const element: Curve25519FieldElement = raw;\n *\n * // Type error: plain bigint is not assignable to Curve25519FieldElement\n * // const bad: Curve25519FieldElement = 12345n; // compile error\n * ```\n *\n * @see {@link assertCurve25519FieldElement} — runtime validator that narrows `bigint` to this type\n * @see {@link CURVE25519_FIELD_PRIME} — the field prime p = 2^255 - 19\n * @see https://cr.yp.to/ecdh/curve25519-20060209.pdf — original Curve25519 specification\n * @see https://www.rfc-editor.org/rfc/rfc7748 — X25519 / X448 RFC\n *\n * @public\n */\nexport type Curve25519FieldElement = SubSubBrandedType<U256, \"Curve25519FieldElement\">;\n\n/**\n * Asserts that a `bigint` value is a valid Curve25519 base field element,\n * narrowing its TypeScript type to `Curve25519FieldElement` on success.\n *\n * @remarks\n * Validation checks, in order:\n * 1. The value must be a `bigint` (not `number`, `string`, etc.).\n * 2. The value must be non-negative: value ≥ 0.\n * 3. The value must be strictly less than the field prime: value < 2^255 - 19.\n *\n * This function is an **assertion function** (TypeScript `asserts` predicate).\n * After a successful call, the TypeScript compiler narrows the type of the\n * variable at the call site to `Curve25519FieldElement`, enabling it to be\n * used in APIs that require a validated field element without an explicit cast.\n *\n * Callers should use this function at trust boundaries — e.g., when accepting\n * field elements from user input, deserialization, or across module boundaries —\n * and rely on the typed field arithmetic functions afterwards.\n *\n * @param value - The `bigint` to validate. Must satisfy 0 ≤ value < 2^255 - 19.\n * @param name - Human-readable variable name for error messages. Defaults to\n * `\"value\"`. Provide a descriptive name to make assertion errors actionable.\n *\n * @throws {CryptographyAssertionError} If `value` is not a `bigint`.\n * @throws {CryptographyAssertionError} If `value` is negative (value < 0).\n * @throws {CryptographyAssertionError} If `value` is out of range (value ≥ p).\n *\n * @example\n * ```typescript\n * import {\n * assertCurve25519FieldElement,\n * CURVE25519_FIELD_PRIME,\n * } from \"@umbra-privacy/sdk\";\n *\n * // Valid: in-range bigint — type is narrowed to Curve25519FieldElement\n * const a = 12345n;\n * assertCurve25519FieldElement(a, \"a\");\n * // a is now Curve25519FieldElement\n *\n * // Invalid: negative value\n * assertCurve25519FieldElement(-1n, \"myValue\");\n * // throws CryptographyAssertionError: \"myValue: Value -1 is negative\"\n *\n * // Invalid: equals the field prime (must be strictly less)\n * assertCurve25519FieldElement(CURVE25519_FIELD_PRIME, \"myValue\");\n * // throws CryptographyAssertionError: \"myValue: Value exceeds Curve25519 field prime\"\n *\n * // Invalid: not a bigint\n * assertCurve25519FieldElement(42 as unknown as bigint, \"myValue\");\n * // throws CryptographyAssertionError: \"myValue: Expected bigint, got number\"\n * ```\n *\n * @see {@link Curve25519FieldElement} — the branded type this function produces\n * @see {@link CURVE25519_FIELD_PRIME} — the upper bound (exclusive) for valid elements\n *\n * @public\n */\nexport function assertCurve25519FieldElement(\n value: bigint,\n name = \"value\",\n): asserts value is Curve25519FieldElement {\n const variableName = name;\n if (typeof value !== \"bigint\") {\n throw new CryptographyAssertionError(`${variableName}: Expected bigint, got ${typeof value}`, {\n value,\n expectedType: \"Curve25519FieldElement\",\n });\n }\n if (value < 0n) {\n throw new CryptographyAssertionError(`${variableName}: Value ${String(value)} is negative`, {\n value,\n expectedType: \"Curve25519FieldElement\",\n constraint: \"value >= 0\",\n });\n }\n if (value >= CURVE25519_FIELD_PRIME) {\n throw new CryptographyAssertionError(`${variableName}: Value exceeds Curve25519 field prime`, {\n value,\n expectedType: \"Curve25519FieldElement\",\n constraint: \"value < 2^255 - 19\",\n });\n }\n}\n","/**\n * Curve25519 Base Field Arithmetic — Concrete Implementation\n *\n * This module provides the constant-operation-count implementations of all\n * modular arithmetic operations over the Curve25519 prime field GF(p), where:\n * ```\n * p = 2^255 - 19\n * = 57896044618658097711785492504343953926634992332820282019728792003956564819949\n * ```\n *\n * ## Role in the SDK\n *\n * This module is the lowest-level arithmetic layer in the SDK's cryptographic\n * stack. Its exported functions are consumed by:\n *\n * - **`crypto/rescue-cipher/`** — the Rescue-XLIX block cipher used inside\n * Arcium MPC computations for symmetric encryption of Umbra confidential\n * token account balances.\n * - **`math/curve25519/interfaces`** — the function-type contracts that the\n * exported symbols satisfy.\n * - Dependency-injection consumers that call\n * `getCurve25519FieldElementSampler` with custom arithmetic.\n *\n * X25519 key-exchange itself (used for Umbra encrypted token account key\n * registration) does not call this module directly — its scalar multiplication\n * is handled by `@noble/curves` — but the field prime is the same.\n *\n * ## Algorithm Overview\n *\n * ### Addition / Subtraction\n *\n * Both operations are implemented at the 4-limb level using carry/borrow\n * propagation, followed by a **constant-time conditional correction**:\n *\n * - **Addition**: compute `t = a + b`; if `t ≥ p` then return `t - p`, else `t`.\n * The conditional is resolved by a bitwise mask derived from the carry and\n * borrow, never an `if` statement.\n * - **Subtraction**: compute `d = a - b`; if a borrow occurred (a < b), add `p`\n * back. The borrow bit is propagated as a mask applied to `P_LIMBS`.\n *\n * ### Multiplication\n *\n * Uses JavaScript's native `BigInt` multiplication (`a * b`) followed by\n * a single `% p` reduction. While this is not a limb-level schoolbook\n * implementation, `BigInt` intermediate values of ≤ 510 bits keep the\n * per-call work uniform. Montgomery form is not used because the constant\n * conversion overhead is not amortised over the small number of multiplications\n * per Rescue-XLIX round.\n *\n * ### Inversion\n *\n * Uses Fermat's Little Theorem: `a^(-1) ≡ a^(p-2) (mod p)`. This delegates to\n * the square-and-multiply exponentiation function with a fixed exponent of\n * p - 2 ≈ 2^255, costing ≈ 255 squarings and ~128 multiplications.\n *\n * ### Exponentiation\n *\n * Binary (square-and-multiply) exponentiation via `moduleExpLimbs`. The loop\n * visits each bit of the exponent from LSB to MSB; the branch on the current\n * bit (`exp & 1n`) operates on the **exponent**, not secret field data, so it\n * does not constitute a secret-dependent branch.\n *\n * ## Security Considerations\n *\n * True hardware-level constant time cannot be guaranteed in JavaScript because\n * the V8/SpiderMonkey JIT, branch predictors, and GC can all introduce\n * data-dependent timing variation. These implementations are\n * **constant-operation-count**: they always execute the same sequence of BigInt\n * operations regardless of the input values. This is the accepted standard for\n * JavaScript cryptographic libraries (e.g., `@noble/curves`).\n *\n * Secret-dependent branching is avoided by:\n * - Using `ctSelect` (bitwise mask) for all conditional value choices.\n * - Processing all 4 limbs in every loop iteration regardless of value.\n * - Applying `P_LIMBS` correction via masking rather than a conditional add.\n *\n * ## Limb Representation\n *\n * All internal computation decomposes field elements into four 64-bit limbs\n * stored in little-endian order `[limb0, limb1, limb2, limb3]`:\n * ```\n * value = limb0 + limb1×2^64 + limb2×2^128 + limb3×2^192\n * ```\n * - `limb0` — bits 0-63 (least significant)\n * - `limb1` — bits 64-127\n * - `limb2` — bits 128-191\n * - `limb3` — bits 192-255 (most significant; high bit always 0 for valid elements)\n *\n * The 4-limb split keeps individual BigInt values at a uniform 64-bit size,\n * making per-limb arithmetic cost independent of the field element's magnitude.\n *\n * @module implementation/mathematics/curve25519-field-arithmetic\n * @packageDocumentation\n */\n\nimport type {\n Curve25519FieldElementLimb,\n Curve25519ModuloAddFunction as Curve25519ModuleAddFunction,\n Curve25519ModuloInvFunction as Curve25519ModuleInvFunction,\n Curve25519ModuloMulFunction as Curve25519ModuleMulFunction,\n Curve25519ModuloPowFunction as Curve25519ModulePowFunction,\n Curve25519ModuloSubFunction as Curve25519ModuleSubFunction,\n U512BasedCurve25519FieldElementSamplerFunction as U512BasedCurve25519FieldElementSamplerFunction,\n U512BasedCurve25519FieldElementSamplerDeps,\n} from \"./interfaces\";\nimport { CURVE25519_FIELD_PRIME, type Curve25519FieldElement } from \"./types\";\nimport { type U512BeBytes, U256_BYTE_LENGTH } from \"../../common/types\";\nimport { createU256BeBytes } from \"../../common/converters/branded\";\nimport { decodeU256BeBytesToU256 } from \"../../common/converters/mathematics\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * The number of bits per limb used in the 4-limb field element representation.\n *\n * @remarks\n * All field elements are decomposed into 4 limbs of exactly 64 bits each.\n * Using 64 as the limb width keeps each limb within the range of a single\n * 64-bit unsigned integer, making carry/borrow arithmetic straightforward\n * with BigInt shift operations.\n *\n * @internal\n */\nconst N64 = 64n;\n\n/**\n * Bitmask for extracting the lower 64 bits from a BigInt.\n *\n * @remarks\n * Equal to 2^64 - 1 = 0xFFFFFFFFFFFFFFFF. Applied with the bitwise AND\n * operator (`& MASK64`) after any addition or shift to isolate the low 64\n * bits of a result and discard any carry that has propagated into bit 64 or\n * above.\n *\n * @example\n * ```typescript\n * // Extract low 64 bits after an addition that may overflow\n * const sum = a + b + carry;\n * const low64 = sum & MASK64; // keep bits 0-63\n * const nextCarry = sum >> N64; // propagate bit 64 upwards\n * ```\n *\n * @internal\n */\nconst MASK64 = 0xff_ff_ff_ff_ff_ff_ff_ffn;\n\n/**\n * The Curve25519 field prime p = 2^255 - 19 decomposed into 4 × 64-bit limbs,\n * stored in little-endian order.\n *\n * @remarks\n * Binary representation of p = 2^255 - 19:\n * - Bits 0-63: `0xFFFFFFFFFFFFFFED` (= 2^64 - 19)\n * - Bits 64-127: `0xFFFFFFFFFFFFFFFF` (all ones)\n * - Bits 128-191:`0xFFFFFFFFFFFFFFFF` (all ones)\n * - Bits 192-255:`0x7FFFFFFFFFFFFFFF` (2^63 - 1; high bit is 0)\n *\n * The high bit of limb 3 being 0 reflects the fact that p < 2^255.\n *\n * This constant is used in:\n * - `addModuleLimbs` — trial subtraction to enforce the canonical range.\n * - `subModuleLimbs` — conditional addition to wrap negative differences.\n * - `reduce256Curve25519` — single-step reduction of 256-bit values.\n *\n * @privateRemarks\n * Limb 0 value derivation:\n * p = 2^255 - 19. The low 64 bits of p are:\n * 2^64 × floor(p / 2^64) + r => r = p mod 2^64 = (2^64 - 19) = 0xFFFFFFFFFFFFFFED\n *\n * @internal\n */\nconst P_LIMBS: Curve25519FieldElementLimb = [\n 0xff_ff_ff_ff_ff_ff_ff_edn, // limb 0 (bits 0-63): 2^64 - 19\n 0xff_ff_ff_ff_ff_ff_ff_ffn, // limb 1 (bits 64-127): all 1s\n 0xff_ff_ff_ff_ff_ff_ff_ffn, // limb 2 (bits 128-191): all 1s\n 0x7f_ff_ff_ff_ff_ff_ff_ffn, // limb 3 (bits 192-255): 2^63 - 1\n];\n\n// =============================================================================\n// Internal Helper Functions\n// =============================================================================\n\n/**\n * Constant-time conditional select between two `bigint` values.\n *\n * @remarks\n * Returns `x` when `bit === 1n` and `y` when `bit === 0n`, without branching\n * on the value of `bit`. The selection is performed using bitwise arithmetic:\n * ```\n * mask = -bit // 0n if bit=0, -1n (all ones) if bit=1\n * result = (x & mask) | (y & ~mask)\n * ```\n * This is the BigInt equivalent of the C idiom `(mask & x) | (~mask & y)`.\n *\n * `bit` MUST be exactly `0n` or `1n`. Passing any other value produces\n * undefined results.\n *\n * @param bit - Selection bit. Must be `0n` or `1n`.\n * @param x - Value returned when `bit === 1n`.\n * @param y - Value returned when `bit === 0n`.\n * @returns `x` if `bit === 1n`; `y` if `bit === 0n`.\n *\n * @privateRemarks\n * JavaScript BigInt negation of a 1-bit value: `-1n` in BigInt is the\n * two's-complement all-ones pattern (arbitrary precision), which acts as a\n * perfect mask. `-0n === 0n`, so the 0 case also works correctly.\n *\n * @internal\n */\nfunction ctSelect(bit: bigint, x: bigint, y: bigint): bigint {\n const mask = -bit;\n return (x & mask) | (y & ~mask);\n}\n\n/**\n * Decomposes a non-negative `bigint` into the 4-limb little-endian representation\n * used throughout this module.\n *\n * @remarks\n * Extracts four 64-bit windows by successive right-shifts combined with\n * `MASK64`:\n * ```\n * limb0 = value & 0xFFFFFFFFFFFFFFFF (bits 0-63)\n * limb1 = (value >> 64) & 0xFFFFFFFFFFFFFFFF (bits 64-127)\n * limb2 = (value >> 128) & 0xFFFFFFFFFFFFFFFF (bits 128-191)\n * limb3 = (value >> 192) & 0xFFFFFFFFFFFFFFFF (bits 192-255)\n * ```\n *\n * The input must satisfy 0 ≤ value < 2^256. Values in the range [p, 2^256)\n * are representable in limb form but are not canonical field elements;\n * callers are responsible for reducing them if needed.\n *\n * @param value - A non-negative `bigint` in range [0, 2^256 - 1].\n * @returns A 4-element tuple `[limb0, limb1, limb2, limb3]` in little-endian order.\n *\n * @internal\n */\nfunction bigintToLimbs(value: bigint): Curve25519FieldElementLimb {\n return [\n value & MASK64,\n (value >> N64) & MASK64,\n (value >> (N64 * 2n)) & MASK64,\n (value >> (N64 * 3n)) & MASK64,\n ];\n}\n\n/**\n * Reconstructs a `bigint` from the 4-limb little-endian representation.\n *\n * @remarks\n * Computes:\n * ```\n * value = limbs[0]\n * + limbs[1] × 2^64\n * + limbs[2] × 2^128\n * + limbs[3] × 2^192\n * ```\n *\n * This is the inverse of {@link bigintToLimbs}. The reconstructed value lies in\n * [0, 2^256 - 1] (or [0, p-1] if the limbs represent a canonical field element).\n *\n * @param limbs - A 4-element tuple in little-endian order, each limb in [0, 2^64 - 1].\n * @returns The reconstructed `bigint` value.\n *\n * @internal\n */\nfunction limbsToBigint(limbs: Curve25519FieldElementLimb): bigint {\n return limbs[0] + (limbs[1] << N64) + (limbs[2] << (N64 * 2n)) + (limbs[3] << (N64 * 3n));\n}\n\n/**\n * Constant-time modular addition of two field elements, both in 4-limb form.\n *\n * @remarks\n * ## Algorithm\n *\n * **Step 1 — Raw addition with carry propagation:**\n * ```\n * t[i] = a[i] + b[i] + carry_in\n * t_carry = final carry out of limb 3\n * ```\n * The carry is propagated upward through all 4 limbs. After all limbs are\n * processed, `tCarry` is `1n` iff the sum `a + b` exceeded 2^256 - 1.\n *\n * **Step 2 — Trial subtraction:**\n * ```\n * d = t - p (with borrow propagation across 4 limbs)\n * ```\n * After this step, `borrow` is `1n` iff `t < p` (i.e., no reduction needed).\n *\n * **Step 3 — Constant-time selection:**\n * ```\n * useD = tCarry | (1 - borrow)\n * result[i] = ctSelect(useD, d[i], t[i])\n * ```\n * If `tCarry` is 1 (overflow) or if the trial subtraction did not borrow\n * (meaning t ≥ p), use the reduced value `d`. Otherwise use `t`.\n *\n * No `if` statement branches on input-derived data.\n *\n * @param a - Minuend in 4-limb form. Each limb in [0, 2^64 - 1]; value in [0, p-1].\n * @param b - Subtrahend in 4-limb form. Each limb in [0, 2^64 - 1]; value in [0, p-1].\n * @returns The canonical sum `(a + b) mod p` in 4-limb form.\n *\n * @internal\n */\nfunction addModuleLimbs(\n a: Curve25519FieldElementLimb,\n b: Curve25519FieldElementLimb,\n): Curve25519FieldElementLimb {\n // 1. Raw Addition: t = a + b\n const t: bigint[] = [0n, 0n, 0n, 0n];\n let carry = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sum = a[index] + b[index] + carry;\n t[index] = sum & MASK64;\n carry = sum >> N64;\n }\n const tCarry = carry;\n\n // 2. Trial Subtraction: d = t - p\n const d: bigint[] = [0n, 0n, 0n, 0n];\n let borrow = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sub = t[index] - P_LIMBS[index] - borrow;\n d[index] = sub & MASK64;\n borrow = -(sub >> N64);\n }\n\n // 3. Selection: use d if overflow or no borrow\n const useD = tCarry | (1n - borrow);\n\n return [\n ctSelect(useD, d[0], t[0]),\n ctSelect(useD, d[1], t[1]),\n ctSelect(useD, d[2], t[2]),\n ctSelect(useD, d[3], t[3]),\n ];\n}\n\n/**\n * Constant-time modular subtraction of two field elements, both in 4-limb form.\n *\n * @remarks\n * ## Algorithm\n *\n * **Step 1 — Raw subtraction with borrow propagation:**\n * ```\n * out[i] = a[i] - b[i] - borrow_in\n * ```\n * After all 4 limbs, `borrow` is `1n` iff a < b (the difference is negative\n * in ordinary arithmetic and must wrap around modulo p).\n *\n * **Step 2 — Conditional add-back of p:**\n * ```\n * mask = -borrow // all-ones mask if a < b, zero mask otherwise\n * for each limb i:\n * addValue = P_LIMBS[i] & mask // add p iff borrow occurred\n * out[i] = out[i] + addValue + carry\n * ```\n * The mask is derived from the borrow bit without a branch. When borrow = 0\n * the mask is 0 and no correction is applied. When borrow = 1 the mask is\n * all-ones and p is added back.\n *\n * @param a - Minuend in 4-limb form. Value in [0, p-1].\n * @param b - Subtrahend in 4-limb form. Value in [0, p-1].\n * @returns The canonical difference `(a - b) mod p` in 4-limb form.\n *\n * @internal\n */\nfunction subModuleLimbs(\n a: Curve25519FieldElementLimb,\n b: Curve25519FieldElementLimb,\n): Curve25519FieldElementLimb {\n // 1. Calculate diff = a - b\n const out: bigint[] = [0n, 0n, 0n, 0n];\n let borrow = 0n;\n\n for (let index = 0; index < 4; index++) {\n const sub = a[index] - b[index] - borrow;\n out[index] = sub & MASK64;\n borrow = -(sub >> N64);\n }\n\n // 2. If we borrowed, add P back using masking\n const mask = -borrow;\n let carry = 0n;\n\n for (let index = 0; index < 4; index++) {\n const addValue = P_LIMBS[index] & mask;\n\n const sum = out[index] + addValue + carry;\n out[index] = sum & MASK64;\n carry = sum >> N64;\n }\n\n return [out[0], out[1], out[2], out[3]];\n}\n\n/**\n * Modular multiplication of two field elements in 4-limb form, returning the\n * product reduced modulo p.\n *\n * @remarks\n * ## Algorithm\n *\n * Converts both limb arrays back to full-precision `BigInt` values, performs\n * native `BigInt` multiplication to obtain a ≤ 510-bit intermediate product,\n * and reduces by `% CURVE25519_FIELD_PRIME`.\n *\n * ```\n * product = limbsToBigint(a) * limbsToBigint(b) (up to 510 bits)\n * reduced = product % p\n * return bigintToLimbs(reduced)\n * ```\n *\n * ## Why Not Schoolbook Limb Multiplication?\n *\n * A true 4×4 schoolbook multiplication would produce an 8-limb (512-bit)\n * intermediate and require a multi-step reduction using the structure of p.\n * JavaScript's `BigInt` already implements this internally, and the V8 engine\n * performs the reduction in native code. This approach is simpler and has\n * predictable worst-case cost.\n *\n * ## Why Not Montgomery Form?\n *\n * Montgomery multiplication eliminates the per-call division at the cost of\n * converting inputs into and out of Montgomery domain. That conversion\n * overhead is only amortized when the same operands participate in many\n * multiplications (e.g., long scalar multiplication chains). For the Rescue\n * cipher's relatively short permutation rounds, the conversion cost is not\n * justified.\n *\n * @param a - First factor in 4-limb form. Value in [0, p-1].\n * @param b - Second factor in 4-limb form. Value in [0, p-1].\n * @returns The canonical product `(a × b) mod p` in 4-limb form.\n *\n * @internal\n */\nfunction mulModuleLimbs(\n a: Curve25519FieldElementLimb,\n b: Curve25519FieldElementLimb,\n): Curve25519FieldElementLimb {\n // For Curve25519, we use direct multiplication and reduction\n // This is simpler than Montgomery for this specific prime\n const aBig = limbsToBigint(a);\n const bBig = limbsToBigint(b);\n const product = (aBig * bBig) % CURVE25519_FIELD_PRIME;\n return bigintToLimbs(product);\n}\n\n/**\n * Modular exponentiation of a field element by an arbitrary non-negative\n * exponent, using binary square-and-multiply.\n *\n * @remarks\n * ## Algorithm — Binary Exponentiation\n *\n * Starting from `result = 1` (the multiplicative identity in limb form):\n * ```\n * current = base\n * while exp > 0:\n * if (exp & 1) == 1:\n * result = result × current (mod p)\n * current = current × current (mod p)\n * exp >>= 1\n * return result\n * ```\n *\n * The branch `if (exp & 1) == 1` tests a bit of the **exponent**, not a\n * secret field value. When the exponent is a fixed protocol constant (e.g.,\n * p - 2 for inversion) this does not leak secret data; when the exponent is\n * secret (e.g., a private scalar), a constant-time double-and-add should be\n * used instead.\n *\n * ## Cost\n *\n * For an n-bit exponent: at most n squarings and at most n multiplications\n * (≈ n/2 on average). For the full range [0, p-1] this is ≈ 255 squarings\n * and ≈ 128 multiplications.\n *\n * @param base - Base field element in 4-limb form. Value in [0, p-1].\n * @param exp - Non-negative exponent as a plain `bigint`.\n * @returns `base^exp mod p` in 4-limb form.\n *\n * @internal\n */\nfunction moduleExpLimbs(base: Curve25519FieldElementLimb, exp: bigint): Curve25519FieldElementLimb {\n let result: Curve25519FieldElementLimb = [1n, 0n, 0n, 0n];\n let current = base;\n\n while (exp > 0n) {\n if ((exp & 1n) === 1n) {\n result = mulModuleLimbs(result, current);\n }\n current = mulModuleLimbs(current, current);\n exp >>= 1n;\n }\n\n return result;\n}\n\n// =============================================================================\n// Exported Functions\n// =============================================================================\n\n/**\n * Constant-operation-count modular addition for the Curve25519 base field.\n *\n * @remarks\n * Computes the canonical field sum:\n * ```\n * result ≡ a + b (mod p), p = 2^255 - 19\n * ```\n *\n * Implementation delegates to {@link addModuleLimbs} which performs the\n * addition and conditional reduction entirely with bitwise masking — no\n * data-dependent branches on `a` or `b`.\n *\n * This function satisfies {@link Curve25519ModuloAddFunction}.\n *\n * @param a - First field element. Must be in canonical range [0, p-1].\n * @param b - Second field element. Must be in canonical range [0, p-1].\n * @returns `(a + b) mod p` in canonical range [0, p-1].\n *\n * @example\n * ```typescript\n * import { curve25519ModuloAdd, CURVE25519_FIELD_PRIME } from \"@umbra-privacy/sdk\";\n *\n * // Basic addition\n * const sum = curve25519ModuloAdd(10n, 20n);\n * console.log(sum); // 30n\n *\n * // Wrap-around: p-1 + 1 = 0\n * const wrap = curve25519ModuloAdd(CURVE25519_FIELD_PRIME - 1n, 1n);\n * console.log(wrap); // 0n\n * ```\n *\n * @see {@link curve25519ModuloSub} — complementary subtraction\n * @see {@link getCurve25519ModularAddFunction} — returns a cached reference to this function\n *\n * @public\n */\nexport const curve25519ModuloAdd: Curve25519ModuleAddFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n const resultLimbs = addModuleLimbs(aLimbs, bLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Constant-operation-count modular subtraction for the Curve25519 base field.\n *\n * @remarks\n * Computes the canonical field difference:\n * ```\n * result ≡ a - b (mod p), p = 2^255 - 19\n * ```\n *\n * When a < b the result wraps around: `a - b + p`, which is still in [0, p-1].\n * Implementation delegates to {@link subModuleLimbs}, which adds p back via\n * a borrow-derived bitmask rather than a conditional branch.\n *\n * This function satisfies {@link Curve25519ModuloSubFunction}.\n *\n * @param a - Minuend. Must be in canonical range [0, p-1].\n * @param b - Subtrahend. Must be in canonical range [0, p-1].\n * @returns `(a - b) mod p` in canonical range [0, p-1].\n *\n * @example\n * ```typescript\n * import { curve25519ModuloSub, CURVE25519_FIELD_PRIME } from \"@umbra-privacy/sdk\";\n *\n * // Normal subtraction\n * const diff = curve25519ModuloSub(30n, 10n);\n * console.log(diff); // 20n\n *\n * // Wrap-around: 0 - 1 = p - 1\n * const wrap = curve25519ModuloSub(0n, 1n);\n * console.log(wrap === CURVE25519_FIELD_PRIME - 1n); // true\n * ```\n *\n * @see {@link curve25519ModuloAdd} — complementary addition\n * @see {@link getCurve25519ModularSubFunction} — returns a cached reference to this function\n *\n * @public\n */\nexport const curve25519ModuloSub: Curve25519ModuleSubFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n const resultLimbs = subModuleLimbs(aLimbs, bLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Modular multiplication for the Curve25519 base field.\n *\n * @remarks\n * Computes the canonical field product:\n * ```\n * result ≡ a × b (mod p), p = 2^255 - 19\n * ```\n *\n * Implementation converts both operands to full-precision `BigInt`, multiplies\n * natively (producing a ≤ 510-bit intermediate), then reduces with `% p`.\n * See {@link mulModuleLimbs} for rationale on why Montgomery form is not used.\n *\n * This function satisfies {@link Curve25519ModuloMulFunction}.\n *\n * @param a - First factor. Must be in canonical range [0, p-1].\n * @param b - Second factor. Must be in canonical range [0, p-1].\n * @returns `(a × b) mod p` in canonical range [0, p-1].\n *\n * @example\n * ```typescript\n * import { curve25519ModuloMul, CURVE25519_FIELD_PRIME } from \"@umbra-privacy/sdk\";\n *\n * // Basic multiplication\n * const product = curve25519ModuloMul(7n, 8n);\n * console.log(product); // 56n\n *\n * // Large value reduces modulo p\n * const large = curve25519ModuloMul(CURVE25519_FIELD_PRIME - 1n, 2n);\n * // (p-1) × 2 = 2p - 2 ≡ p - 2 (mod p)\n * console.log(large === CURVE25519_FIELD_PRIME - 2n); // true\n * ```\n *\n * @see {@link curve25519ModuloInv} — uses this function for inversion via Fermat's theorem\n * @see {@link getCurve25519ModularMulFunction} — returns a cached reference to this function\n *\n * @public\n */\nexport const curve25519ModuloMul: Curve25519ModuleMulFunction = (a: bigint, b: bigint): bigint => {\n const aLimbs = bigintToLimbs(a);\n const bLimbs = bigintToLimbs(b);\n const resultLimbs = mulModuleLimbs(aLimbs, bLimbs);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Modular multiplicative inverse for the Curve25519 base field.\n *\n * @remarks\n * Computes the unique inverse such that:\n * ```\n * a × result ≡ 1 (mod p), p = 2^255 - 19\n * ```\n *\n * ## Algorithm — Fermat's Little Theorem\n *\n * Because p is prime, Fermat's Little Theorem guarantees:\n * ```\n * a^(p-1) ≡ 1 (mod p) for all a ≠ 0\n * ```\n * Therefore:\n * ```\n * a^(-1) ≡ a^(p-2) (mod p)\n * ```\n *\n * The exponent p - 2 is a fixed protocol constant, so the square-and-multiply\n * loop in {@link moduleExpLimbs} does not branch on secret data.\n *\n * **Cost**: ≈ 255 squarings + ≈ 128 multiplications. For applications that call\n * inversion in a tight loop, a batch-inversion algorithm (Montgomery's trick)\n * can reduce the cost to 1 inversion + 3(n-1) multiplications for n elements.\n *\n * This function satisfies {@link Curve25519ModuloInvFunction}.\n *\n * @param a - The field element to invert. Must be in range [1, p-1].\n * Passing `0n` is a programming error — zero has no multiplicative inverse.\n * @returns The unique inverse `a^(-1) mod p` in range [1, p-1].\n * @throws {Error} If `a === 0n`. The error message is\n * `\"Cannot compute modular inverse of zero\"`.\n *\n * @example\n * ```typescript\n * import { curve25519ModuloInv, curve25519ModuloMul } from \"@umbra-privacy/sdk\";\n *\n * const a = 7n;\n * const invA = curve25519ModuloInv(a);\n *\n * // Verification: a × a^{-1} ≡ 1 (mod p)\n * const product = curve25519ModuloMul(a, invA);\n * console.log(product === 1n); // true\n *\n * // Throws for zero\n * try {\n * curve25519ModuloInv(0n);\n * } catch (e) {\n * console.log((e as Error).message); // \"Cannot compute modular inverse of zero\"\n * }\n * ```\n *\n * @see {@link curve25519ModuloPow} — the underlying exponentiation used internally\n * @see {@link getCurve25519ModularInvFunction} — returns a cached reference to this function\n *\n * @public\n */\nexport const curve25519ModuloInv: Curve25519ModuleInvFunction = (a: bigint): bigint => {\n if (a === 0n) {\n throw new Error(\"Cannot compute modular inverse of zero\");\n }\n\n const aLimbs = bigintToLimbs(a);\n const exp = CURVE25519_FIELD_PRIME - 2n;\n const resultLimbs = moduleExpLimbs(aLimbs, exp);\n return limbsToBigint(resultLimbs);\n};\n\n/**\n * Modular exponentiation for the Curve25519 base field.\n *\n * @remarks\n * Computes the field power:\n * ```\n * result ≡ base^exp (mod p), p = 2^255 - 19\n * ```\n *\n * Uses binary (square-and-multiply) exponentiation via {@link moduleExpLimbs}.\n * The special case `exp === 0n` is handled explicitly: `base^0 = 1` for all\n * `base`, including `base = 0`.\n *\n * This function satisfies {@link Curve25519ModuloPowFunction}.\n *\n * @param base - The base. Must be in canonical range [0, p-1].\n * @param exp - A non-negative `bigint` exponent.\n * @returns `base^exp mod p` in canonical range [0, p-1].\n *\n * @example\n * ```typescript\n * import { curve25519ModuloPow, CURVE25519_FIELD_PRIME } from \"@umbra-privacy/sdk\";\n *\n * // Small exponent\n * const r1 = curve25519ModuloPow(2n, 10n);\n * console.log(r1); // 1024n\n *\n * // Zero exponent: always 1\n * const r2 = curve25519ModuloPow(12345n, 0n);\n * console.log(r2); // 1n\n *\n * // Fermat's Little Theorem: a^(p-1) ≡ 1 for a ≠ 0\n * const r3 = curve25519ModuloPow(42n, CURVE25519_FIELD_PRIME - 1n);\n * console.log(r3); // 1n\n * ```\n *\n * @see {@link curve25519ModuloInv} — uses this with exponent p-2\n * @see {@link getCurve25519ModularPowFunction} — returns a cached reference to this function\n *\n * @public\n */\nexport const curve25519ModuloPow: Curve25519ModulePowFunction = (\n base: bigint,\n exp: bigint,\n): bigint => {\n if (exp === 0n) {\n return 1n;\n }\n\n const baseLimbs = bigintToLimbs(base);\n const resultLimbs = moduleExpLimbs(baseLimbs, exp);\n return limbsToBigint(resultLimbs);\n};\n\n// =============================================================================\n// Cached Getter Functions\n// =============================================================================\n\n/**\n * Lazy-initialised cache slot for the modular addition function.\n *\n * @remarks\n * Set to `null` on module load; populated on the first call to\n * `getCurve25519ModularAddFunction`. The nullish-coalescing assignment\n * (`??=`) ensures the function reference is written exactly once per\n * module lifetime, making the getter safe to call from multiple\n * concurrent contexts in a single-threaded environment.\n *\n * @internal\n */\nlet cachedModuleAddFunction: Curve25519ModuleAddFunction | null = null;\n\n/**\n * Lazy-initialised cache slot for the modular subtraction function.\n * @internal\n */\nlet cachedModuleSubFunction: Curve25519ModuleSubFunction | null = null;\n\n/**\n * Lazy-initialised cache slot for the modular multiplication function.\n * @internal\n */\nlet cachedModuleMulFunction: Curve25519ModuleMulFunction | null = null;\n\n/**\n * Lazy-initialised cache slot for the modular inverse function.\n * @internal\n */\nlet cachedModuleInvFunction: Curve25519ModuleInvFunction | null = null;\n\n/**\n * Lazy-initialised cache slot for the modular exponentiation function.\n * @internal\n */\nlet cachedModulePowFunction: Curve25519ModulePowFunction | null = null;\n\n/**\n * Returns a lazily cached reference to the Curve25519 modular addition function.\n *\n * @remarks\n * On the first call, stores `curve25519ModuloAdd` in the module-level cache\n * variable and returns it. Subsequent calls return the cached reference\n * without re-assignment. This pattern avoids redundant function object\n * allocation when the getter is called in a hot path.\n *\n * The returned function is identical to calling {@link curve25519ModuloAdd}\n * directly; the getter is provided for dependency-injection consumers that\n * accept a `Curve25519ModuloAddFunction` from a provider rather than\n * importing the concrete implementation.\n *\n * @returns The singleton `curve25519ModuloAdd` function.\n *\n * @example\n * ```typescript\n * import { getCurve25519ModularAddFunction } from \"@umbra-privacy/sdk\";\n *\n * const modAdd = getCurve25519ModularAddFunction();\n * const sum = modAdd(10n, 20n); // 30n\n * ```\n *\n * @see {@link curve25519ModuloAdd} — the underlying constant-time implementation\n *\n * @public\n */\nexport function getCurve25519ModularAddFunction(): Curve25519ModuleAddFunction {\n cachedModuleAddFunction ??= curve25519ModuloAdd;\n return cachedModuleAddFunction;\n}\n\n/**\n * Returns a lazily cached reference to the Curve25519 modular subtraction function.\n *\n * @remarks\n * Follows the same lazy-caching pattern as {@link getCurve25519ModularAddFunction}.\n * The returned function is identical to calling {@link curve25519ModuloSub} directly.\n *\n * @returns The singleton `curve25519ModuloSub` function.\n *\n * @example\n * ```typescript\n * import { getCurve25519ModularSubFunction } from \"@umbra-privacy/sdk\";\n *\n * const modSub = getCurve25519ModularSubFunction();\n * const diff = modSub(30n, 10n); // 20n\n * ```\n *\n * @see {@link curve25519ModuloSub} — the underlying constant-time implementation\n *\n * @public\n */\nexport function getCurve25519ModularSubFunction(): Curve25519ModuleSubFunction {\n cachedModuleSubFunction ??= curve25519ModuloSub;\n return cachedModuleSubFunction;\n}\n\n/**\n * Returns a lazily cached reference to the Curve25519 modular multiplication function.\n *\n * @remarks\n * Follows the same lazy-caching pattern as {@link getCurve25519ModularAddFunction}.\n * The returned function is identical to calling {@link curve25519ModuloMul} directly.\n *\n * @returns The singleton `curve25519ModuloMul` function.\n *\n * @example\n * ```typescript\n * import { getCurve25519ModularMulFunction } from \"@umbra-privacy/sdk\";\n *\n * const modMul = getCurve25519ModularMulFunction();\n * const product = modMul(7n, 8n); // 56n\n * ```\n *\n * @see {@link curve25519ModuloMul} — the underlying implementation\n *\n * @public\n */\nexport function getCurve25519ModularMulFunction(): Curve25519ModuleMulFunction {\n cachedModuleMulFunction ??= curve25519ModuloMul;\n return cachedModuleMulFunction;\n}\n\n/**\n * Returns a lazily cached reference to the Curve25519 modular inverse function.\n *\n * @remarks\n * Follows the same lazy-caching pattern as {@link getCurve25519ModularAddFunction}.\n * The returned function is identical to calling {@link curve25519ModuloInv} directly.\n *\n * @returns The singleton `curve25519ModuloInv` function.\n *\n * @example\n * ```typescript\n * import { getCurve25519ModularInvFunction } from \"@umbra-privacy/sdk\";\n *\n * const modInv = getCurve25519ModularInvFunction();\n * const inverse = modInv(7n);\n * // modInv(7n) * 7n ≡ 1 (mod p)\n * ```\n *\n * @see {@link curve25519ModuloInv} — the underlying Fermat's theorem implementation\n *\n * @public\n */\nexport function getCurve25519ModularInvFunction(): Curve25519ModuleInvFunction {\n cachedModuleInvFunction ??= curve25519ModuloInv;\n return cachedModuleInvFunction;\n}\n\n/**\n * Returns a lazily cached reference to the Curve25519 modular exponentiation function.\n *\n * @remarks\n * Follows the same lazy-caching pattern as {@link getCurve25519ModularAddFunction}.\n * The returned function is identical to calling {@link curve25519ModuloPow} directly.\n *\n * @returns The singleton `curve25519ModuloPow` function.\n *\n * @example\n * ```typescript\n * import { getCurve25519ModularPowFunction } from \"@umbra-privacy/sdk\";\n *\n * const modPow = getCurve25519ModularPowFunction();\n * const result = modPow(2n, 10n); // 1024n\n * ```\n *\n * @see {@link curve25519ModuloPow} — the underlying square-and-multiply implementation\n *\n * @public\n */\nexport function getCurve25519ModularPowFunction(): Curve25519ModulePowFunction {\n cachedModulePowFunction ??= curve25519ModuloPow;\n return cachedModulePowFunction;\n}\n\n// =============================================================================\n// U512-Based Field Element Sampler\n// =============================================================================\n\n/**\n * The Montgomery constant R = 2^256 mod p for the Curve25519 field.\n *\n * @remarks\n * Used in the U512-based sampler to combine the high and low 256-bit halves\n * of a 512-bit input into a single field element:\n * ```\n * result = (high × R + low) mod p\n * ```\n *\n * ## Derivation\n *\n * ```\n * 2^256 = 2 × 2^255\n * = 2 × (p + 19) (since p = 2^255 - 19)\n * = 2p + 38\n * ∴ 2^256 mod p = 38\n * ```\n *\n * The small value of R (just 38) means the multiplication `high × R` can be\n * computed cheaply: it is equivalent to `high × 38`, well within the range\n * of a single BigInt multiply-and-reduce.\n *\n * @internal\n */\nconst R_MOD_P_CURVE25519 = 38n;\n\n/**\n * Reduces a 256-bit value into the canonical Curve25519 field range [0, p)\n * using constant-time trial subtraction.\n *\n * @remarks\n * ## Algorithm\n *\n * Computes `d = value - p` using 4-limb borrow propagation. If the final\n * borrow is 1, then value < p and the original value should be returned;\n * otherwise d is in [0, p) and should be returned. Selection between `value`\n * and `d` is performed with {@link ctSelect} — no branch on the borrow bit.\n *\n * This function handles exactly one conditional subtraction, which is correct\n * because the input is guaranteed to be in [0, 2^256). Any value in\n * [p, 2^256) satisfies p ≤ value < 2p (since p > 2^254), so a single\n * subtraction of p suffices.\n *\n * @param value - A non-negative `bigint` in [0, 2^256 - 1]. Values already\n * in [0, p) are returned unchanged. Values in [p, 2^256) are reduced by p.\n * @returns The equivalent element in the canonical range [0, p-1].\n *\n * @internal\n */\nfunction reduce256Curve25519(value: bigint): bigint {\n const [l0, l1, l2, l3] = bigintToLimbs(value);\n const [p0, p1, p2, p3] = P_LIMBS;\n\n // Trial subtraction: d = value - p\n // Compute d0\n const sub0 = l0 - p0;\n const d0 = sub0 & MASK64;\n const borrow0 = -(sub0 >> N64) & 1n;\n\n // Compute d1\n const sub1 = l1 - p1 - borrow0;\n const d1 = sub1 & MASK64;\n const borrow1 = -(sub1 >> N64) & 1n;\n\n // Compute d2\n const sub2 = l2 - p2 - borrow1;\n const d2 = sub2 & MASK64;\n const borrow2 = -(sub2 >> N64) & 1n;\n\n // Compute d3\n const sub3 = l3 - p3 - borrow2;\n const d3 = sub3 & MASK64;\n const borrow3 = -(sub3 >> N64) & 1n;\n\n // If borrow3 is 0, value >= p, so use d (the subtracted value)\n // If borrow3 is 1, value < p, so use original value\n const useOriginal = borrow3;\n\n return limbsToBigint([\n ctSelect(useOriginal, l0, d0),\n ctSelect(useOriginal, l1, d1),\n ctSelect(useOriginal, l2, d2),\n ctSelect(useOriginal, l3, d3),\n ]);\n}\n\n/**\n * Decodes 32 bytes from a big-endian byte array starting at `offset` into a\n * `bigint`, using the SDK's typed `U256BeBytes` converter pipeline.\n *\n * @remarks\n * Steps:\n * 1. Slice `bytes[offset .. offset+32]` (32 bytes = 256 bits).\n * 2. Wrap the slice in a `U256BeBytes` branded type via `createU256BeBytes`.\n * 3. Decode the branded bytes to a `bigint` via `decodeU256BeBytesToU256`.\n *\n * The resulting `bigint` is in the range [0, 2^256 - 1]. It may be ≥ p;\n * callers are responsible for reducing it if needed (e.g., via\n * {@link reduce256Curve25519}).\n *\n * @param bytes - The source byte array (must be at least `offset + 32` bytes long).\n * @param offset - Byte index at which to start reading the 32-byte window.\n * @returns The big-endian decoded `bigint` for bytes `[offset, offset+32)`.\n *\n * @internal\n */\nfunction bytesToBigintBECurve25519(bytes: Uint8Array, offset: number): bigint {\n const slice = bytes.slice(offset, offset + U256_BYTE_LENGTH);\n const u256BeBytes = createU256BeBytes(slice);\n return decodeU256BeBytesToU256(u256BeBytes);\n}\n\n/**\n * Factory that creates a sampler converting 512-bit big-endian byte arrays to\n * uniformly distributed Curve25519 field elements.\n *\n * @remarks\n * ## Purpose\n *\n * Hash-to-field algorithms produce 512-bit outputs to avoid statistical bias\n * when mapping into the 255-bit field. This factory encapsulates the standard\n * two-half combination technique (see below), returning a closure that can be\n * used repeatedly.\n *\n * ## Algorithm\n *\n * Given a 64-byte big-endian input array:\n *\n * 1. **Split** into two 256-bit halves:\n * - `high = input[0..31]` (most significant)\n * - `low = input[32..63]` (least significant)\n *\n * 2. **Reduce** each half into [0, p) via constant-time trial subtraction\n * (`reduce256Curve25519`).\n *\n * 3. **Combine** using the precomputed constant R = 2^256 mod p = 38:\n * ```\n * result = (highReduced × R + lowReduced) mod p\n * ```\n *\n * ## Customization via `deps`\n *\n * The `modAdd` and `modMul` slots in `deps` allow replacing the default\n * constant-time implementations with alternatives. Common use cases:\n * - Inject test stubs to exercise the combination logic in isolation.\n * - Use a faster non-constant-time implementation for offline tooling.\n *\n * ## Uniformity\n *\n * The bias of the result is bounded by p / 2^512 < 2^-257, which is\n * negligible for all practical cryptographic purposes.\n *\n * @param deps - Optional overrides for modular arithmetic. If omitted, uses\n * the default constant-time SDK implementations.\n * @returns A closure `(input: U512BeBytes) => Curve25519FieldElement`.\n *\n * @example\n * ```typescript\n * import { getCurve25519FieldElementSampler } from \"@umbra-privacy/sdk\";\n *\n * // Default: uses SDK constant-time arithmetic\n * const sampler = getCurve25519FieldElementSampler();\n *\n * const input = crypto.getRandomValues(new Uint8Array(64)) as U512BeBytes;\n * const element = sampler(input);\n * // element is a valid Curve25519FieldElement in [0, p-1]\n *\n * // With custom multiplication for testing\n * const testSampler = getCurve25519FieldElementSampler({\n * modMul: (a, b) => (a * b) % ((1n << 255n) - 19n),\n * });\n * ```\n *\n * @see {@link curve25519FieldElementSampler} — pre-built default instance\n * @see {@link U512BasedCurve25519FieldElementSamplerDeps} — the dependency injection bag\n * @see {@link U512BasedCurve25519FieldElementSamplerFunction} — the returned function's type\n *\n * @public\n */\nexport function getCurve25519FieldElementSampler(\n deps?: U512BasedCurve25519FieldElementSamplerDeps,\n): U512BasedCurve25519FieldElementSamplerFunction {\n // Use provided functions or fall back to defaults\n const { modAdd: moduleAdd = curve25519ModuloAdd, modMul: moduleMul = curve25519ModuloMul } =\n deps ?? {};\n\n return (input: U512BeBytes): Curve25519FieldElement => {\n // Extract high and low 256-bit halves (big-endian)\n // bytes 0-31 = high (most significant)\n // bytes 32-63 = low (least significant)\n const high = bytesToBigintBECurve25519(input, 0); // bytes 0-31\n const low = bytesToBigintBECurve25519(input, 32); // bytes 32-63\n\n // Reduce both halves to [0, p)\n // This is necessary because 256-bit values can be >= p\n const lowReduced = reduce256Curve25519(low);\n const highReduced = reduce256Curve25519(high);\n\n // Compute: result = (high × R + low) mod p\n // where R = 2^256 mod p = 38 for Curve25519\n const highTimesR = moduleMul(highReduced, R_MOD_P_CURVE25519);\n const result = moduleAdd(highTimesR, lowReduced);\n\n return result as Curve25519FieldElement;\n };\n}\n\n/**\n * Pre-instantiated U512-to-field-element sampler using the default\n * constant-time Curve25519 field arithmetic.\n *\n * @remarks\n * This is a convenience export for callers that do not need to inject custom\n * arithmetic. It is equivalent to calling:\n * ```typescript\n * getCurve25519FieldElementSampler()\n * ```\n * but avoids the factory call overhead for the common case.\n *\n * ## Typical Usage Pattern\n *\n * Hash-to-field: pass the 512-bit output of a wide hash (SHA-512, BLAKE2b-512,\n * HKDF output, etc.) directly to this sampler to obtain a uniformly distributed\n * field element:\n * ```\n * fieldElement = sampler(sha512(domainSeparator || message))\n * ```\n *\n * This pattern is used internally in the Umbra SDK wherever a scalar must be\n * derived deterministically from a secret without bias.\n *\n * @param input - A 64-byte big-endian byte array (`U512BeBytes`).\n * @returns A `Curve25519FieldElement` in the canonical range [0, p-1].\n *\n * @example\n * ```typescript\n * import { curve25519FieldElementSampler } from \"@umbra-privacy/sdk\";\n *\n * // All-zero input → deterministic result (== 0n)\n * const zeroInput = new Uint8Array(64) as U512BeBytes;\n * const element = curve25519FieldElementSampler(zeroInput);\n * console.log(element); // 0n\n *\n * // Random 64-byte input from a CSPRNG\n * const randomInput = crypto.getRandomValues(new Uint8Array(64)) as U512BeBytes;\n * const randomElement = curve25519FieldElementSampler(randomInput);\n * // randomElement is uniformly distributed in [0, p-1]\n * ```\n *\n * @see {@link getCurve25519FieldElementSampler} — factory for custom arithmetic\n * @see {@link U512BasedCurve25519FieldElementSamplerFunction} — the function type\n *\n * @public\n */\nexport const curve25519FieldElementSampler: U512BasedCurve25519FieldElementSamplerFunction =\n getCurve25519FieldElementSampler();\n"]}