-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain256.cpp
More file actions
843 lines (696 loc) · 21.9 KB
/
main256.cpp
File metadata and controls
843 lines (696 loc) · 21.9 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
#include <bitset>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>
#include <locale>
#include <sstream>
#include <string>
#include "uint256.hpp"
namespace {
using u256::uint256;
struct ios_flags_guard {
std::ios& os;
std::ios::fmtflags flags;
char fill;
std::streamsize precision;
explicit ios_flags_guard(std::ios& s)
: os(s)
, flags(s.flags())
, fill(s.fill())
, precision(s.precision()) {}
~ios_flags_guard() {
os.flags(flags);
os.fill(fill);
os.precision(precision);
}
};
void print_limbs_be(const uint256& v, const char* label) {
ios_flags_guard g(std::cout);
std::cout << label << " limbs [w3 w2 w1 w0]: [";
std::cout << std::hex << std::showbase << v.data()[3] << " " << v.data()[2]
<< " " << v.data()[1] << " " << v.data()[0] << "]\n";
}
void print_bytes(const std::uint8_t b[32], const char* label) {
ios_flags_guard g(std::cout);
std::cout << label << " bytes: ";
std::cout << std::hex << std::setfill('0');
for (int i = 0; i < 32; ++i) {
std::cout << std::setw(2) << static_cast<unsigned>(b[i]);
if (i == 15) std::cout << " ";
}
std::cout << std::dec << "\n";
}
// Build a std::bitset<256> from the underlying 4x64-bit limbs (little-endian).
std::bitset<256> to_bitset(const uint256& x) {
std::bitset<256> bs;
const auto* p = x.data();
for (std::size_t limb = 0; limb < uint256::size(); ++limb) {
std::uint64_t v = p[limb];
for (int b = 0; b < 64; ++b) {
const std::size_t idx = limb * 64u + static_cast<std::size_t>(b);
bs.set(idx, (v >> b) & 1u);
}
}
return bs;
}
uint256 pow2(unsigned k) {
uint256 x{1};
x <<= k;
return x;
}
void print_banner(const char* title) {
std::cout << "\n=== " << title << " ===\n";
}
void test_basic() {
print_banner("basic / bool / comparisons");
const uint256 z{0};
const uint256 one{1};
const uint256 two{2};
assert(z.is_zero());
assert(!static_cast<bool>(z));
assert(static_cast<bool>(one));
assert(!z);
assert(!(!one));
assert(z == uint256{0});
assert(one != two);
assert(one < two);
assert(two > one);
assert(one <= one);
assert(two >= one);
std::cout << "ok\n";
}
void test_add_sub_inc_dec() {
print_banner("add/sub/inc/dec");
uint256 a{0};
++a;
assert(a == uint256{1});
a++;
assert(a == uint256{2});
--a;
assert(a == uint256{1});
a--;
assert(a == uint256{0});
// carry across limbs: (2^64 - 1) + 1 = 2^64
uint256 x{};
x.data()[0] = ~std::uint64_t{0};
x += uint256{1};
assert(x.data()[0] == 0);
assert(x.data()[1] == 1);
// borrow across limbs: 2^64 - 1
x -= uint256{1};
assert(x.data()[0] == ~std::uint64_t{0});
assert(x.data()[1] == 0);
// modulo wrap: 0 - 1 == 2^256 - 1
uint256 w{0};
w -= uint256{1};
for (std::size_t i = 0; i < uint256::size(); ++i) {
assert(w.data()[i] == ~std::uint64_t{0});
}
std::cout << "ok\n";
}
void test_bitwise_and_shifts() {
print_banner("bitwise / shifts");
uint256 a{};
a.data()[0] = 0x0123456789abcdefULL;
a.data()[1] = 0xfedcba9876543210ULL;
uint256 b{};
b.data()[0] = 0xffff0000ffff0000ULL;
b.data()[1] = 0x0000ffff0000ffffULL;
const uint256 andv = a & b;
const uint256 orv = a | b;
const uint256 xrv = a ^ b;
const uint256 notv = ~a;
assert((andv | xrv) == orv);
assert((a ^ a).is_zero());
assert((~notv) == a);
// shifting 1 by various amounts
for (unsigned k : {0u, 1u, 63u, 64u, 65u, 127u, 128u, 255u}) {
const uint256 p = pow2(k);
uint256 q = p;
q >>= k;
assert(q == uint256{1});
}
// cross-limb shift check
uint256 s{1};
s <<= 64;
assert(s.data()[0] == 0);
assert(s.data()[1] == 1);
s >>= 1;
assert(s.data()[0] == (1ULL << 63));
assert(s.data()[1] == 0);
std::cout << "ok\n";
}
void test_mul() {
print_banner("multiplication");
const uint256 a = pow2(200) + uint256{12345};
const uint256 b = pow2(120) + uint256{67890};
const uint256 c = a * b;
// sanity: c / a == b when exact? Not exact due to low-term mixing, so test
// via distributive pieces:
const uint256 a0{12345};
const uint256 a1 = pow2(200);
const uint256 b0{67890};
const uint256 b1 = pow2(120);
const uint256 expected = (a1 * b1) + (a1 * b0) + (a0 * b1) + (a0 * b0);
assert(c == expected);
// modulo behavior: (2^255 * 2) wraps to 0 (since 2^256 == 0 mod 2^256)
const uint256 m = pow2(255);
assert((m * uint256{2}).is_zero());
std::cout << "ok\n";
}
void test_div_mod_small() {
print_banner("division/modulo");
// exact division
const uint256 n = pow2(200) + pow2(123) + uint256{999};
const uint256 d{7};
const uint256 q = n / d;
const uint256 r = n % d;
assert(n == q * d + r);
assert(r < d);
// divide by 1
assert((n / uint256{1}) == n);
assert((n % uint256{1}).is_zero());
// n < d
const uint256 small{5};
const uint256 big{9};
assert((small / big).is_zero());
assert((small % big) == small);
std::cout << "ok\n";
}
void test_stream_io() {
print_banner("stream I/O");
// Compose a value with all limbs touched.
uint256 x{};
x.data()[0] = 0x0123456789abcdefULL;
x.data()[1] = 0xfedcba9876543210ULL;
x.data()[2] = 0x0f0e0d0c0b0a0908ULL;
x.data()[3] = 0x8070605040302010ULL;
// hex output (showbase + uppercase)
{
std::ostringstream oss;
oss << std::showbase << std::uppercase << std::hex << x;
const std::string s = oss.str();
assert(s.size() >= 3);
assert(s[0] == '0' && (s[1] == 'X'));
}
// round-trip via hex input
{
std::ostringstream oss;
oss << std::hex << x;
const std::string hexs = oss.str();
std::istringstream iss(hexs);
iss >> std::hex;
uint256 y{};
iss >> y;
assert(iss);
assert(y == x);
}
// decimal output then input (base 10)
{
std::ostringstream oss;
oss << std::dec << x;
const std::string decs = oss.str();
std::istringstream iss(decs);
uint256 y{};
iss >> y;
assert(iss);
assert(y == x);
}
// oct output then input (base 8)
{
std::ostringstream oss;
oss << std::oct << x;
const std::string octs = oss.str();
std::istringstream iss(octs);
iss >> std::oct;
uint256 y{};
iss >> y;
assert(iss);
assert(y == x);
}
std::cout << "ok\n";
}
void test_literal_and_bitset() {
print_banner("literal + bitset interop");
using namespace u256::literals;
const uint256 a = "0x1"_u256;
const uint256 b = "123456789"_u256;
assert(a == uint256{1});
assert(b == uint256{123456789});
const uint256 x = (pow2(255) + uint256{1});
const auto bs = to_bitset(x);
assert(bs.test(0));
assert(bs.test(255));
assert(bs.count() == 2);
std::cout << "ok\n";
}
void test_bit_queries() {
print_banner("bit queries (<bit> vocabulary)");
// zero
{
const uint256 z{0};
assert(z.popcount() == 0u);
assert(z.countl_zero() == 256u);
assert(z.countr_zero() == 256u);
assert(z.bit_width() == 0u);
assert(z.msb_index() == -1);
}
// one
{
const uint256 o{1};
assert(o.popcount() == 1u);
assert(o.countl_zero() == 255u);
assert(o.countr_zero() == 0u);
assert(o.bit_width() == 1u);
assert(o.msb_index() == 0);
}
// powers of two
for (unsigned k : {0u, 1u, 63u, 64u, 65u, 127u, 128u, 129u, 200u, 255u}) {
const uint256 x = pow2(k);
assert(x.popcount() == 1u);
assert(x.countr_zero() == static_cast<std::uint32_t>(k));
assert(x.bit_width() == static_cast<std::uint32_t>(k + 1u));
assert(x.msb_index() == static_cast<std::int32_t>(k));
}
// mixed bits: build using public ops only
{
const uint256 x =
(uint256{1} << 0) | (uint256{1} << 5) | (uint256{1} << 200);
assert(x.popcount() == 3u);
assert(x.countr_zero() == 0u);
assert(x.bit_width() == 201u);
assert(x.msb_index() == 200);
}
// all ones
{
uint256 x{};
for (std::size_t i = 0; i < uint256::size(); ++i) {
x.data()[i] = ~std::uint64_t{0};
}
assert(x.popcount() == 256u);
assert(x.countl_zero() == 0u);
assert(x.countr_zero() == 0u);
assert(x.bit_width() == 256u);
assert(x.msb_index() == 255);
}
std::cout << "ok\n";
}
// ---- randomized/property tests ----
struct splitmix64 {
std::uint64_t s;
explicit splitmix64(std::uint64_t seed)
: s(seed) {}
std::uint64_t next_u64() {
std::uint64_t z = (s += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
unsigned next_u32() { return static_cast<unsigned>(next_u64()); }
};
uint256 random_u256(splitmix64& rng) {
uint256 x{};
auto* p = x.data();
for (std::size_t i = 0; i < uint256::size(); ++i) p[i] = rng.next_u64();
return x;
}
uint256 random_nonzero_u256(splitmix64& rng) {
for (;;) {
uint256 x = random_u256(rng);
if (x) return x;
}
}
uint256 random_small_u256(splitmix64& rng) {
const unsigned bits = rng.next_u32() % 128;
uint256 x = random_u256(rng);
if (bits < 256) x >>= (256 - bits);
return x;
}
void test_properties_random() {
print_banner("randomized properties");
splitmix64 rng{0x123456789abcdef0ULL};
constexpr int N = 2000;
for (int i = 0; i < N; ++i) {
const uint256 a = random_u256(rng);
const uint256 b = random_u256(rng);
const uint256 c = random_u256(rng);
assert(a + b == b + a);
assert((a + b) + c == a + (b + c));
assert((a ^ a).is_zero());
assert((a ^ b) ^ (b == a));
assert(~(a & b) == (~a | ~b));
assert(~(a | b) == (~a & ~b));
assert(a * (b + c) == (a * b) + (a * c));
const unsigned k = rng.next_u32() % 256;
const uint256 p = pow2(k);
uint256 t = p;
t >>= k;
assert(t == uint256{1});
}
for (int i = 0; i < 400; ++i) {
const uint256 n = random_small_u256(rng);
const uint256 d = random_nonzero_u256(rng);
const uint256 q = n / d;
const uint256 r = n % d;
assert(n == q * d + r);
assert(r < d);
}
std::cout << "ok\n";
}
void test_vs_u64_random() {
print_banner("randomized cross-check vs uint64_t (low limb)");
splitmix64 rng{0x0fedcba987654321ULL};
constexpr int N = 5000;
for (int i = 0; i < N; ++i) {
const std::uint64_t a64 = rng.next_u64();
const std::uint64_t b64 = rng.next_u64();
const std::uint64_t c64 = (rng.next_u64() | 1ULL);
const uint256 a{a64};
const uint256 b{b64};
const uint256 c{c64};
{
const uint256 s = a + b;
assert(s.data()[0] == static_cast<std::uint64_t>(a64 + b64));
const std::uint64_t carry =
(a64 > (std::numeric_limits<std::uint64_t>::max() - b64)) ? 1ULL
: 0ULL;
assert(s.data()[1] == carry);
assert(s.data()[2] == 0);
assert(s.data()[3] == 0);
}
{
const uint256 d = a - b;
assert(d.data()[0] == static_cast<std::uint64_t>(a64 - b64));
}
{
const uint256 m = a * b;
const unsigned __int128 prod = static_cast<unsigned __int128>(a64) *
static_cast<unsigned __int128>(b64);
assert(m.data()[0] == static_cast<std::uint64_t>(prod));
assert(m.data()[1] == static_cast<std::uint64_t>(prod >> 64));
assert(m.data()[2] == 0);
assert(m.data()[3] == 0);
}
{
const uint256 q = a / c;
const uint256 r = a % c;
assert(q.data()[1] == 0 && q.data()[2] == 0 && q.data()[3] == 0);
assert(r.data()[0] == static_cast<std::uint64_t>(a64 % c64));
assert((q * c + r) == a);
}
{
const unsigned sh = static_cast<unsigned>(rng.next_u32() % 64);
const uint256 sl = a << sh;
assert(sl.data()[0] == static_cast<std::uint64_t>(a64 << sh));
const uint256 sr = a >> sh;
assert(sr.data()[0] == static_cast<std::uint64_t>(a64 >> sh));
}
}
std::cout << "ok\n";
}
// ---- demo ----
void show_value(const char* name, const uint256& v) {
ios_flags_guard g(std::cout);
std::cout << name << " (hex): " << std::showbase << std::hex << v << "\n";
std::cout << name << " (dec): " << std::dec << v << "\n";
}
void demo() {
print_banner("demo (showcase + interop)");
using namespace u256::literals;
const uint256 x =
"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"_u256;
const uint256 y = pow2(200) + uint256{42};
// Show human-facing forms (MSB on the left).
show_value("x", x);
show_value("y", y);
const uint256 z = x + y;
show_value("z = x + y", z);
// ---- Representation demo: limbs vs bytes vs hex ----
std::cout << "\nrepresentation demo (note: printing is big-endian)\n";
print_limbs_be(x, "x");
std::uint8_t be[32]{};
std::uint8_t le[32]{};
x.to_bytes_be(be);
x.to_bytes_le(le);
print_bytes(be, "x (big-endian)");
print_bytes(le, "x (little-endian)");
// Round-trip bytes
const uint256 xb = uint256::from_bytes_be(be);
const uint256 xl = uint256::from_bytes_le(le);
assert(xb == x);
assert(xl == x);
// Hex string interop (big-endian string)
const std::string hx = x.to_hex_be(/*prefix=*/true, /*uppercase=*/false);
std::cout << "x.to_hex_be(): " << hx << "\n";
bool ok = false;
const uint256 xp = uint256::from_hex_be(hx, ok);
assert(ok);
assert(xp == x);
// Demonstrate that underscores are accepted (if you enabled it)
{
std::string hx2 = hx;
// insert a couple underscores in safe places
if (hx2.size() > 10) hx2.insert(10, "_");
if (hx2.size() > 30) hx2.insert(30, "_");
bool ok2 = false;
const uint256 xu = uint256::from_hex_be(hx2, ok2);
assert(ok2);
assert(xu == x);
std::cout << "from_hex_be() accepts '_' separators: ok\n";
}
// ---- Bitcoin-style “hash” display example ----
// A typical block hash is shown as 32 bytes, big-endian hex.
const std::string hash_hex =
"00000000000000000000144d46277fbe49c3216eeea45e85408b3465b88978d5";
assert(hash_hex.size() == 64); // demo invariant: “this is a 32-byte hash”
bool okh = false;
const uint256 h = uint256::from_hex_be(hash_hex, okh);
assert(okh);
std::uint8_t hbe[32]{};
h.to_bytes_be(hbe);
std::cout << "\nbitcoin-style hash example\n";
std::cout << "hash input: " << hash_hex << "\n";
std::cout << "hash parsed: " << h.to_hex_be(false, false) << "\n";
print_bytes(hbe, "hash (big-endian)");
assert(h.to_hex_be_fixed(false, false) == hash_hex); // exact round-trip
{
bool oks = false;
const uint256 s = uint256::from_hex_be("1", oks);
assert(oks);
assert(s == uint256{1});
std::cout << "short hex \"1\" parses as: " << std::showbase << std::hex
<< s << std::dec << "\n";
}
// ---- bitwise / shift / div demo (as before, but kept short) ----
{
// Carry across 64-bit boundary: (2^64 - 1) + 1 = 2^64
uint256 a{};
a.data()[0] = ~std::uint64_t{0};
const uint256 b{1};
const uint256 c = a + b;
ios_flags_guard g(std::cout);
std::cout << "\ncarry demo:\n";
std::cout << " a = " << std::showbase << std::hex << a << "\n";
std::cout << " b = " << std::showbase << std::hex << b << "\n";
std::cout << " c = a + b = " << std::showbase << std::hex << c << "\n";
std::cout << " c limbs: [" << std::hex << c.data()[3] << " "
<< c.data()[2] << " " << c.data()[1] << " " << c.data()[0]
<< "]\n";
}
{
ios_flags_guard g(std::cout);
std::cout << "\nshift boundaries:\n";
for (unsigned k : {63u, 64u, 65u, 127u, 128u, 129u}) {
uint256 t{1};
t <<= k;
std::cout << " 1<<" << std::dec << k << " = " << std::showbase
<< std::hex << t << "\n";
}
}
{
const uint256 n = x;
const uint256 d{97};
const uint256 q = n / d;
const uint256 r = n % d;
ios_flags_guard g(std::cout);
std::cout << "\ndiv/mod demo:\n";
std::cout << " n = " << std::showbase << std::hex << n << "\n";
std::cout << " d = " << std::dec << 97 << "\n";
std::cout << " q = n / d = " << std::showbase << std::hex << q << "\n";
std::cout << " r = n % d = " << std::dec << r << "\n";
assert(n == q * d + r);
}
{
const auto bs = to_bitset(y);
std::cout << "\nbitset demo:\n";
std::cout << " y popcount: " << bs.count() << "\n";
std::cout << " y bit 200: " << bs.test(200) << "\n";
std::cout << " y bit 0: " << bs.test(0) << "\n";
}
}
// Function to expand bitcoin compact target format to uint256
uint256 expand_compact_target(uint32_t compact) {
uint32_t exponent = (compact >> 24) & 0xff;
uint32_t coefficient = compact & 0x007fffff;
uint256 target;
if (exponent <= 3) {
target = coefficient >> (8 * (3 - exponent));
} else {
target = uint256(coefficient) * (uint256(1) << (8 * (exponent - 3)));
}
return target;
}
std::string trim_trailing_zeros(std::string s) {
const auto pos = s.find('.');
if (pos == std::string::npos) return s;
// Remove trailing zeros
while (!s.empty() && s.back() == '0') {
s.pop_back();
}
// Remove trailing decimal point if needed
if (!s.empty() && s.back() == '.') {
s.pop_back();
}
return s;
}
void bitcoin_sha256() {
print_banner("Bitcoin/SHA-256 Demo");
using namespace u256::literals;
uint32_t initial_compact_target{0x1d00ffffu};
uint32_t compact_target{0x1701ebf2u};
uint256 initial_target = expand_compact_target(initial_compact_target);
uint256 target = expand_compact_target(compact_target);
long double difficulty = static_cast<long double>(initial_target) /
static_cast<long double>(target);
uint256 block_hash{
"0x00000000000000000000edc8c459660bd1962f095703a754d23e81cd68f4551e"_u256};
bool block_hash_lt_target{block_hash < target};
std::string lt_target{block_hash_lt_target ? "true" : "false"};
{
ios_flags_guard g(std::cout);
std::cout << std::hex
<< " Initial Compact Target: " << initial_compact_target
<< "\n"
<< " Compact Target: " << compact_target << "\n";
}
std::cout << " Initial Target: " << initial_target.to_hex_be_fixed() << "\n"
<< " Target : " << target.to_hex_be_fixed() << "\n"
<< " Block Hash : " << block_hash.to_hex_be_fixed() << "\n"
<< " Block Hash Less Than Target: " << lt_target << "\n\n";
{
ios_flags_guard g(std::cout);
std::ostringstream oss;
oss.imbue(std::locale(""));
oss << std::fixed
<< std::setprecision(std::numeric_limits<long double>::digits10)
<< difficulty;
std::cout << " Difficulty : " << trim_trailing_zeros(oss.str())
<< "\n\n";
}
}
template<class F>
std::uint64_t time_it_us(F&& f) {
using clock = std::chrono::steady_clock;
const auto t0 = clock::now();
f();
const auto t1 = clock::now();
return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count());
}
void micro_bench() {
print_banner("micro-bench (rough)");
// Keep it deterministic.
splitmix64 rng{0xdeadbeefcafebabeULL};
constexpr int N = 20000;
uint256 acc{0};
uint256 a = random_u256(rng);
uint256 b = random_u256(rng);
uint256 c = random_nonzero_u256(rng);
const auto add_us = time_it_us([&] {
for (int i = 0; i < N; ++i) {
a = a + b;
acc ^= a;
b = random_u256(rng);
}
});
const auto mul_us = time_it_us([&] {
for (int i = 0; i < N; ++i) {
a = a * b;
acc ^= a;
b = random_u256(rng);
}
});
// General division (mostly slow path: random 256-bit divisors)
constexpr int Nd = 2000;
const auto div_us = time_it_us([&] {
for (int i = 0; i < Nd; ++i) {
a = a / c;
acc ^= a;
c = random_nonzero_u256(rng);
}
});
// Fast path: small 64-bit divisor
constexpr int Nd_small = 20000;
const uint256 d_small{97};
const auto div_small_us = time_it_us([&] {
uint256 t = a;
uint256 acc2{0};
for (int i = 0; i < Nd_small; ++i) {
t = t / d_small;
acc2 ^= t;
t += uint256{1};
}
if (!acc2.is_zero()) {
// keep
}
});
// Fast path: power-of-two divisor
constexpr int Nd_pow2 = 20000;
const uint256 d_pow2 = pow2(137);
const auto div_pow2_us = time_it_us([&] {
uint256 t = a;
uint256 acc3{0};
for (int i = 0; i < Nd_pow2; ++i) {
t = t / d_pow2;
acc3 ^= t;
t += uint256{1};
}
if (!acc3.is_zero()) {
// keep
}
});
// Prevent “optimized away”.
if (!acc.is_zero()) {
// do nothing
}
std::cout << " add/xor : " << add_us << " us for " << N
<< " iterations\n";
std::cout << " mul/xor : " << mul_us << " us for " << N
<< " iterations\n";
std::cout << " div/xor : " << div_us << " us for " << Nd
<< " iterations\n";
std::cout << " div by 97 : " << div_small_us << " us for " << Nd_small
<< " iterations\n";
std::cout << " div by 2^137 : " << div_pow2_us << " us for " << Nd_pow2
<< " iterations\n";
}
} // namespace
int main() {
test_basic();
test_add_sub_inc_dec();
test_bitwise_and_shifts();
test_mul();
test_div_mod_small();
test_stream_io();
test_literal_and_bitset();
test_properties_random();
test_vs_u64_random();
test_bit_queries();
demo();
bitcoin_sha256();
micro_bench();
std::cout << "\nAll tests passed.\n";
}