-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompressionAlgo.cpp
More file actions
6412 lines (5247 loc) · 243 KB
/
Copy pathcompressionAlgo.cpp
File metadata and controls
6412 lines (5247 loc) · 243 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
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Standard Library — I/O and String Handling
//----------------------------------------------------------------------------------
#include <fstream> // file stream read/write (keys.db, xor.db, README, etc.)
#include <iomanip> // stream formatting (setw, setprecision, hex)
#include <iostream> // console I/O
#include <sstream> // string streams for parsing/building output
#include <string> // std::string
//----------------------------------------------------------------------------------
// Standard Library — Containers
//----------------------------------------------------------------------------------
#include <algorithm> // sort, find, transform, etc.
#include <array> // fixed-size arrays (ring buffers, hash state)
#include <bitset> // fixed-width bit sequences
#include <deque> // double-ended queue
#include <map> // ordered key/value store
#include <optional> // nullable return values
#include <queue> // FIFO queue (order queue, command queue)
#include <set> // ordered unique elements
#include <unordered_map> // hash map
#include <unordered_set> // hash set
#include <utility> // std::pair, std::move, std::swap
#include <vector> // dynamic array
//----------------------------------------------------------------------------------
// Standard Library — Numerics and Math
//----------------------------------------------------------------------------------
#include <cmath> // math functions (used in NIST test suite, FFT, etc.)
#include <cstdint> // fixed-width integer types (uint8_t, uint64_t, ...)
#include <cstdlib> // general utilities (rand, exit, strtol)
#include <ctime> // time_t, timing utilities
#include <random> // std::mt19937 and friends (non-cryptographic RNG needs)
//----------------------------------------------------------------------------------
// Standard Library — Memory and Characters
//----------------------------------------------------------------------------------
#include <cctype> // character classification (isalpha, isdigit, ...)
#include <cstdio> // C-style I/O (snprintf, etc.)
#include <cstring> // C-style string/memory ops (memcpy, memset)
#include <locale> // locale-aware formatting
//----------------------------------------------------------------------------------
// Standard Library — Multithreading
//----------------------------------------------------------------------------------
#include <atomic> // std::atomic (uiRunning, thread-safe flags)
#include <condition_variable> // thread signalling
#include <functional> // std::function (callbacks, command dispatch)
#include <future> // std::future/async
#include <mutex> // mutual exclusion locks
#include <shared_mutex> // reader/writer locks
#include <thread> // std::thread (UI thread, trading loop thread)
//----------------------------------------------------------------------------------
// Standard Library — Time
//----------------------------------------------------------------------------------
#include <chrono> // durations, clocks, frame timing
//----------------------------------------------------------------------------------
// Standard Library — Exceptions and Utilities
//----------------------------------------------------------------------------------
#include <stdexcept> // std::runtime_error, std::invalid_argument, ...
//----------------------------------------------------------------------------------
// Standard Library — File System
//----------------------------------------------------------------------------------
#include <filesystem> // path handling, per-user file layout (FileSystem class)
//----------------------------------------------------------------------------------
// Windows — Console, Input, and OS APIs
//----------------------------------------------------------------------------------
#ifdef _WIN32
#include <windows.h> // ANSI escape enabling, console buffer sizing, VirtualLock
#include <conio.h> // _kbhit / _getch — raw keyboard input for the UI loop
#endif
//----------------------------------------------------------------------------------
// Type Aliases
//----------------------------------------------------------------------------------
using Bytes = std::vector<uint8_t>;
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Macros: Version
//----------------------------------------------------------------------------------
#define CLIENT_VERSION "0.1.0"
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Windows Specific Utilities
//----------------------------------------------------------------------------------
class WindowsUtilities {
public:
void showCursor() {
#ifdef _WIN32
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = TRUE;
SetConsoleCursorInfo(hConsole, &info);
#endif
}
static inline int getConsoleWidth() {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) {
return csbi.srWindow.Right - csbi.srWindow.Left + 1;
}
return 80; // fallback width
#else
return 80;
#endif
}
void maximizeConsoleWindow() {
#ifdef _WIN32
HWND consoleWindow = GetConsoleWindow();
if (consoleWindow != nullptr) {
ShowWindow(consoleWindow, SW_MAXIMIZE);
}
#endif
}
void hideCursor() {
#ifdef _WIN32
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.dwSize = 100;
info.bVisible = FALSE;
SetConsoleCursorInfo(hConsole, &info);
#endif
}
bool enableAnsiEscapes() {
#ifdef _WIN32
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
if (!GetConsoleMode(hOut, &mode))
return false;
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
return SetConsoleMode(hOut, mode) != 0;
#else
return true;
#endif
}
void fitBufferToWindow() {
#ifdef _WIN32
// Remove horizontal scrollbar only — don't touch buffer height
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hOut, &csbi);
int w = csbi.srWindow.Right - csbi.srWindow.Left + 1;
// Only shrink buffer width to window width, leave height alone
COORD bufferSize = {(SHORT)w, csbi.dwSize.Y};
SetConsoleScreenBufferSize(hOut, bufferSize);
#endif
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Global Enums
//----------------------------------------------------------------------------------
enum class Align { LEFT, CENTER, RIGHT };
enum class Page { HOME, COMPRESSOR };
enum class InputMode { COMMAND };
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Global Structs
//----------------------------------------------------------------------------------
struct ConsoleSize {
int width;
int height;
};
ConsoleSize getConsoleSize() {
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return {csbi.srWindow.Right - csbi.srWindow.Left + 1, csbi.srWindow.Bottom - csbi.srWindow.Top + 1};
}
struct Line {
std::string text;
Align alignment = Align::LEFT;
};
struct SymbolEntry {
uint16_t wordId;
std::vector<uint16_t> positions;
};
struct ByteEntry {
uint8_t byteValue;
std::vector<uint16_t> positions;
};
struct BlockMeta {
char state;
uint32_t symbolPosition;
};
struct Layer {
size_t index = 0;
size_t inputBits = 0;
size_t outputBits = 0;
};
struct EncodingMeta {
int wordIdBytes;
int positionBytes;
};
struct EncodingResult {
std::vector<SymbolEntry> symbols;
std::vector<uint8_t> bytes;
EncodingMeta meta;
std::string binary;
};
struct BinaryEncodingResult {
std::vector<ByteEntry> entries;
std::vector<uint8_t> bytes;
std::string binary;
};
struct HuffmanResults {
std::vector<uint8_t> inputBytes;
std::string finalBinaryPackage; // ASCII '0'/'1' debug form -- keep for display only
std::vector<uint8_t> packedBytes; // actual on-disk/serializable form
uint8_t paddingBits = 0; // trailing pad bits in packedBytes.back()
std::string selectedCodec;
size_t inputBits = 0;
size_t outputBits = 0;
std::unordered_map<uint8_t, std::string> huffmanCode;
};
struct RLEEntry {
uint8_t value;
uint8_t count;
};
struct RLEResult {
std::vector<RLEEntry> entries;
std::vector<uint8_t> bytes;
};
struct TransitionEntry {
uint8_t toPair;
uint32_t gap;
};
struct TransitionStream {
uint8_t startPair;
std::vector<TransitionEntry> transitions;
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Global Struct for Compression Algorithm
//----------------------------------------------------------------------------------
struct CompressionState {
enum class Stage { MENU, AWAITING_TEXT, DECODE_PROMPT };
Stage stage = Stage::MENU;
std::vector<std::string> statusLines;
static constexpr size_t maxStatusLines = 6;
void addStatus(const std::string &line) {
statusLines.push_back(line);
if (statusLines.size() > maxStatusLines)
statusLines.erase(statusLines.begin());
}
void reset() {
stage = Stage::MENU;
statusLines.clear();
}
// BlockData output
std::vector<BlockMeta> blocks;
std::string blockStates; // one char per block, e.g. "010" for 3 blocks
std::string blockPadPairs; // two chars per block, e.g. "000110" for 3 blocks ("00","01","10")
std::vector<uint32_t> hashPositions;
std::string bitPairs;
// OrderHeader output
std::vector<uint32_t> headerPositions;
std::vector<uint8_t> headerGaps;
HuffmanResults headerGapCanonical;
std::string headerPacked;
// OrderFooter output
std::vector<uint8_t> hashGaps;
std::vector<uint8_t> sumValue;
std::string hashGapBits;
std::vector<uint8_t> run;
HuffmanResults hashGapCanonical;
HuffmanResults hashGapCanonicalDouble;
std::string footerPacked;
std::string footerCodec;
// OrderBody output
HuffmanResults bitPairsHuffman;
std::string bodyPacked;
// GENERIC HUFFMAN OUTPUT
std::string selectedCodec;
std::string outputBits;
size_t outputBitsSize = 0;
std::unordered_map<uint8_t, std::string> huffmanCode;
// GENERAL HUFFMAN
HuffmanResults huffman;
std::vector<RLEEntry> rleEntries;
// ENCODING RESULTS
std::vector<SymbolEntry> encoded;
std::vector<uint8_t> bytes;
std::vector<ByteEntry> byteEntries;
bool isText = true;
size_t originalBits = 0;
size_t afterRleBits = 0;
size_t afterBinBits = 0;
size_t afterHuffmanBits = 0;
double compressionRatio = 0.0;
// ENCODED LAYERS
std::string eBits;
std::string dBits;
std::string header;
std::string body;
size_t p0 = 0;
size_t p1 = 0;
size_t p2 = 0;
size_t p3 = 0;
// FINALIZATION
std::vector<Layer> layers;
size_t targetBits = 0;
size_t zeroPadding = 0;
bool fitsTarget = false;
std::string finalizedBits;
// RESET BY BLOCKDATA
void resetBlockAnalysis() {
blockStates.clear();
bitPairs.clear();
blocks.clear();
hashPositions.clear();
hashGaps.clear();
hashGapBits.clear();
hashGapCanonical = {};
bitPairsHuffman = {};
headerPositions.clear();
headerGaps.clear();
headerGapCanonical = {};
}
// RESET BY LAYEREDCOMPRESSION
void resetForRun(const std::string &eBits_, size_t targetBits_) {
resetBlockAnalysis();
dBits.clear();
header.clear();
body.clear();
finalizedBits.clear();
layers.clear();
p0 = p1 = p2 = p3 = 0;
zeroPadding = 0;
fitsTarget = false;
eBits = eBits_;
targetBits = targetBits_;
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// File System
//----------------------------------------------------------------------------------
namespace fs = std::filesystem;
class FileSystem {
public:
static fs::path getLogPath() {
fs::path dir = "logs";
if (!fs::exists(dir))
fs::create_directories(dir);
return dir / "debug.log";
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Render
//----------------------------------------------------------------------------------
class Render {
public:
void pushLine(const std::string &txt, Align a = Align::LEFT) { bufferedLines.push_back({txt, a}); }
void flushToColumn(std::vector<Line> &column) {
column.insert(column.end(), bufferedLines.begin(), bufferedLines.end());
bufferedLines.clear();
}
void clearBuffer() { bufferedLines.clear(); }
void addEmptyLines(std::vector<Line> &col, int n) {
for (int i = 0; i < n; ++i)
col.push_back({"", Align::CENTER});
}
std::string makeLine(char c = '=') const { return std::string(consoleWidth(), c); }
std::string printColumns(const std::vector<std::vector<Line>> &columns, int spacing = 1, int padding = 0, int widthOverride = 0) const {
const int cw = widthOverride > 0 ? widthOverride : consoleWidth();
const int numCols = (int)std::max<size_t>(1, columns.size());
const int totalSpacing = spacing * (numCols - 1);
const int usableWidth = cw - (padding * 2) - totalSpacing;
const int colWidth = std::max(1, usableWidth / numCols);
const std::string leftPad(std::max(0, (cw - (colWidth * numCols + totalSpacing + padding * 2)) / 2), ' ');
std::vector<std::vector<std::string>> wrappedText(numCols);
std::vector<std::vector<Align>> wrappedAlign(numCols);
for (int c = 0; c < numCols; ++c) {
for (const auto &ln : columns[c]) {
auto &wt = wrappedText[c];
auto &wa = wrappedAlign[c];
if (ln.text.find_first_not_of(" \t\r\n") == std::string::npos) {
wt.push_back("");
wa.push_back(ln.alignment);
continue;
}
if ((int)ln.text.size() <= colWidth) {
wt.push_back(ln.text);
wa.push_back(ln.alignment);
continue;
}
std::istringstream iss(ln.text);
std::string word, current;
while (iss >> word) {
if (current.empty()) {
current = word;
} else if ((int)(current.size() + 1 + word.size()) <= colWidth) {
current += ' ' + word;
} else {
wt.push_back(current);
wa.push_back(ln.alignment);
current = word;
}
}
if (!current.empty()) {
wt.push_back(current);
wa.push_back(ln.alignment);
}
}
}
size_t maxLines = 0;
for (const auto &col : wrappedText)
maxLines = std::max(maxLines, col.size());
std::ostringstream oss;
for (size_t i = 0; i < maxLines; ++i) {
oss << leftPad;
for (int c = 0; c < numCols; ++c) {
const std::string &text = i < wrappedText[c].size() ? wrappedText[c][i] : "";
const Align a = i < wrappedAlign[c].size() ? wrappedAlign[c][i] : Align::LEFT;
oss << alignFragment(text, a, colWidth);
if (c < numCols - 1)
oss << std::string(spacing, ' ');
}
oss << '\n';
}
return oss.str();
}
// clang-format off
std::string printHeaderColumns (const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 0, 0); }
std::string printMenuColumns (const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 1, 0); }
std::string printBodyColumns (const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 2, 0); }
//std::string printIndicatorColumns(const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 2, 0); }
std::string printFooterColumns (const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 0, 0); }
std::string printCalendar (const std::vector<std::vector<Line>> &cols) const { return printColumns(cols, 1, 0); }
// clang-format on
int consoleWidth() const {
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
return std::max(1, csbi.srWindow.Right - csbi.srWindow.Left);
}
std::string
printColumnsPercent(const std::vector<std::vector<Line>> &columns, const std::vector<double> &percents, int spacing = 1, int padding = 0, int widthOverride = 0) const {
const int cw = widthOverride > 0 ? widthOverride : consoleWidth();
const int numCols = (int)columns.size();
if ((int)percents.size() != numCols || numCols == 0)
return "";
const int totalSpacing = spacing * (numCols - 1);
const int usableWidth = cw - (padding * 2) - totalSpacing;
// column widths
std::vector<int> colWidths(numCols);
int used = 0;
for (int i = 0; i < numCols; ++i) {
colWidths[i] = (int)(usableWidth * (percents[i] / 100.0));
used += colWidths[i];
}
colWidths.back() += usableWidth - used;
// flatten rows per column WITHOUT word wrapping
std::vector<std::vector<std::string>> text(numCols);
std::vector<std::vector<Align>> align(numCols);
for (int c = 0; c < numCols; ++c) {
for (const auto &ln : columns[c]) {
std::string t = ln.text;
// HARD RULE: no reflow, only cut
if ((int)t.size() > colWidths[c])
t = t.substr(0, colWidths[c]);
text[c].push_back(t);
align[c].push_back(ln.alignment);
}
}
size_t maxRows = 0;
for (const auto &c : text)
maxRows = std::max(maxRows, c.size());
std::ostringstream oss;
for (size_t r = 0; r < maxRows; ++r) {
for (int c = 0; c < numCols; ++c) {
std::string t = (r < text[c].size()) ? text[c][r] : "";
Align a = (r < align[c].size()) ? align[c][r] : Align::LEFT;
oss << alignFragment(t, a, colWidths[c]);
if (c < numCols - 1)
oss << std::string(spacing, ' ');
}
oss << '\n';
}
return oss.str();
}
private:
std::vector<Line> bufferedLines;
std::string alignFragment(const std::string &txt, Align a, int width) const {
const int len = (int)txt.size();
const int space = width - len;
if (len >= width)
return txt.substr(0, width);
switch (a) {
case Align::LEFT:
return txt + std::string(space, ' ');
case Align::RIGHT:
return std::string(space, ' ') + txt;
case Align::CENTER: {
const int l = space / 2;
return std::string(l, ' ') + txt + std::string(space - l, ' ');
}
}
return txt;
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Functions
//----------------------------------------------------------------------------------
class Functions {
public:
// =========================================================
// NUMERIC / HASH HELPERS
// =========================================================
static uint64_t hexToUint64(const std::string &hexStr) {
uint64_t value = 0;
std::stringstream ss(hexStr);
ss >> std::hex >> value;
return value;
}
// Takes first 15 hex chars to fit in 60 bits
static uint64_t hashToUint60(const std::string &hexHash) { return hexToUint64(hexHash.substr(0, std::min<size_t>(15, hexHash.size()))); }
static uint64_t messageToUint60(const std::string &message) {
uint64_t value = 0;
for (unsigned char c : message)
value = ((value << 4) | (c & 0xF)) & ((1ULL << 60) - 1);
return value;
}
// Extracts a timestamp embedded in the first 15 chars of a txid
static uint64_t extractTimestamp(const std::string &txid) {
std::string tsStr;
for (size_t i = 0; i < 15 && i < txid.size(); ++i) {
if (txid[i] != '-')
tsStr += txid[i];
}
if (tsStr.empty())
return 0;
return std::stoull(tsStr);
}
// =========================================================
// FORMATTERS
// =========================================================
// All integral types (int, long, long long, uint64_t, etc.)
template <typename T> static std::enable_if_t<std::is_integral_v<T>, std::string> format(T value) { return addCommas(std::to_string(value)); }
// Default: 2 decimal places
static std::string format(double value) { return formatFixed(value, 2); }
// Inserts thousand separators into a numeric string
static std::string addCommas(std::string s) {
size_t dotPos = s.find('.');
if (dotPos == std::string::npos)
dotPos = s.size();
int pos = static_cast<int>(dotPos) - 3;
while (pos > 0) {
s.insert(pos, ",");
pos -= 3;
}
return s;
}
static std::string formatFixed(double value, int precision) {
std::ostringstream ss;
ss << std::fixed << std::setprecision(precision) << value;
return addCommas(ss.str());
}
static std::string formatDouble(double value) { return formatFixed(value, 2); }
static std::string formatExchangeRateDouble(double value) { return formatFixed(value, 5); }
static std::string formatDoubleUSD(double value) { return formatFixed(value, 2); }
static std::string formatDoubleBTC(double value) { return formatFixed(value, 8); }
// Integer satoshi/cent representations → human-readable
static std::string formatWithCommas(long long value) { return addCommas(std::to_string(value)); }
static std::string formatNumber(long long value) { return formatWithCommas(value); }
// =========================================================
// BINARY / HEX
// =========================================================
static std::string generateByteTable() {
std::string output;
for (int i = 0; i <= 50; ++i)
output += std::bitset<8>(i).to_string();
return output;
}
static std::string stringToBinaryASCII(const std::string &input, bool padToPowerOfTwo = true) {
std::string binary;
binary.reserve(input.size() * 8);
for (unsigned char c : input)
binary += std::bitset<8>(c).to_string();
if (padToPowerOfTwo) {
while (!binary.empty() && (binary.size() & (binary.size() - 1)) != 0)
binary.push_back('0');
}
return binary;
}
static std::string binaryASCIIToString(const std::string &binary) {
if (binary.size() % 8 != 0)
throw std::runtime_error("Binary length must be multiple of 8");
std::string output;
output.reserve(binary.size() / 8);
for (size_t i = 0; i < binary.size(); i += 8) {
std::bitset<8> bits(binary.substr(i, 8));
output.push_back(static_cast<char>(bits.to_ulong()));
}
return output;
}
// Binary string → uppercase hex (pads to nearest nibble)
static std::string binaryToHex(const std::string &binary) {
if (binary.empty())
throw std::runtime_error("Empty binary string");
for (char c : binary) {
if (c != '0' && c != '1')
throw std::runtime_error("Invalid binary character");
}
std::string padded = binary;
int pad = (4 - static_cast<int>(padded.size() % 4)) % 4;
padded = std::string(pad, '0') + padded;
std::string hex;
hex.reserve(padded.size() / 4);
for (size_t i = 0; i < padded.size(); i += 4) {
int value = 0;
for (int j = 0; j < 4; ++j)
value = (value << 1) + (padded[i + j] - '0');
hex.push_back(value < 10 ? char('0' + value) : char('A' + value - 10));
}
return hex;
}
static std::string bytesToBinary(const std::vector<uint8_t> &bytes) {
std::string binary;
binary.reserve(bytes.size() * 8);
for (uint8_t b : bytes)
binary += std::bitset<8>(b).to_string();
return binary;
}
static std::vector<uint8_t> binaryToBytes(const std::string &binary) {
if (binary.size() % 8 != 0)
throw std::runtime_error("Binary size must be multiple of 8");
std::vector<uint8_t> bytes;
bytes.reserve(binary.size() / 8);
for (size_t i = 0; i < binary.size(); i += 8) {
std::bitset<8> bits(binary.substr(i, 8));
bytes.push_back(static_cast<uint8_t>(bits.to_ulong()));
}
return bytes;
}
static std::string toBinary(const std::string &text) { return stringToBinaryASCII(text, false); }
static std::string generateByteBlock(uint8_t value, uint32_t count) {
std::string data;
data.reserve(count);
for (uint32_t i = 0; i < count; ++i) {
data.push_back(static_cast<char>(value));
}
return data;
}
static std::string makeProgressBar(int current, int total, int width = 50) {
if (total <= 0)
total = 1;
double progress = std::clamp(static_cast<double>(current) / static_cast<double>(total), 0.0, 1.0);
int filled = static_cast<int>(std::round(progress * width));
std::ostringstream oss;
oss << "[";
for (int i = 0; i < filled; ++i)
oss << "#";
for (int i = filled; i < width; ++i)
oss << " ";
oss << "] " << std::setw(3) << static_cast<int>(progress * 100) << "%";
return oss.str();
}
// Prints in-place using \r — call repeatedly to animate
static void printProgressBar(int current, int total, int width = 50) {
std::cout << '\r' << makeProgressBar(current, total, width);
std::cout.flush();
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// System Clock
//----------------------------------------------------------------------------------
class SystemClock {
public:
inline long long getMilliseconds() {
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}
inline long long getNanoseconds() {
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
}
// =========================================================
// FORMATTED TIME STRINGS
// =========================================================
// Current local time as "YYYY-MM-DD HH:MM:SS.mmm"
std::string getCurrentTime() {
auto now = std::chrono::system_clock::now();
auto tt = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::ostringstream ss;
ss << std::put_time(std::localtime(&tt), "%Y-%m-%d %H:%M:%S") << '.' << std::setfill('0') << std::setw(3) << ms.count();
return ss.str();
}
};
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Logger
//----------------------------------------------------------------------------------
class Logger {
public:
enum Level { LOG_INFO, LOG_WARNING, LOG_ERROR };
Logger() = default;
~Logger() {
if (logFile.is_open()) {
logFile << getCurrentTime() << " [INFO] === Logger shutdown ===\n";
logFile.close();
}
}
void log(const std::string &message, Level level = LOG_INFO, const char *className = "", const char *funcName = "") {
std::lock_guard<std::mutex> lock(mutex_);
ensureLogFileOpen();
std::ostringstream ss;
ss << getCurrentTime() << " ";
switch (level) {
case LOG_INFO:
ss << "[INFO] ";
break;
case LOG_WARNING:
ss << "[WARNING] ";
break;
case LOG_ERROR:
ss << "[ERROR] ";
break;
}
if (className[0] != '\0')
ss << "[" << className << "::" << funcName << "] ";
ss << message << "\n";
logFile << ss.str();
logFile.flush();
}
void info(const std::string &msg) { log(msg, LOG_INFO); }
void warning(const std::string &msg) { log(msg, LOG_WARNING); }
void error(const std::string &msg) { log(msg, LOG_ERROR); }
void setPath(const fs::path &path) {
std::lock_guard<std::mutex> lock(mutex_);
if (logFile.is_open())
logFile.close();
logFileName = path.string();
}
private:
static constexpr const char *CLASS_NAME = "Logger";
SystemClock systemClock;
std::ofstream logFile;
std::mutex mutex_;
std::string logFileName = "file_debug";
void ensureLogFileOpen() {
if (!logFile.is_open()) {
logFile.open(logFileName, std::ios::out | std::ios::app);
if (logFile.is_open()) {
logFile << getCurrentTime() << " [INFO] === Logger startup ===\n";
} else {
throw std::runtime_error("FATAL: Could not open log file");
}
}
}
std::string getCurrentTime() { return std::to_string(systemClock.getNanoseconds()); }
};
// Global Instance
inline Logger logger;
// Macros
#define LOG_INFO(msg) logger.log(msg, Logger::LOG_INFO, CLASS_NAME, __func__)
#define LOG_WARNING(msg) logger.log(msg, Logger::LOG_WARNING, CLASS_NAME, __func__)
#define LOG_ERROR(msg) logger.log(msg, Logger::LOG_ERROR, CLASS_NAME, __func__)
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// namespace CRYPTO {SHA256}
//----------------------------------------------------------------------------------
namespace CRYPTO {
class SHA256 {
public:
SHA256() { reset(); }
// clang format off
// ------------------------------------------------------------
// Input: {0x48, 0x65, 0x6C, 0x6C, 0x6F}
// Output: {0x2C, 0xF2, 0x4D, 0xBA, ...}
// Useful for: HMAC, key derivation, checksums, binary protocols
// ------------------------------------------------------------
inline Bytes hashBytes(const Bytes &data) {
update(data.data(), data.size());
return digestBytes();
}
// ------------------------------------------------------------
// Input: "hello"
// Output: {0x2C, 0xF2, 0x4D, 0xBA, ...}
// Useful when: You need the hash in binary form for further processing
// ------------------------------------------------------------
inline Bytes hashString(const std::string &data) {
update(reinterpret_cast<const uint8_t *>(data.data()), data.size());
return digestBytes();
}
// ------------------------------------------------------------
// Input: "hello"
// Output: "00101100111100100100110110111010..."
// Useful for: Entropy pools, mnemonic generation, bit manipulation, debugging
// ------------------------------------------------------------
inline std::string hashBinary(const std::string &data) {
update(reinterpret_cast<const uint8_t *>(data.data()), data.size());
return digestBinary();
}
// ------------------------------------------------------------
// Input: "hello"
// Output: "1b161e5c1fa7425e73043362938b9824"
// Useful for: Transaction IDs, fingerprints, certificates, wallet identifiers, logging and display
// ------------------------------------------------------------
inline std::string hashHex(const std::string &data) {
update(reinterpret_cast<const uint8_t *>(data.data()), data.size());
return digest();
}
inline void update(const uint8_t *data, size_t len) {
for (size_t i = 0; i < len; ++i) {
buffer[bufferLen++] = data[i];
if (bufferLen == 64) {
transform(buffer);
bitlen += 512;
bufferLen = 0;
}
}
}
// clang format on
inline std::string digest() {
uint64_t totalBits = bitlen + bufferLen * 8;
buffer[bufferLen++] = 0x80;
if (bufferLen > 56) {
while (bufferLen < 64)
buffer[bufferLen++] = 0x00;