BN.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. <?php
  2. namespace BN;
  3. use \JsonSerializable;
  4. use \Exception;
  5. use \BI\BigInteger;
  6. class BN implements JsonSerializable
  7. {
  8. public $bi;
  9. public $red;
  10. function __construct($number, $base = 10, $endian = null)
  11. {
  12. if( $number instanceof BN ) {
  13. $this->bi = $number->bi;
  14. $this->red = $number->red;
  15. return;
  16. }
  17. // Reduction context
  18. $this->red = null;
  19. if ( $number instanceof BigInteger ) {
  20. $this->bi = $number;
  21. return;
  22. }
  23. if( is_array($number) )
  24. {
  25. $number = call_user_func_array("pack", array_merge(array("C*"), $number));
  26. $number = bin2hex($number);
  27. $base = 16;
  28. }
  29. if( $base == "hex" )
  30. $base = 16;
  31. if ($endian == 'le') {
  32. if ($base != 16)
  33. throw new \Exception("Not implemented");
  34. $number = bin2hex(strrev(hex2bin($number)));
  35. }
  36. $this->bi = new BigInteger($number, $base);
  37. }
  38. public function negative() {
  39. return $this->bi->sign() < 0 ? 1 : 0;
  40. }
  41. public static function isBN($num) {
  42. return ($num instanceof BN);
  43. }
  44. public static function max($left, $right) {
  45. return ( $left->cmp($right) > 0 ) ? $left : $right;
  46. }
  47. public static function min($left, $right) {
  48. return ( $left->cmp($right) < 0 ) ? $left : $right;
  49. }
  50. public function copy($dest)
  51. {
  52. $dest->bi = $this->bi;
  53. $dest->red = $this->red;
  54. }
  55. public function _clone() {
  56. return clone($this);
  57. }
  58. public function toString($base = 10, $padding = 0)
  59. {
  60. if( $base == "hex" )
  61. $base = 16;
  62. $str = $this->bi->abs()->toString($base);
  63. if ($padding > 0) {
  64. $len = strlen($str);
  65. $mod = $len % $padding;
  66. if ($mod > 0)
  67. $len = $len + $padding - $mod;
  68. $str = str_pad($str, $len, "0", STR_PAD_LEFT);
  69. }
  70. if( $this->negative() )
  71. return "-" . $str;
  72. return $str;
  73. }
  74. public function toNumber() {
  75. return $this->bi->toNumber();
  76. }
  77. public function jsonSerialize() {
  78. return $this->toString(16);
  79. }
  80. public function toArray($endian = "be", $length = -1)
  81. {
  82. $hex = $this->toString(16);
  83. if( $hex[0] === "-" )
  84. $hex = substr($hex, 1);
  85. if( strlen($hex) % 2 )
  86. $hex = "0" . $hex;
  87. $bytes = array_map(
  88. function($v) { return hexdec($v); },
  89. str_split($hex, 2)
  90. );
  91. if( $length > 0 )
  92. {
  93. $count = count($bytes);
  94. if( $count > $length )
  95. throw new Exception("Byte array longer than desired length");
  96. for($i = $count; $i < $length; $i++)
  97. array_unshift($bytes, 0);
  98. }
  99. if( $endian === "le" )
  100. $bytes = array_reverse($bytes);
  101. return $bytes;
  102. }
  103. public function bitLength() {
  104. $bin = $this->toString(2);
  105. return strlen($bin) - ( $bin[0] === "-" ? 1 : 0 );
  106. }
  107. public function zeroBits() {
  108. return $this->bi->scan1(0);
  109. }
  110. public function byteLength() {
  111. return ceil($this->bitLength() / 8);
  112. }
  113. //TODO toTwos, fromTwos
  114. public function isNeg() {
  115. return $this->negative() !== 0;
  116. }
  117. // Return negative clone of `this`
  118. public function neg() {
  119. return $this->_clone()->ineg();
  120. }
  121. public function ineg() {
  122. $this->bi = $this->bi->neg();
  123. return $this;
  124. }
  125. // Or `num` with `this` in-place
  126. public function iuor(BN $num) {
  127. $this->bi = $this->bi->binaryOr($num->bi);
  128. return $this;
  129. }
  130. public function ior(BN $num) {
  131. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative());
  132. return $this->iuor($num);
  133. }
  134. // Or `num` with `this`
  135. public function _or(BN $num) {
  136. if( $this->ucmp($num) > 0 )
  137. return $this->_clone()->ior($num);
  138. return $num->_clone()->ior($this);
  139. }
  140. public function uor(BN $num) {
  141. if( $this->ucmp($num) > 0 )
  142. return $this->_clone()->iuor($num);
  143. return $num->_clone()->ior($this);
  144. }
  145. // And `num` with `this` in-place
  146. public function iuand(BN $num) {
  147. $this->bi = $this->bi->binaryAnd($num->bi);
  148. return $this;
  149. }
  150. public function iand(BN $num) {
  151. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative());
  152. return $this->iuand($num);
  153. }
  154. // And `num` with `this`
  155. public function _and(BN $num) {
  156. if( $this->ucmp($num) > 0 )
  157. return $this->_clone()->iand($num);
  158. return $num->_clone()->iand($this);
  159. }
  160. public function uand(BN $num) {
  161. if( $this->ucmp($num) > 0 )
  162. return $this->_clone()->iuand($num);
  163. return $num->_clone()->iuand($this);
  164. }
  165. // Xor `num` with `this` in-place
  166. public function iuxor(BN $num) {
  167. $this->bi = $this->bi->binaryXor($num->bi);
  168. return $this;
  169. }
  170. public function ixor(BN $num) {
  171. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative());
  172. return $this->iuxor($num);
  173. }
  174. // Xor `num` with `this`
  175. public function _xor(BN $num) {
  176. if( $this->ucmp($num) > 0 )
  177. return $this->_clone()->ixor($num);
  178. return $num->_clone()->ixor($this);
  179. }
  180. public function uxor(BN $num) {
  181. if( $this->ucmp($num) > 0 )
  182. return $this->_clone()->iuxor($num);
  183. return $num->_clone()->iuxor($this);
  184. }
  185. // Not ``this`` with ``width`` bitwidth
  186. public function inotn($width)
  187. {
  188. assert(is_integer($width) && $width >= 0);
  189. $neg = false;
  190. if( $this->isNeg() )
  191. {
  192. $this->negi();
  193. $neg = true;
  194. }
  195. for($i = 0; $i < $width; $i++)
  196. $this->bi = $this->bi->setbit($i, !$this->bi->testbit($i));
  197. return $neg ? $this->negi() : $this;
  198. }
  199. public function notn($width) {
  200. return $this->_clone()->inotn($width);
  201. }
  202. // Set `bit` of `this`
  203. public function setn($bit, $val) {
  204. assert(is_integer($bit) && $bit > 0);
  205. $this->bi = $this->bi->setbit($bit, !!$val);
  206. return $this;
  207. }
  208. // Add `num` to `this` in-place
  209. public function iadd(BN $num) {
  210. $this->bi = $this->bi->add($num->bi);
  211. return $this;
  212. }
  213. // Add `num` to `this`
  214. public function add(BN $num) {
  215. return $this->_clone()->iadd($num);
  216. }
  217. // Subtract `num` from `this` in-place
  218. public function isub(BN $num) {
  219. $this->bi = $this->bi->sub($num->bi);
  220. return $this;
  221. }
  222. // Subtract `num` from `this`
  223. public function sub(BN $num) {
  224. return $this->_clone()->isub($num);
  225. }
  226. // Multiply `this` by `num`
  227. public function mul(BN $num) {
  228. return $this->_clone()->imul($num);
  229. }
  230. // In-place Multiplication
  231. public function imul(BN $num) {
  232. $this->bi = $this->bi->mul($num->bi);
  233. return $this;
  234. }
  235. public function imuln($num)
  236. {
  237. assert(is_numeric($num));
  238. $int = intval($num);
  239. $res = $this->bi->mul($int);
  240. if( ($num - $int) > 0 )
  241. {
  242. $mul = 10;
  243. $frac = ($num - $int) * $mul;
  244. $int = intval($frac);
  245. while( ($frac - $int) > 0 )
  246. {
  247. $mul *= 10;
  248. $frac *= 10;
  249. $int = intval($frac);
  250. }
  251. $tmp = $this->bi->mul($int);
  252. $tmp = $tmp->div($mul);
  253. $res = $res->add($tmp);
  254. }
  255. $this->bi = $res;
  256. return $this;
  257. }
  258. public function muln($num) {
  259. return $this->_clone()->imuln($num);
  260. }
  261. // `this` * `this`
  262. public function sqr() {
  263. return $this->mul($this);
  264. }
  265. // `this` * `this` in-place
  266. public function isqr() {
  267. return $this->imul($this);
  268. }
  269. // Math.pow(`this`, `num`)
  270. public function pow(BN $num) {
  271. $res = clone($this);
  272. $res->bi = $res->bi->pow($num->bi);
  273. return $res;
  274. }
  275. // Shift-left in-place
  276. public function iushln($bits) {
  277. assert(is_integer($bits) && $bits >= 0);
  278. if ($bits < 54) {
  279. $this->bi = $this->bi->mul(1 << $bits);
  280. } else {
  281. $this->bi = $this->bi->mul((new BigInteger(2))->pow($bits));
  282. }
  283. return $this;
  284. }
  285. public function ishln($bits) {
  286. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative());
  287. return $this->iushln($bits);
  288. }
  289. // Shift-right in-place
  290. // NOTE: `hint` is a lowest bit before trailing zeroes
  291. // NOTE: if `extended` is present - it will be filled with destroyed bits
  292. public function iushrn($bits, $hint = 0, &$extended = null) {
  293. if( $hint != 0 )
  294. throw new Exception("Not implemented");
  295. assert(is_integer($bits) && $bits >= 0);
  296. if( $extended != null )
  297. $extended = $this->maskn($bits);
  298. if ($bits < 54) {
  299. $this->bi = $this->bi->div(1 << $bits);
  300. } else {
  301. $this->bi = $this->bi->div((new BigInteger(2))->pow($bits));
  302. }
  303. return $this;
  304. }
  305. public function ishrn($bits, $hint = null, $extended = null) {
  306. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative());
  307. return $this->iushrn($bits, $hint, $extended);
  308. }
  309. // Shift-left
  310. public function shln($bits) {
  311. return $this->_clone()->ishln($bits);
  312. }
  313. public function ushln($bits) {
  314. return $this->_clone()->iushln($bits);
  315. }
  316. // Shift-right
  317. public function shrn($bits) {
  318. return $this->_clone()->ishrn($bits);
  319. }
  320. public function ushrn($bits) {
  321. return $this->_clone()->iushrn($bits);
  322. }
  323. // Test if n bit is set
  324. public function testn($bit) {
  325. assert(is_integer($bit) && $bit >= 0);
  326. return $this->bi->testbit($bit);
  327. }
  328. // Return only lowers bits of number (in-place)
  329. public function imaskn($bits) {
  330. assert(is_integer($bits) && $bits >= 0);
  331. if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative());
  332. $mask = "";
  333. for($i = 0; $i < $bits; $i++)
  334. $mask .= "1";
  335. return $this->iand(new BN($mask, 2));
  336. }
  337. // Return only lowers bits of number
  338. public function maskn($bits) {
  339. return $this->_clone()->imaskn($bits);
  340. }
  341. // Add plain number `num` to `this`
  342. public function iaddn($num) {
  343. assert(is_numeric($num));
  344. $this->bi = $this->bi->add(intval($num));
  345. return $this;
  346. }
  347. // Subtract plain number `num` from `this`
  348. public function isubn($num) {
  349. assert(is_numeric($num));
  350. $this->bi = $this->bi->sub(intval($num));
  351. return $this;
  352. }
  353. public function addn($num) {
  354. return $this->_clone()->iaddn($num);
  355. }
  356. public function subn($num) {
  357. return $this->_clone()->isubn($num);
  358. }
  359. public function iabs() {
  360. if ($this->bi->sign() < 0) {
  361. $this->bi = $this->bi->abs();
  362. }
  363. return $this;
  364. }
  365. public function abs() {
  366. $res = clone($this);
  367. if ($res->bi->sign() < 0)
  368. $res->bi = $res->bi->abs();
  369. return $res;
  370. }
  371. // Find `this` / `num`
  372. public function div(BN $num) {
  373. if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero());
  374. $res = clone($this);
  375. $res->bi = $res->bi->div($num->bi);
  376. return $res;
  377. }
  378. // Find `this` % `num`
  379. public function mod(BN $num) {
  380. if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero());
  381. $res = clone($this);
  382. $res->bi = $res->bi->divR($num->bi);
  383. return $res;
  384. }
  385. public function umod(BN $num) {
  386. if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero());
  387. $tmp = $num->bi->sign() < 0 ? $num->bi->abs() : $num->bi;
  388. $res = clone($this);
  389. $res->bi = $this->bi->mod($tmp);
  390. return $res;
  391. }
  392. // Find Round(`this` / `num`)
  393. public function divRound(BN $num)
  394. {
  395. if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero());
  396. $negative = $this->negative() !== $num->negative();
  397. $res = $this->_clone()->abs();
  398. $arr = $res->bi->divQR($num->bi->abs());
  399. $res->bi = $arr[0];
  400. $tmp = $num->bi->sub($arr[1]->mul(2));
  401. if( $tmp->cmp(0) <= 0 && (!$negative || $this->negative() === 0) )
  402. $res->iaddn(1);
  403. return $negative ? $res->negi() : $res;
  404. }
  405. public function modn($num) {
  406. assert(is_numeric($num) && $num != 0);
  407. return $this->bi->divR(intval($num))->toNumber();
  408. }
  409. // In-place division by number
  410. public function idivn($num) {
  411. assert(is_numeric($num) && $num != 0);
  412. $this->bi = $this->bi->div(intval($num));
  413. return $this;
  414. }
  415. public function divn($num) {
  416. return $this->_clone()->idivn($num);
  417. }
  418. public function gcd(BN $num) {
  419. $res = clone($this);
  420. $res->bi = $this->bi->gcd($num->bi);
  421. return $res;
  422. }
  423. public function invm(BN $num) {
  424. $res = clone($this);
  425. $res->bi = $res->bi->modInverse($num->bi);
  426. return $res;
  427. }
  428. public function isEven() {
  429. return !$this->bi->testbit(0);
  430. }
  431. public function isOdd() {
  432. return $this->bi->testbit(0);
  433. }
  434. public function andln($num) {
  435. assert(is_numeric($num));
  436. return $this->bi->binaryAnd($num)->toNumber();
  437. }
  438. public function bincn($num) {
  439. $tmp = (new BN(1))->iushln($num);
  440. return $this->add($tmp);
  441. }
  442. public function isZero() {
  443. return $this->bi->sign() == 0;
  444. }
  445. public function cmpn($num) {
  446. assert(is_numeric($num));
  447. return $this->bi->cmp($num);
  448. }
  449. // Compare two numbers and return:
  450. // 1 - if `this` > `num`
  451. // 0 - if `this` == `num`
  452. // -1 - if `this` < `num`
  453. public function cmp(BN $num) {
  454. return $this->bi->cmp($num->bi);
  455. }
  456. public function ucmp(BN $num) {
  457. return $this->bi->abs()->cmp($num->bi->abs());
  458. }
  459. public function gtn($num) {
  460. return $this->cmpn($num) > 0;
  461. }
  462. public function gt(BN $num) {
  463. return $this->cmp($num) > 0;
  464. }
  465. public function gten($num) {
  466. return $this->cmpn($num) >= 0;
  467. }
  468. public function gte(BN $num) {
  469. return $this->cmp($num) >= 0;
  470. }
  471. public function ltn($num) {
  472. return $this->cmpn($num) < 0;
  473. }
  474. public function lt(BN $num) {
  475. return $this->cmp($num) < 0;
  476. }
  477. public function lten($num) {
  478. return $this->cmpn($num) <= 0;
  479. }
  480. public function lte(BN $num) {
  481. return $this->cmp($num) <= 0;
  482. }
  483. public function eqn($num) {
  484. return $this->cmpn($num) === 0;
  485. }
  486. public function eq(BN $num) {
  487. return $this->cmp($num) === 0;
  488. }
  489. public function toRed(Red &$ctx) {
  490. if( $this->red !== null )
  491. throw new Exception("Already a number in reduction context");
  492. if( $this->negative() !== 0 )
  493. throw new Exception("red works only with positives");
  494. return $ctx->convertTo($this)->_forceRed($ctx);
  495. }
  496. public function fromRed() {
  497. if( $this->red === null )
  498. throw new Exception("fromRed works only with numbers in reduction context");
  499. return $this->red->convertFrom($this);
  500. }
  501. public function _forceRed(Red &$ctx) {
  502. $this->red = $ctx;
  503. return $this;
  504. }
  505. public function forceRed(Red &$ctx) {
  506. if( $this->red !== null )
  507. throw new Exception("Already a number in reduction context");
  508. return $this->_forceRed($ctx);
  509. }
  510. public function redAdd(BN $num) {
  511. if( $this->red === null )
  512. throw new Exception("redAdd works only with red numbers");
  513. $res = clone($this);
  514. $res->bi = $res->bi->add($num->bi);
  515. if ($res->bi->cmp($this->red->m->bi) >= 0)
  516. $res->bi = $res->bi->sub($this->red->m->bi);
  517. return $res;
  518. // return $this->red->add($this, $num);
  519. }
  520. public function redIAdd(BN $num) {
  521. if( $this->red === null )
  522. throw new Exception("redIAdd works only with red numbers");
  523. $res = $this;
  524. $res->bi = $res->bi->add($num->bi);
  525. if ($res->bi->cmp($this->red->m->bi) >= 0)
  526. $res->bi = $res->bi->sub($this->red->m->bi);
  527. return $res;
  528. //return $this->red->iadd($this, $num);
  529. }
  530. public function redSub(BN $num) {
  531. if( $this->red === null )
  532. throw new Exception("redSub works only with red numbers");
  533. $res = clone($this);
  534. $res->bi = $this->bi->sub($num->bi);
  535. if ($res->bi->sign() < 0)
  536. $res->bi = $res->bi->add($this->red->m->bi);
  537. return $res;
  538. //return $this->red->sub($this, $num);
  539. }
  540. public function redISub(BN $num) {
  541. if( $this->red === null )
  542. throw new Exception("redISub works only with red numbers");
  543. $this->bi = $this->bi->sub($num->bi);
  544. if ($this->bi->sign() < 0)
  545. $this->bi = $this->bi->add($this->red->m->bi);
  546. return $this;
  547. // return $this->red->isub($this, $num);
  548. }
  549. public function redShl(BN $num) {
  550. if( $this->red === null )
  551. throw new Exception("redShl works only with red numbers");
  552. return $this->red->shl($this, $num);
  553. }
  554. public function redMul(BN $num) {
  555. if( $this->red === null )
  556. throw new Exception("redMul works only with red numbers");
  557. $res = clone($this);
  558. $res->bi = $this->bi->mul($num->bi)->mod($this->red->m->bi);
  559. return $res;
  560. /*
  561. return $this->red->mul($this, $num);
  562. */
  563. }
  564. public function redIMul(BN $num) {
  565. if( $this->red === null )
  566. throw new Exception("redIMul works only with red numbers");
  567. $this->bi = $this->bi->mul($num->bi)->mod($this->red->m->bi);
  568. return $this;
  569. //return $this->red->imul($this, $num);
  570. }
  571. public function redSqr() {
  572. if( $this->red === null )
  573. throw new Exception("redSqr works only with red numbers");
  574. $res = clone($this);
  575. $res->bi = $this->bi->mul($this->bi)->mod($this->red->m->bi);
  576. return $res;
  577. /*
  578. $this->red->verify1($this);
  579. return $this->red->sqr($this);
  580. */
  581. }
  582. public function redISqr() {
  583. if( $this->red === null )
  584. throw new Exception("redISqr works only with red numbers");
  585. $res = $this;
  586. $res->bi = $this->bi->mul($this->bi)->mod($this->red->m->bi);
  587. return $res;
  588. /* $this->red->verify1($this);
  589. return $this->red->isqr($this);
  590. */
  591. }
  592. public function redSqrt() {
  593. if( $this->red === null )
  594. throw new Exception("redSqrt works only with red numbers");
  595. $this->red->verify1($this);
  596. return $this->red->sqrt($this);
  597. }
  598. public function redInvm() {
  599. if( $this->red === null )
  600. throw new Exception("redInvm works only with red numbers");
  601. $this->red->verify1($this);
  602. return $this->red->invm($this);
  603. }
  604. public function redNeg() {
  605. if( $this->red === null )
  606. throw new Exception("redNeg works only with red numbers");
  607. $this->red->verify1($this);
  608. return $this->red->neg($this);
  609. }
  610. public function redPow(BN $num) {
  611. $this->red->verify2($this, $num);
  612. return $this->red->pow($this, $num);
  613. }
  614. public static function red($num) {
  615. return new Red($num);
  616. }
  617. public static function mont($num) {
  618. return new Red($num);
  619. }
  620. public function inspect() {
  621. return ($this->red == null ? "<BN: " : "<BN-R: ") . $this->toString(16) . ">";
  622. }
  623. public function __debugInfo() {
  624. if ($this->red != null) {
  625. return ["BN-R" => $this->toString(16)];
  626. } else {
  627. return ["BN" => $this->toString(16)];
  628. }
  629. }
  630. }