Math.sol 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
  3. pragma solidity ^0.8.20;
  4. import {Panic} from "../Panic.sol";
  5. import {SafeCast} from "./SafeCast.sol";
  6. /**
  7. * @dev Standard math utilities missing in the Solidity language.
  8. */
  9. library Math {
  10. enum Rounding {
  11. Floor, // Toward negative infinity
  12. Ceil, // Toward positive infinity
  13. Trunc, // Toward zero
  14. Expand // Away from zero
  15. }
  16. /**
  17. * @dev Return the 512-bit addition of two uint256.
  18. *
  19. * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
  20. */
  21. function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
  22. assembly ("memory-safe") {
  23. low := add(a, b)
  24. high := lt(low, a)
  25. }
  26. }
  27. /**
  28. * @dev Return the 512-bit multiplication of two uint256.
  29. *
  30. * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
  31. */
  32. function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
  33. // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
  34. // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
  35. // variables such that product = high * 2²⁵⁶ + low.
  36. assembly ("memory-safe") {
  37. let mm := mulmod(a, b, not(0))
  38. low := mul(a, b)
  39. high := sub(sub(mm, low), lt(mm, low))
  40. }
  41. }
  42. /**
  43. * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
  44. */
  45. function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
  46. unchecked {
  47. uint256 c = a + b;
  48. success = c >= a;
  49. result = c * SafeCast.toUint(success);
  50. }
  51. }
  52. /**
  53. * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
  54. */
  55. function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
  56. unchecked {
  57. uint256 c = a - b;
  58. success = c <= a;
  59. result = c * SafeCast.toUint(success);
  60. }
  61. }
  62. /**
  63. * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
  64. */
  65. function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
  66. unchecked {
  67. uint256 c = a * b;
  68. assembly ("memory-safe") {
  69. // Only true when the multiplication doesn't overflow
  70. // (c / a == b) || (a == 0)
  71. success := or(eq(div(c, a), b), iszero(a))
  72. }
  73. // equivalent to: success ? c : 0
  74. result = c * SafeCast.toUint(success);
  75. }
  76. }
  77. /**
  78. * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
  79. */
  80. function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
  81. unchecked {
  82. success = b > 0;
  83. assembly ("memory-safe") {
  84. // The `DIV` opcode returns zero when the denominator is 0.
  85. result := div(a, b)
  86. }
  87. }
  88. }
  89. /**
  90. * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
  91. */
  92. function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
  93. unchecked {
  94. success = b > 0;
  95. assembly ("memory-safe") {
  96. // The `MOD` opcode returns zero when the denominator is 0.
  97. result := mod(a, b)
  98. }
  99. }
  100. }
  101. /**
  102. * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
  103. */
  104. function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
  105. (bool success, uint256 result) = tryAdd(a, b);
  106. return ternary(success, result, type(uint256).max);
  107. }
  108. /**
  109. * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
  110. */
  111. function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
  112. (, uint256 result) = trySub(a, b);
  113. return result;
  114. }
  115. /**
  116. * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
  117. */
  118. function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
  119. (bool success, uint256 result) = tryMul(a, b);
  120. return ternary(success, result, type(uint256).max);
  121. }
  122. /**
  123. * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
  124. *
  125. * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
  126. * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
  127. * one branch when needed, making this function more expensive.
  128. */
  129. function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
  130. unchecked {
  131. // branchless ternary works because:
  132. // b ^ (a ^ b) == a
  133. // b ^ 0 == b
  134. return b ^ ((a ^ b) * SafeCast.toUint(condition));
  135. }
  136. }
  137. /**
  138. * @dev Returns the largest of two numbers.
  139. */
  140. function max(uint256 a, uint256 b) internal pure returns (uint256) {
  141. return ternary(a > b, a, b);
  142. }
  143. /**
  144. * @dev Returns the smallest of two numbers.
  145. */
  146. function min(uint256 a, uint256 b) internal pure returns (uint256) {
  147. return ternary(a < b, a, b);
  148. }
  149. /**
  150. * @dev Returns the average of two numbers. The result is rounded towards
  151. * zero.
  152. */
  153. function average(uint256 a, uint256 b) internal pure returns (uint256) {
  154. // (a + b) / 2 can overflow.
  155. return (a & b) + (a ^ b) / 2;
  156. }
  157. /**
  158. * @dev Returns the ceiling of the division of two numbers.
  159. *
  160. * This differs from standard division with `/` in that it rounds towards infinity instead
  161. * of rounding towards zero.
  162. */
  163. function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
  164. if (b == 0) {
  165. // Guarantee the same behavior as in a regular Solidity division.
  166. Panic.panic(Panic.DIVISION_BY_ZERO);
  167. }
  168. // The following calculation ensures accurate ceiling division without overflow.
  169. // Since a is non-zero, (a - 1) / b will not overflow.
  170. // The largest possible result occurs when (a - 1) / b is type(uint256).max,
  171. // but the largest value we can obtain is type(uint256).max - 1, which happens
  172. // when a = type(uint256).max and b = 1.
  173. unchecked {
  174. return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
  175. }
  176. }
  177. /**
  178. * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
  179. * denominator == 0.
  180. *
  181. * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
  182. * Uniswap Labs also under MIT license.
  183. */
  184. function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
  185. unchecked {
  186. (uint256 high, uint256 low) = mul512(x, y);
  187. // Handle non-overflow cases, 256 by 256 division.
  188. if (high == 0) {
  189. // Solidity will revert if denominator == 0, unlike the div opcode on its own.
  190. // The surrounding unchecked block does not change this fact.
  191. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
  192. return low / denominator;
  193. }
  194. // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
  195. if (denominator <= high) {
  196. Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
  197. }
  198. ///////////////////////////////////////////////
  199. // 512 by 256 division.
  200. ///////////////////////////////////////////////
  201. // Make division exact by subtracting the remainder from [high low].
  202. uint256 remainder;
  203. assembly ("memory-safe") {
  204. // Compute remainder using mulmod.
  205. remainder := mulmod(x, y, denominator)
  206. // Subtract 256 bit number from 512 bit number.
  207. high := sub(high, gt(remainder, low))
  208. low := sub(low, remainder)
  209. }
  210. // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
  211. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
  212. uint256 twos = denominator & (0 - denominator);
  213. assembly ("memory-safe") {
  214. // Divide denominator by twos.
  215. denominator := div(denominator, twos)
  216. // Divide [high low] by twos.
  217. low := div(low, twos)
  218. // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
  219. twos := add(div(sub(0, twos), twos), 1)
  220. }
  221. // Shift in bits from high into low.
  222. low |= high * twos;
  223. // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
  224. // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
  225. // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
  226. uint256 inverse = (3 * denominator) ^ 2;
  227. // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
  228. // works in modular arithmetic, doubling the correct bits in each step.
  229. inverse *= 2 - denominator * inverse; // inverse mod 2⁸
  230. inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
  231. inverse *= 2 - denominator * inverse; // inverse mod 2³²
  232. inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
  233. inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
  234. inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
  235. // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
  236. // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
  237. // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
  238. // is no longer required.
  239. result = low * inverse;
  240. return result;
  241. }
  242. }
  243. /**
  244. * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
  245. */
  246. function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
  247. return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
  248. }
  249. /**
  250. * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
  251. */
  252. function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
  253. unchecked {
  254. (uint256 high, uint256 low) = mul512(x, y);
  255. if (high >= 1 << n) {
  256. Panic.panic(Panic.UNDER_OVERFLOW);
  257. }
  258. return (high << (256 - n)) | (low >> n);
  259. }
  260. }
  261. /**
  262. * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
  263. */
  264. function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
  265. return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
  266. }
  267. /**
  268. * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
  269. *
  270. * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
  271. * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
  272. *
  273. * If the input value is not inversible, 0 is returned.
  274. *
  275. * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
  276. * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
  277. */
  278. function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
  279. unchecked {
  280. if (n == 0) return 0;
  281. // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
  282. // Used to compute integers x and y such that: ax + ny = gcd(a, n).
  283. // When the gcd is 1, then the inverse of a modulo n exists and it's x.
  284. // ax + ny = 1
  285. // ax = 1 + (-y)n
  286. // ax ≡ 1 (mod n) # x is the inverse of a modulo n
  287. // If the remainder is 0 the gcd is n right away.
  288. uint256 remainder = a % n;
  289. uint256 gcd = n;
  290. // Therefore the initial coefficients are:
  291. // ax + ny = gcd(a, n) = n
  292. // 0a + 1n = n
  293. int256 x = 0;
  294. int256 y = 1;
  295. while (remainder != 0) {
  296. uint256 quotient = gcd / remainder;
  297. (gcd, remainder) = (
  298. // The old remainder is the next gcd to try.
  299. remainder,
  300. // Compute the next remainder.
  301. // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
  302. // where gcd is at most n (capped to type(uint256).max)
  303. gcd - remainder * quotient
  304. );
  305. (x, y) = (
  306. // Increment the coefficient of a.
  307. y,
  308. // Decrement the coefficient of n.
  309. // Can overflow, but the result is casted to uint256 so that the
  310. // next value of y is "wrapped around" to a value between 0 and n - 1.
  311. x - y * int256(quotient)
  312. );
  313. }
  314. if (gcd != 1) return 0; // No inverse exists.
  315. return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
  316. }
  317. }
  318. /**
  319. * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
  320. *
  321. * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
  322. * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
  323. * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
  324. *
  325. * NOTE: this function does NOT check that `p` is a prime greater than `2`.
  326. */
  327. function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
  328. unchecked {
  329. return Math.modExp(a, p - 2, p);
  330. }
  331. }
  332. /**
  333. * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
  334. *
  335. * Requirements:
  336. * - modulus can't be zero
  337. * - underlying staticcall to precompile must succeed
  338. *
  339. * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
  340. * sure the chain you're using it on supports the precompiled contract for modular exponentiation
  341. * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
  342. * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
  343. * interpreted as 0.
  344. */
  345. function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
  346. (bool success, uint256 result) = tryModExp(b, e, m);
  347. if (!success) {
  348. Panic.panic(Panic.DIVISION_BY_ZERO);
  349. }
  350. return result;
  351. }
  352. /**
  353. * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
  354. * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
  355. * to operate modulo 0 or if the underlying precompile reverted.
  356. *
  357. * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
  358. * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
  359. * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
  360. * of a revert, but the result may be incorrectly interpreted as 0.
  361. */
  362. function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
  363. if (m == 0) return (false, 0);
  364. assembly ("memory-safe") {
  365. let ptr := mload(0x40)
  366. // | Offset | Content | Content (Hex) |
  367. // |-----------|------------|--------------------------------------------------------------------|
  368. // | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  369. // | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  370. // | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
  371. // | 0x60:0x7f | value of b | 0x<.............................................................b> |
  372. // | 0x80:0x9f | value of e | 0x<.............................................................e> |
  373. // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
  374. mstore(ptr, 0x20)
  375. mstore(add(ptr, 0x20), 0x20)
  376. mstore(add(ptr, 0x40), 0x20)
  377. mstore(add(ptr, 0x60), b)
  378. mstore(add(ptr, 0x80), e)
  379. mstore(add(ptr, 0xa0), m)
  380. // Given the result < m, it's guaranteed to fit in 32 bytes,
  381. // so we can use the memory scratch space located at offset 0.
  382. success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
  383. result := mload(0x00)
  384. }
  385. }
  386. /**
  387. * @dev Variant of {modExp} that supports inputs of arbitrary length.
  388. */
  389. function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
  390. (bool success, bytes memory result) = tryModExp(b, e, m);
  391. if (!success) {
  392. Panic.panic(Panic.DIVISION_BY_ZERO);
  393. }
  394. return result;
  395. }
  396. /**
  397. * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
  398. */
  399. function tryModExp(
  400. bytes memory b,
  401. bytes memory e,
  402. bytes memory m
  403. ) internal view returns (bool success, bytes memory result) {
  404. if (_zeroBytes(m)) return (false, new bytes(0));
  405. uint256 mLen = m.length;
  406. // Encode call args in result and move the free memory pointer
  407. result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
  408. assembly ("memory-safe") {
  409. let dataPtr := add(result, 0x20)
  410. // Write result on top of args to avoid allocating extra memory.
  411. success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
  412. // Overwrite the length.
  413. // result.length > returndatasize() is guaranteed because returndatasize() == m.length
  414. mstore(result, mLen)
  415. // Set the memory pointer after the returned data.
  416. mstore(0x40, add(dataPtr, mLen))
  417. }
  418. }
  419. /**
  420. * @dev Returns whether the provided byte array is zero.
  421. */
  422. function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
  423. for (uint256 i = 0; i < byteArray.length; ++i) {
  424. if (byteArray[i] != 0) {
  425. return false;
  426. }
  427. }
  428. return true;
  429. }
  430. /**
  431. * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
  432. * towards zero.
  433. *
  434. * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
  435. * using integer operations.
  436. */
  437. function sqrt(uint256 a) internal pure returns (uint256) {
  438. unchecked {
  439. // Take care of easy edge cases when a == 0 or a == 1
  440. if (a <= 1) {
  441. return a;
  442. }
  443. // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
  444. // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
  445. // the current value as `ε_n = | x_n - sqrt(a) |`.
  446. //
  447. // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
  448. // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
  449. // bigger than any uint256.
  450. //
  451. // By noticing that
  452. // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
  453. // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
  454. // to the msb function.
  455. uint256 aa = a;
  456. uint256 xn = 1;
  457. if (aa >= (1 << 128)) {
  458. aa >>= 128;
  459. xn <<= 64;
  460. }
  461. if (aa >= (1 << 64)) {
  462. aa >>= 64;
  463. xn <<= 32;
  464. }
  465. if (aa >= (1 << 32)) {
  466. aa >>= 32;
  467. xn <<= 16;
  468. }
  469. if (aa >= (1 << 16)) {
  470. aa >>= 16;
  471. xn <<= 8;
  472. }
  473. if (aa >= (1 << 8)) {
  474. aa >>= 8;
  475. xn <<= 4;
  476. }
  477. if (aa >= (1 << 4)) {
  478. aa >>= 4;
  479. xn <<= 2;
  480. }
  481. if (aa >= (1 << 2)) {
  482. xn <<= 1;
  483. }
  484. // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
  485. //
  486. // We can refine our estimation by noticing that the middle of that interval minimizes the error.
  487. // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
  488. // This is going to be our x_0 (and ε_0)
  489. xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
  490. // From here, Newton's method give us:
  491. // x_{n+1} = (x_n + a / x_n) / 2
  492. //
  493. // One should note that:
  494. // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
  495. // = ((x_n² + a) / (2 * x_n))² - a
  496. // = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
  497. // = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
  498. // = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
  499. // = (x_n² - a)² / (2 * x_n)²
  500. // = ((x_n² - a) / (2 * x_n))²
  501. // ≥ 0
  502. // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
  503. //
  504. // This gives us the proof of quadratic convergence of the sequence:
  505. // ε_{n+1} = | x_{n+1} - sqrt(a) |
  506. // = | (x_n + a / x_n) / 2 - sqrt(a) |
  507. // = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
  508. // = | (x_n - sqrt(a))² / (2 * x_n) |
  509. // = | ε_n² / (2 * x_n) |
  510. // = ε_n² / | (2 * x_n) |
  511. //
  512. // For the first iteration, we have a special case where x_0 is known:
  513. // ε_1 = ε_0² / | (2 * x_0) |
  514. // ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
  515. // ≤ 2**(2*e-4) / (3 * 2**(e-1))
  516. // ≤ 2**(e-3) / 3
  517. // ≤ 2**(e-3-log2(3))
  518. // ≤ 2**(e-4.5)
  519. //
  520. // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
  521. // ε_{n+1} = ε_n² / | (2 * x_n) |
  522. // ≤ (2**(e-k))² / (2 * 2**(e-1))
  523. // ≤ 2**(2*e-2*k) / 2**e
  524. // ≤ 2**(e-2*k)
  525. xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
  526. xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
  527. xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
  528. xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
  529. xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
  530. xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
  531. // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
  532. // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
  533. // sqrt(a) or sqrt(a) + 1.
  534. return xn - SafeCast.toUint(xn > a / xn);
  535. }
  536. }
  537. /**
  538. * @dev Calculates sqrt(a), following the selected rounding direction.
  539. */
  540. function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
  541. unchecked {
  542. uint256 result = sqrt(a);
  543. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
  544. }
  545. }
  546. /**
  547. * @dev Return the log in base 2 of a positive value rounded towards zero.
  548. * Returns 0 if given 0.
  549. */
  550. function log2(uint256 x) internal pure returns (uint256 r) {
  551. // If value has upper 128 bits set, log2 result is at least 128
  552. r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
  553. // If upper 64 bits of 128-bit half set, add 64 to result
  554. r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
  555. // If upper 32 bits of 64-bit half set, add 32 to result
  556. r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
  557. // If upper 16 bits of 32-bit half set, add 16 to result
  558. r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
  559. // If upper 8 bits of 16-bit half set, add 8 to result
  560. r |= SafeCast.toUint((x >> r) > 0xff) << 3;
  561. // If upper 4 bits of 8-bit half set, add 4 to result
  562. r |= SafeCast.toUint((x >> r) > 0xf) << 2;
  563. // Shifts value right by the current result and use it as an index into this lookup table:
  564. //
  565. // | x (4 bits) | index | table[index] = MSB position |
  566. // |------------|---------|-----------------------------|
  567. // | 0000 | 0 | table[0] = 0 |
  568. // | 0001 | 1 | table[1] = 0 |
  569. // | 0010 | 2 | table[2] = 1 |
  570. // | 0011 | 3 | table[3] = 1 |
  571. // | 0100 | 4 | table[4] = 2 |
  572. // | 0101 | 5 | table[5] = 2 |
  573. // | 0110 | 6 | table[6] = 2 |
  574. // | 0111 | 7 | table[7] = 2 |
  575. // | 1000 | 8 | table[8] = 3 |
  576. // | 1001 | 9 | table[9] = 3 |
  577. // | 1010 | 10 | table[10] = 3 |
  578. // | 1011 | 11 | table[11] = 3 |
  579. // | 1100 | 12 | table[12] = 3 |
  580. // | 1101 | 13 | table[13] = 3 |
  581. // | 1110 | 14 | table[14] = 3 |
  582. // | 1111 | 15 | table[15] = 3 |
  583. //
  584. // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
  585. assembly ("memory-safe") {
  586. r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
  587. }
  588. }
  589. /**
  590. * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
  591. * Returns 0 if given 0.
  592. */
  593. function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
  594. unchecked {
  595. uint256 result = log2(value);
  596. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
  597. }
  598. }
  599. /**
  600. * @dev Return the log in base 10 of a positive value rounded towards zero.
  601. * Returns 0 if given 0.
  602. */
  603. function log10(uint256 value) internal pure returns (uint256) {
  604. uint256 result = 0;
  605. unchecked {
  606. if (value >= 10 ** 64) {
  607. value /= 10 ** 64;
  608. result += 64;
  609. }
  610. if (value >= 10 ** 32) {
  611. value /= 10 ** 32;
  612. result += 32;
  613. }
  614. if (value >= 10 ** 16) {
  615. value /= 10 ** 16;
  616. result += 16;
  617. }
  618. if (value >= 10 ** 8) {
  619. value /= 10 ** 8;
  620. result += 8;
  621. }
  622. if (value >= 10 ** 4) {
  623. value /= 10 ** 4;
  624. result += 4;
  625. }
  626. if (value >= 10 ** 2) {
  627. value /= 10 ** 2;
  628. result += 2;
  629. }
  630. if (value >= 10 ** 1) {
  631. result += 1;
  632. }
  633. }
  634. return result;
  635. }
  636. /**
  637. * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
  638. * Returns 0 if given 0.
  639. */
  640. function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
  641. unchecked {
  642. uint256 result = log10(value);
  643. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
  644. }
  645. }
  646. /**
  647. * @dev Return the log in base 256 of a positive value rounded towards zero.
  648. * Returns 0 if given 0.
  649. *
  650. * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
  651. */
  652. function log256(uint256 x) internal pure returns (uint256 r) {
  653. // If value has upper 128 bits set, log2 result is at least 128
  654. r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
  655. // If upper 64 bits of 128-bit half set, add 64 to result
  656. r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
  657. // If upper 32 bits of 64-bit half set, add 32 to result
  658. r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
  659. // If upper 16 bits of 32-bit half set, add 16 to result
  660. r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
  661. // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
  662. return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
  663. }
  664. /**
  665. * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
  666. * Returns 0 if given 0.
  667. */
  668. function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
  669. unchecked {
  670. uint256 result = log256(value);
  671. return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
  672. }
  673. }
  674. /**
  675. * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
  676. */
  677. function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
  678. return uint8(rounding) % 2 == 1;
  679. }
  680. }