-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path512Math.sol
More file actions
1953 lines (1679 loc) · 76.6 KB
/
512Math.sol
File metadata and controls
1953 lines (1679 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity =0.8.34;
import {Panic} from "./Panic.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {Clz} from "../vendor/Clz.sol";
import {Ternary} from "./Ternary.sol";
import {FastLogic} from "./FastLogic.sol";
import {Sqrt} from "../vendor/Sqrt.sol";
/*
WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
*** ***
WARNING This code is unaudited WARNING
*** ***
WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
*/
/// The type uint512 behaves as if it were declared as
/// struct uint512 {
/// uint256 hi;
/// uint256 lo;
/// }
/// However, returning `memory` references from internal functions is impossible
/// to do efficiently, especially when the functions are small and are called
/// frequently. Therefore, we assume direct control over memory allocation using
/// the functions `tmp()` and `alloc()` defined below. If you need to pass
/// 512-bit integers between contracts (generally a bad idea), the struct
/// `uint512_external` defined at the end of this file is provided for this
/// purpose and has exactly the definition you'd expect (as well as convenient
/// conversion functions).
///
/// MAKING A DECLARATION OF THE FOLLOWING FORM WILL CAUSE UNEXPECTED BEHAVIOR:
/// uint512 x;
/// INSTEAD OF DOING THAT, YOU MUST USE `alloc()`, LIKE THIS:
/// uint512 x = alloc();
/// IF YOU REALLY WANTED TO DO THAT (ADVANCED USAGE) THEN FOR CLARITY, WRITE THE
/// FOLLOWING:
/// uint512 x = tmp();
///
/// While user-defined arithmetic operations (i.e. +, -, *, %, /) are provided
/// for `uint512`, they are not gas-optimal, full-featured, or composable. You
/// will get a revert upon incorrect usage. Their primary usage is when a simple
/// arithmetic operation needs to be performed followed by a comparison (e.g. <,
/// >, ==, etc.) or conversion to a pair of `uint256`s (i.e. `.into()`). The use
/// of the user-defined arithmetic operations is not composable with the usage
/// of `tmp()`.
///
/// In general, correct usage of `uint512` requires always specifying the output
/// location of each operation. For each `o*` operation (mnemonic:
/// out-of-place), the first argument is the output location and the remaining
/// arguments are the input. For each `i*` operation (mnemonic: in-place), the
/// first argument is both input and output and the remaining arguments are
/// purely input. For each `ir*` operation (mnemonic: in-place reverse; only for
/// non-commutative operations), the semantics of the input arguments are
/// flipped (i.e. `irsub(foo, bar)` is semantically equivalent to `foo = bar -
/// foo`); the first argument is still the output location. Only `irsub`,
/// `irmod`, `irdiv`, `irmodAlt`, and `irdivAlt` exist. Unless otherwise noted,
/// the return value of each function is the output location. This supports
/// chaining/pipeline/tacit-style programming.
///
/// All provided arithmetic operations behave as if they were inside an
/// `unchecked` block. We assume that because you're reaching for 512-bit math,
/// you have domain knowledge about the range of values that you will
/// encounter. Overflow causes truncation, not a revert. Division or modulo by
/// zero still causes a panic revert with code 18 (identical behavior to
/// "normal" unchecked arithmetic). The `unsafe*` functions do not perform
/// checking for division or modulo by zero; in this case division or modulo by
/// zero is undefined behavior.
///
/// Three additional arithmetic operations are provided, bare `sub`, `mod`, and
/// `div`. These are provided for use when it is known that the result of the
/// operation will fit into 256 bits. This fact is not checked, but more
/// efficient algorithms are employed assuming this. The result is a `uint256`.
///
/// The operations `*mod` and `*div` with 512-bit denominator are `view` instead
/// of `pure` because they make use of the MODEXP (5) precompile. Some EVM L2s
/// and sidechains do not support MODEXP with 512-bit arguments. On those
/// chains, the `*modAlt` and `*divAlt` functions are provided. These functions
/// are truly `pure` and do not rely on MODEXP at all. The downside is that they
/// consume slightly (really only *slightly*) more gas.
///
/// ## Full list of provided functions
///
/// Unless otherwise noted, all functions return `(uint512)`
///
/// ### Utility
///
/// * from(uint256)
/// * from(uint256,uint256) -- The EVM is big-endian. The most-significant word is first.
/// * from(uint512) -- performs a copy
/// * into() returns (uint256,uint256) -- Again, the most-significant word is first.
/// * toExternal(uint512) returns (uint512_external memory)
///
/// ### Comparison (all functions return `(bool)`)
///
/// * isZero(uint512)
/// * isMax(uint512)
/// * eq(uint512,uint256)
/// * eq(uint512,uint512)
/// * ne(uint512,uint256)
/// * ne(uint512,uint512)
/// * gt(uint512,uint256)
/// * gt(uint512,uint512)
/// * ge(uint512,uint256)
/// * ge(uint512,uint512)
/// * lt(uint512,uint256)
/// * lt(uint512,uint512)
/// * le(uint512,uint256)
/// * le(uint512,uint512)
///
/// ### Addition
///
/// * oadd(uint512,uint256,uint256) -- iadd(uint256,uint256) is not provided for somewhat obvious reasons
/// * oadd(uint512,uint512,uint256)
/// * iadd(uint512,uint256)
/// * oadd(uint512,uint512,uint512)
/// * iadd(uint512,uint512)
///
/// ### Subtraction
///
/// * sub(uint512,uint256) returns (uint256)
/// * sub(uint512,uint512) returns (uint256)
/// * osub(uint512,uint512,uint256)
/// * isub(uint512,uint256)
/// * osub(uint512,uint512,uint512)
/// * isub(uint512,uint512)
/// * irsub(uint512,uint512)
///
/// ### Multiplication
///
/// * omul(uint512,uint256,uint256)
/// * omul(uint512,uint512,uint256)
/// * imul(uint512,uint256)
/// * omul(uint512,uint512,uint512)
/// * imul(uint512,uint512)
///
/// ### Modulo
///
/// * mod(uint512,uint256) returns (uint256) -- mod(uint512,uint512) is not provided for less obvious reasons
/// * omod(uint512,uint512,uint512)
/// * imod(uint512,uint512)
/// * irmod(uint512,uint512)
/// * omodAlt(uint512,uint512,uint512)
/// * imodAlt(uint512,uint512)
/// * irmodAlt(uint512,uint512)
///
/// ### Division
///
/// * div(uint512,uint256) returns (uint256)
/// * divUp(uint512,uint256) returns (uint256)
/// * unsafeDiv(uint512,uint256) returns (uint256)
/// * unsafeDivUp(uint512,uint256) returns (uint256)
/// * div(uint512,uint512) returns (uint256)
/// * divUp(uint512,uint512) returns (uint256)
/// * odiv(uint512,uint512,uint256)
/// * idiv(uint512,uint256)
/// * odivUp(uint512,uint512,uint256)
/// * idivUp(uint512,uint256)
/// * odiv(uint512,uint512,uint512)
/// * idiv(uint512,uint512)
/// * irdiv(uint512,uint512)
/// * odivUp(uint512,uint512,uint512)
/// * idivUp(uint512,uint512)
/// * irdivUp(uint512,uint512)
/// * divAlt(uint512,uint512) returns (uint256) -- divAlt(uint512,uint256) is not provided because div(uint512,uint256) is suitable for chains without MODEXP
/// * odivAlt(uint512,uint512,uint512)
/// * idivAlt(uint512,uint512)
/// * irdivAlt(uint512,uint512)
/// * divUpAlt(uint512,uint512) returns (uint256)
/// * odivUpAlt(uint512,uint512,uint512)
/// * idivUpAlt(uint512,uint512)
/// * irdivUpAlt(uint512,uint512)
///
/// ### Square root
///
/// * sqrt(uint512) returns (uint256)
/// * osqrtUp(uint512,uint512)
/// * isqrtUp(uint512)
///
/// ### Shifting
///
/// * oshr(uint512,uint512,uint256)
/// * ishr(uint512,uint256)
/// * oshrUp(uint512,uint512,uint256)
/// * ishrUp(uint512,uint256)
/// * oshl(uint512,uint512,uint256)
/// * ishl(uint512,uint256)
type uint512 is bytes32;
function alloc() pure returns (uint512 r) {
assembly ("memory-safe") {
r := mload(0x40)
mstore(0x40, add(0x40, r))
}
}
function tmp() pure returns (uint512 r) {}
library Lib512MathAccessors {
function from(uint512 r, uint256 x) internal pure returns (uint512 r_out) {
assembly ("memory-safe") {
mstore(r, 0x00)
mstore(add(0x20, r), x)
r_out := r
}
}
function from(uint512 r, uint256 x_hi, uint256 x_lo) internal pure returns (uint512 r_out) {
assembly ("memory-safe") {
mstore(r, x_hi)
mstore(add(0x20, r), x_lo)
r_out := r
}
}
function from(uint512 r, uint512 x) internal pure returns (uint512 r_out) {
assembly ("memory-safe") {
// Paradoxically, using `mload` and `mstore` here (instead of
// `mcopy`) produces more optimal code because it gives solc the
// opportunity to optimize-out the use of memory entirely, in
// typical usage. As a happy side effect, it also means that we
// don't have to deal with Cancun hardfork compatibility issues.
mstore(r, mload(x))
mstore(add(0x20, r), mload(add(0x20, x)))
r_out := r
}
}
function into(uint512 x) internal pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
r_hi := mload(x)
r_lo := mload(add(0x20, x))
}
}
}
using Lib512MathAccessors for uint512 global;
library Lib512MathComparisons {
function isZero(uint512 x) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
assembly ("memory-safe") {
r := iszero(or(x_hi, x_lo))
}
}
function isMax(uint512 x) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
assembly ("memory-safe") {
r := iszero(not(and(x_hi, x_lo)))
}
}
function eq(uint512 x, uint256 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
assembly ("memory-safe") {
r := and(iszero(x_hi), eq(x_lo, y))
}
}
function gt(uint512 x, uint256 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
assembly ("memory-safe") {
r := or(gt(x_hi, 0x00), gt(x_lo, y))
}
}
function lt(uint512 x, uint256 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
assembly ("memory-safe") {
r := and(iszero(x_hi), lt(x_lo, y))
}
}
function ne(uint512 x, uint256 y) internal pure returns (bool) {
return !eq(x, y);
}
function ge(uint512 x, uint256 y) internal pure returns (bool) {
return !lt(x, y);
}
function le(uint512 x, uint256 y) internal pure returns (bool) {
return !gt(x, y);
}
function eq(uint512 x, uint512 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
assembly ("memory-safe") {
r := and(eq(x_hi, y_hi), eq(x_lo, y_lo))
}
}
function gt(uint512 x, uint512 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
assembly ("memory-safe") {
r := or(gt(x_hi, y_hi), and(eq(x_hi, y_hi), gt(x_lo, y_lo)))
}
}
function lt(uint512 x, uint512 y) internal pure returns (bool r) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
assembly ("memory-safe") {
r := or(lt(x_hi, y_hi), and(eq(x_hi, y_hi), lt(x_lo, y_lo)))
}
}
function ne(uint512 x, uint512 y) internal pure returns (bool) {
return !eq(x, y);
}
function ge(uint512 x, uint512 y) internal pure returns (bool) {
return !lt(x, y);
}
function le(uint512 x, uint512 y) internal pure returns (bool) {
return !gt(x, y);
}
}
using Lib512MathComparisons for uint512 global;
function __eq(uint512 x, uint512 y) pure returns (bool) {
return x.eq(y);
}
function __gt(uint512 x, uint512 y) pure returns (bool) {
return x.gt(y);
}
function __lt(uint512 x, uint512 y) pure returns (bool r) {
return x.lt(y);
}
function __ne(uint512 x, uint512 y) pure returns (bool) {
return x.ne(y);
}
function __ge(uint512 x, uint512 y) pure returns (bool) {
return x.ge(y);
}
function __le(uint512 x, uint512 y) pure returns (bool) {
return x.le(y);
}
using {__eq as ==, __gt as >, __lt as <, __ne as !=, __ge as >=, __le as <=} for uint512 global;
library Lib512MathArithmetic {
using UnsafeMath for uint256;
using Clz for uint256;
using Ternary for bool;
using FastLogic for bool;
using Sqrt for uint256;
function _add(uint256 x, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
r_lo := add(x, y)
// `lt(r_lo, x)` indicates overflow in the lower addition. We can
// add the bool directly to the integer to perform carry
r_hi := lt(r_lo, x)
}
}
function _add(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
r_lo := add(x_lo, y)
// `lt(r_lo, x_lo)` indicates overflow in the lower
// addition. Overflow in the high limb is simply ignored
r_hi := add(x_hi, lt(r_lo, x_lo))
}
}
function _add(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo)
private
pure
returns (uint256 r_hi, uint256 r_lo)
{
assembly ("memory-safe") {
r_lo := add(x_lo, y_lo)
// `lt(r_lo, x_lo)` indicates overflow in the lower
// addition. Overflow in the high limb is simply ignored.
r_hi := add(add(x_hi, y_hi), lt(r_lo, x_lo))
}
}
function oadd(uint512 r, uint256 x, uint256 y) internal pure returns (uint512) {
(uint256 r_hi, uint256 r_lo) = _add(x, y);
return r.from(r_hi, r_lo);
}
function oadd(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 r_hi, uint256 r_lo) = _add(x_hi, x_lo, y);
return r.from(r_hi, r_lo);
}
function iadd(uint512 r, uint256 y) internal pure returns (uint512) {
return oadd(r, r, y);
}
function oadd(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
(uint256 r_hi, uint256 r_lo) = _add(x_hi, x_lo, y_hi, y_lo);
return r.from(r_hi, r_lo);
}
function iadd(uint512 r, uint512 y) internal pure returns (uint512) {
return oadd(r, r, y);
}
function _sub(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
r_lo := sub(x_lo, y)
// `gt(r_lo, x_lo)` indicates underflow in the lower subtraction. We
// can subtract the bool directly from the integer to perform carry.
r_hi := sub(x_hi, gt(r_lo, x_lo))
}
}
function osub(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 r_hi, uint256 r_lo) = _sub(x_hi, x_lo, y);
return r.from(r_hi, r_lo);
}
function isub(uint512 r, uint256 y) internal pure returns (uint512) {
return osub(r, r, y);
}
function _sub(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo)
private
pure
returns (uint256 r_hi, uint256 r_lo)
{
assembly ("memory-safe") {
r_lo := sub(x_lo, y_lo)
// `gt(r_lo, x_lo)` indicates underflow in the lower subtraction.
// Underflow in the high limb is simply ignored.
r_hi := sub(sub(x_hi, y_hi), gt(r_lo, x_lo))
}
}
function osub(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
(uint256 r_hi, uint256 r_lo) = _sub(x_hi, x_lo, y_hi, y_lo);
return r.from(r_hi, r_lo);
}
function isub(uint512 r, uint512 y) internal pure returns (uint512) {
return osub(r, r, y);
}
function irsub(uint512 r, uint512 y) internal pure returns (uint512) {
return osub(r, y, r);
}
function sub(uint512 x, uint256 y) internal pure returns (uint256 r) {
assembly ("memory-safe") {
r := sub(mload(add(0x20, x)), y)
}
}
function sub(uint512 x, uint512 y) internal pure returns (uint256 r) {
assembly ("memory-safe") {
r := sub(mload(add(0x20, x)), mload(add(0x20, y)))
}
}
//// The technique implemented in the following functions for multiplication is
//// adapted from Remco Bloemen's work https://2π.com/17/full-mul/ .
//// The original code was released under the MIT license.
function _mul(uint256 x, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
let mm := mulmod(x, y, not(0x00))
r_lo := mul(x, y)
r_hi := sub(sub(mm, r_lo), lt(mm, r_lo))
}
}
function omul(uint512 r, uint256 x, uint256 y) internal pure returns (uint512) {
(uint256 r_hi, uint256 r_lo) = _mul(x, y);
return r.from(r_hi, r_lo);
}
function _mul(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 r_hi, uint256 r_lo) {
assembly ("memory-safe") {
let mm := mulmod(x_lo, y, not(0x00))
r_lo := mul(x_lo, y)
r_hi := add(mul(x_hi, y), sub(sub(mm, r_lo), lt(mm, r_lo)))
}
}
function omul(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, y);
return r.from(r_hi, r_lo);
}
function imul(uint512 r, uint256 y) internal pure returns (uint512) {
return omul(r, r, y);
}
function _mul(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo)
private
pure
returns (uint256 r_hi, uint256 r_lo)
{
assembly ("memory-safe") {
let mm := mulmod(x_lo, y_lo, not(0x00))
r_lo := mul(x_lo, y_lo)
r_hi := add(add(mul(x_hi, y_lo), mul(x_lo, y_hi)), sub(sub(mm, r_lo), lt(mm, r_lo)))
}
}
function omul(uint512 r, uint512 x, uint512 y) internal pure returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
(uint256 r_hi, uint256 r_lo) = _mul(x_hi, x_lo, y_hi, y_lo);
return r.from(r_hi, r_lo);
}
function imul(uint512 r, uint512 y) internal pure returns (uint512) {
return omul(r, r, y);
}
function mod(uint512 n, uint256 d) internal pure returns (uint256 r) {
if (d == 0) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
(uint256 n_hi, uint256 n_lo) = n.into();
assembly ("memory-safe") {
r := mulmod(n_hi, sub(0x00, d), d)
r := addmod(n_lo, r, d)
}
}
function omod(uint512 r, uint512 x, uint512 y) internal view returns (uint512) {
(uint256 x_hi, uint256 x_lo) = x.into();
(uint256 y_hi, uint256 y_lo) = y.into();
assembly ("memory-safe") {
// We use the MODEXP (5) precompile with an exponent of 1. We encode
// the arguments to the precompile at the beginning of free memory
// without allocating. Arguments are encoded as:
// [64 32 64 x_hi x_lo 1 y_hi y_lo]
let ptr := mload(0x40)
mstore(ptr, 0x40)
mstore(add(0x20, ptr), 0x20)
mstore(add(0x40, ptr), 0x40)
// See comment in `from` about why `mstore` is more efficient than `mcopy`
mstore(add(0x60, ptr), x_hi)
mstore(add(0x80, ptr), x_lo)
mstore(add(0xa0, ptr), 0x01)
mstore(add(0xc0, ptr), y_hi)
mstore(add(0xe0, ptr), y_lo)
// We write the result of MODEXP directly into the output space r.
pop(staticcall(gas(), 0x05, ptr, 0x100, r, 0x40))
// The MODEXP precompile can only fail due to out-of-gas. This call
// consumes only 200 gas, so if it failed, there is only 4 gas
// remaining in this context. Therefore, we will out-of-gas
// immediately when we attempt to read the result. We don't bother
// to check for failure.
}
return r;
}
function imod(uint512 r, uint512 y) internal view returns (uint512) {
return omod(r, r, y);
}
function irmod(uint512 r, uint512 y) internal view returns (uint512) {
return omod(r, y, r);
}
/// Multiply 512-bit [x_hi x_lo] by 256-bit [y] giving 768-bit [r_ex r_hi r_lo]
function _mul768(uint256 x_hi, uint256 x_lo, uint256 y)
private
pure
returns (uint256 r_ex, uint256 r_hi, uint256 r_lo)
{
assembly ("memory-safe") {
let mm0 := mulmod(x_lo, y, not(0x00))
r_lo := mul(x_lo, y)
let mm1 := mulmod(x_hi, y, not(0x00))
let r_partial := mul(x_hi, y)
r_ex := sub(sub(mm1, r_partial), lt(mm1, r_partial))
r_hi := add(r_partial, sub(sub(mm0, r_lo), lt(mm0, r_lo)))
// `lt(r_hi, r_partial)` indicates overflow in the addition to form
// `r_hi`. We can add the bool directly to the integer to perform
// carry.
r_ex := add(r_ex, lt(r_hi, r_partial))
}
}
//// The technique implemented in the following functions for division is
//// adapted from Remco Bloemen's work https://2π.com/21/muldiv/ .
//// The original code was released under the MIT license.
function _roundDown(uint256 x_hi, uint256 x_lo, uint256 d)
private
pure
returns (uint256 r_hi, uint256 r_lo, uint256 rem)
{
assembly ("memory-safe") {
// Get the remainder [n_hi n_lo] % d (< 2²⁵⁶ - 1)
// 2**256 % d = -d % 2**256 % d -- https://2π.com/17/512-bit-division/
rem := mulmod(x_hi, sub(0x00, d), d)
rem := addmod(x_lo, rem, d)
r_hi := sub(x_hi, gt(rem, x_lo))
r_lo := sub(x_lo, rem)
}
}
// TODO: remove and replace existing division operations with the Algorithm
// D variants
function _roundDown(uint256 x_hi, uint256 x_lo, uint256 d_hi, uint256 d_lo)
private
view
returns (uint256 r_hi, uint256 r_lo, uint256 rem_hi, uint256 rem_lo)
{
uint512 r;
assembly ("memory-safe") {
// We point `r` to the beginning of free memory WITHOUT allocating.
// This is not technically "memory-safe" because solc might use that
// memory for something in between the end of this assembly block
// and the beginning of the call to `into()`, but empirically and
// practically speaking that won't and doesn't happen. We save some
// gas by not bumping the free pointer.
r := mload(0x40)
// Get the remainder [x_hi x_lo] % [d_hi d_lo] (< 2⁵¹² - 1) We use
// the MODEXP (5) precompile with an exponent of 1. We encode the
// arguments to the precompile at the beginning of free memory
// without allocating. Conveniently, `r` already points to this
// region. Arguments are encoded as:
// [64 32 64 x_hi x_lo 1 d_hi d_lo]
mstore(r, 0x40)
mstore(add(0x20, r), 0x20)
mstore(add(0x40, r), 0x40)
mstore(add(0x60, r), x_hi)
mstore(add(0x80, r), x_lo)
mstore(add(0xa0, r), 0x01)
mstore(add(0xc0, r), d_hi)
mstore(add(0xe0, r), d_lo)
// The MODEXP precompile can only fail due to out-of-gas. This call
// consumes only 200 gas, so if it failed, there is only 4 gas
// remaining in this context. Therefore, we will out-of-gas
// immediately when we attempt to read the result. We don't bother
// to check for failure.
pop(staticcall(gas(), 0x05, r, 0x100, r, 0x40))
}
(rem_hi, rem_lo) = r.into();
// Round down by subtracting the remainder from the numerator
(r_hi, r_lo) = _sub(x_hi, x_lo, rem_hi, rem_lo);
}
function _twos(uint256 x) private pure returns (uint256 twos, uint256 twosInv) {
assembly ("memory-safe") {
// Compute largest power of two divisor of `x`. `x` is nonzero, so
// this is always ≥ 1.
twos := and(sub(0x00, x), x)
// To shift up (bits from the high limb into the low limb) we need
// the inverse of `twos`. That is, 2²⁵⁶ / twos.
// 2**256 / twos = -twos % 2**256 / twos + 1 -- https://2π.com/17/512-bit-division/
// If `twos` is zero, then `twosInv` becomes one (not possible)
twosInv := add(div(sub(0x00, twos), twos), 0x01)
}
}
function _toOdd256(uint256 x_hi, uint256 x_lo, uint256 y) private pure returns (uint256 x_lo_out, uint256 y_out) {
// Factor powers of two out of `y` and apply the same shift to [x_hi
// x_lo]
(uint256 twos, uint256 twosInv) = _twos(y);
assembly ("memory-safe") {
// Divide `y` by the power of two
y_out := div(y, twos)
// Divide [x_hi x_lo] by the power of two
x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv))
}
}
function _toOdd256(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo)
private
pure
returns (uint256 x_lo_out, uint256 y_lo_out)
{
// Factor powers of two out of `y_lo` and apply the same shift to `x_lo`
(uint256 twos, uint256 twosInv) = _twos(y_lo);
assembly ("memory-safe") {
// Divide [y_hi y_lo] by the power of two, returning only the low limb
y_lo_out := or(div(y_lo, twos), mul(y_hi, twosInv))
// Divide [x_hi x_lo] by the power of two, returning only the low limb
x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv))
}
}
function _toOdd512(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo)
private
pure
returns (uint256 x_hi_out, uint256 x_lo_out, uint256 y_hi_out, uint256 y_lo_out)
{
// Factor powers of two out of [y_hi y_lo] and apply the same shift to
// [x_hi x_lo] and [y_hi y_lo]
(uint256 twos, uint256 twosInv) = _twos(y_lo);
assembly ("memory-safe") {
// Divide [y_hi y_lo] by the power of two
y_hi_out := div(y_hi, twos)
y_lo_out := or(div(y_lo, twos), mul(y_hi, twosInv))
// Divide [x_hi x_lo] by the power of two
x_hi_out := div(x_hi, twos)
x_lo_out := or(div(x_lo, twos), mul(x_hi, twosInv))
}
}
function _invert256(uint256 d) private pure returns (uint256 inv) {
assembly ("memory-safe") {
// Invert `d` mod 2²⁵⁶ -- https://2π.com/18/multiplitcative-inverses/
// `d` is an odd number (from _toOdd*). It has an inverse modulo
// 2²⁵⁶ such that d * inv ≡ 1 mod 2²⁵⁶.
// We use Newton-Raphson iterations compute inv. Thanks to Hensel's
// lifting lemma, this also works in modular arithmetic, doubling
// the correct bits in each step. The Newton-Raphson-Hensel step is:
// inv_{n+1} = inv_n * (2 - d*inv_n) % 2**512
// To kick off Newton-Raphson-Hensel iterations, we start with a
// seed of the inverse that is correct correct for four bits.
// d * inv ≡ 1 mod 2⁴
inv := xor(mul(0x03, d), 0x02)
// Each Newton-Raphson-Hensel step doubles the number of correct
// bits in `inv`. After 6 iterations, full convergence is
// guaranteed.
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2⁸
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2¹⁶
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2³²
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2⁶⁴
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2¹²⁸
inv := mul(inv, sub(0x02, mul(d, inv))) // inverse mod 2²⁵⁶
}
}
// TODO: once the existing division routines are ported over to the
// Algorithm D variants (avoiding the use of the `MODEXP` precompile), this
// function is no longer needed.
function _invert512(uint256 d_hi, uint256 d_lo) private pure returns (uint256 inv_hi, uint256 inv_lo) {
// First, we get the inverse of `d` mod 2²⁵⁶
inv_lo = _invert256(d_lo);
// To extend this to the inverse mod 2⁵¹², we perform a more elaborate
// 7th Newton-Raphson-Hensel iteration with 512 bits of precision.
// tmp = d * inv_lo % 2**512
(uint256 tmp_hi, uint256 tmp_lo) = _mul(d_hi, d_lo, inv_lo);
// tmp = 2 - tmp % 2**512
(tmp_hi, tmp_lo) = _sub(0, 2, tmp_hi, tmp_lo);
assembly ("memory-safe") {
// inv_hi = inv_lo * tmp / 2**256 % 2**256
let mm := mulmod(inv_lo, tmp_lo, not(0x00))
inv_hi := add(mul(inv_lo, tmp_hi), sub(sub(mm, inv_lo), lt(mm, inv_lo)))
}
}
function _div(uint256 n_hi, uint256 n_lo, uint256 d) private pure returns (uint256) {
// Round the numerator down to a multiple of the denominator. This makes
// the division exact without affecting the result.
(n_hi, n_lo,) = _roundDown(n_hi, n_lo, d);
// Make `d` odd so that it has a multiplicative inverse mod 2²⁵⁶.
// After this we can discard `n_hi` because our result is only 256 bits
(n_lo, d) = _toOdd256(n_hi, n_lo, d);
// We perform division by multiplying by the multiplicative inverse of
// the denominator mod 2²⁵⁶. Since `d` is odd, this inverse
// exists. Compute that inverse
d = _invert256(d);
unchecked {
// Because the division is now exact (we rounded `n` down to a
// multiple of `d`), we perform it by multiplying with the modular
// inverse of the denominator. This is the correct result mod 2²⁵⁶.
return n_lo * d;
}
}
function _divUp(uint256 n_hi, uint256 n_lo, uint256 d) private pure returns (uint256) {
// Round the numerator down to a multiple of the denominator. This makes
// the division exact without affecting the result. Store the remainder
// for later to determine whether we must increment the result in order
// to round up.
uint256 rem;
(n_hi, n_lo, rem) = _roundDown(n_hi, n_lo, d);
// Make `d` odd so that it has a multiplicative inverse mod 2²⁵⁶.
// After this we can discard `n_hi` because our result is only 256 bits
(n_lo, d) = _toOdd256(n_hi, n_lo, d);
// We perform division by multiplying by the multiplicative inverse of
// the denominator mod 2²⁵⁶. Since `d` is odd, this inverse
// exists. Compute that inverse
d = _invert256(d);
unchecked {
// Because the division is now exact (we rounded `n` down to a
// multiple of `d`), we perform it by multiplying with the modular
// inverse of the denominator. This is the floor of the division,
// mod 2²⁵⁶. To obtain the ceiling, we conditionally add 1 if the
// remainder was nonzero.
return (n_lo * d).unsafeInc(0 < rem);
}
}
function unsafeDiv(uint512 n, uint256 d) internal pure returns (uint256) {
(uint256 n_hi, uint256 n_lo) = n.into();
if (n_hi == 0) {
return n_lo.unsafeDiv(d);
}
return _div(n_hi, n_lo, d);
}
function div(uint512 n, uint256 d) internal pure returns (uint256) {
if (d == 0) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return unsafeDiv(n, d);
}
function unsafeDivUp(uint512 n, uint256 d) internal pure returns (uint256) {
(uint256 n_hi, uint256 n_lo) = n.into();
if (n_hi == 0) {
return n_lo.unsafeDivUp(d);
}
return _divUp(n_hi, n_lo, d);
}
function divUp(uint512 n, uint256 d) internal pure returns (uint256) {
if (d == 0) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return unsafeDivUp(n, d);
}
function _gt(uint256 x_hi, uint256 x_lo, uint256 y_hi, uint256 y_lo) private pure returns (bool r) {
assembly ("memory-safe") {
r := or(gt(x_hi, y_hi), and(eq(x_hi, y_hi), gt(x_lo, y_lo)))
}
}
function div(uint512 n, uint512 d) internal view returns (uint256) {
(uint256 d_hi, uint256 d_lo) = d.into();
if (d_hi == 0) {
return div(n, d_lo);
}
(uint256 n_hi, uint256 n_lo) = n.into();
if (d_lo == 0) {
return n_hi.unsafeDiv(d_hi);
}
if (_gt(d_hi, d_lo, n_hi, n_lo)) {
// TODO: this optimization may not be overall optimizing
return 0;
}
// Round the numerator down to a multiple of the denominator. This makes
// the division exact without affecting the result.
(n_hi, n_lo,,) = _roundDown(n_hi, n_lo, d_hi, d_lo);
// Make `d_lo` odd so that it has a multiplicative inverse mod 2²⁵⁶.
// After this we can discard `n_hi` and `d_hi` because our result is
// only 256 bits
(n_lo, d_lo) = _toOdd256(n_hi, n_lo, d_hi, d_lo);
// We perform division by multiplying by the multiplicative inverse of
// the denominator mod 2²⁵⁶. Since `d_lo` is odd, this inverse
// exists. Compute that inverse
d_lo = _invert256(d_lo);
unchecked {
// Because the division is now exact (we rounded `n` down to a
// multiple of `d`), we perform it by multiplying with the modular
// inverse of the denominator. This is the correct result mod 2²⁵⁶.
return n_lo * d_lo;
}
}
function divUp(uint512 n, uint512 d) internal view returns (uint256) {
(uint256 d_hi, uint256 d_lo) = d.into();
if (d_hi == 0) {
return divUp(n, d_lo);
}
(uint256 n_hi, uint256 n_lo) = n.into();
if (d_lo == 0) {
return n_hi.unsafeDiv(d_hi).unsafeInc(0 < (n_lo | n_hi.unsafeMod(d_hi)));
}
// Round the numerator down to a multiple of the denominator. This makes
// the division exact without affecting the result. Save the remainder
// for later to determine whether we need to increment to round up.
uint256 rem_hi;
uint256 rem_lo;
(n_hi, n_lo, rem_hi, rem_lo) = _roundDown(n_hi, n_lo, d_hi, d_lo);
// Make `d_lo` odd so that it has a multiplicative inverse mod 2²⁵⁶.
// After this we can discard `n_hi` and `d_hi` because our result is
// only 256 bits
(n_lo, d_lo) = _toOdd256(n_hi, n_lo, d_hi, d_lo);
// We perform division by multiplying by the multiplicative inverse of
// the denominator mod 2²⁵⁶. Since `d_lo` is odd, this inverse
// exists. Compute that inverse
d_lo = _invert256(d_lo);
unchecked {
// Because the division is now exact (we rounded `n` down to a
// multiple of `d`), we perform it by multiplying with the modular
// inverse of the denominator. This is the floor of the division,
// mod 2²⁵⁶. To obtain the ceiling, we conditionally add 1 if the
// remainder was nonzero.
return (n_lo * d_lo).unsafeInc(0 < (rem_hi | rem_lo));
}
}
function odiv(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) {
if (y == 0) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
(uint256 x_hi, uint256 x_lo) = x.into();
if (x_hi == 0) {
return r.from(0, x_lo.unsafeDiv(y));
}
// The upper word of the quotient is straightforward. We can use
// "normal" division to obtain it. The remainder after that division
// must be carried forward to the later steps, however, because the next
// operation we perform is a `mulmod` of `x_hi` with `y`, there's no
// need to reduce `x_hi` mod `y` as would be ordinarily expected.
uint256 r_hi = x_hi.unsafeDiv(y);
// Round the numerator down to a multiple of the denominator. This makes
// the division exact without affecting the result.
(x_hi, x_lo,) = _roundDown(x_hi, x_lo, y);
// Make `y` odd so that it has a multiplicative inverse mod 2²⁵⁶. After
// this we can discard `x_hi` because we have already obtained the upper
// word.
(x_lo, y) = _toOdd256(x_hi, x_lo, y);
// The lower word of the quotient is obtained from division by
// multiplying by the multiplicative inverse of the denominator mod
// 2²⁵⁶. Since `y` is odd, this inverse exists. Compute that inverse
y = _invert256(y);
uint256 r_lo;
unchecked {
// Because the division is now exact (we rounded `x` down to a
// multiple of the original `y`), we perform it by multiplying with
// the modular inverse of the denominator. This is the correct
// result mod 2²⁵⁶.
r_lo = x_lo * y;
}
return r.from(r_hi, r_lo);
}
function idiv(uint512 r, uint256 y) internal pure returns (uint512) {
return odiv(r, r, y);
}
function odivUp(uint512 r, uint512 x, uint256 y) internal pure returns (uint512) {
if (y == 0) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
(uint256 x_hi, uint256 x_lo) = x.into();
if (x_hi == 0) {
return r.from(0, x_lo.unsafeDivUp(y));