-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1807 lines (1511 loc) · 56.6 KB
/
main.cpp
File metadata and controls
1807 lines (1511 loc) · 56.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
/**
* @file main.cpp
* @author Chen Enhua (陈恩华)
* @brief CEH-Orbit Blockchain Fire Seed V1 - 可视化调试版
*
* 说明:
* 1. 本文件为单文件完整演示版
* 2. 包含:
* - CEH-Orbit KeyGen / Sign / Verify
* - Wallet / Address
* - Transaction / TxID
* - Block / Header / Merkle
* - Simplified PoW
* - Account State Machine
* - Local Gossip Simulation
* - Qt 参数调试面板
* - Qt 实时图表渲染
*
* 严正声明:
* - 本实现为研究原型,不是商用品
* - 未完成形式化安全证明
* - 未完成侧信道防护
* - 未兼容现有主流公链
* - 核心基于 CEH_Orbit 非商业许可协议
*/
#include <QApplication>
#include <QMainWindow>
#include <QWidget>
#include <QFrame>
#include <QLabel>
#include <QPushButton>
#include <QSpinBox>
#include <QLineEdit>
#include <QTextEdit>
#include <QFormLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QSplitter>
#include <QTimer>
#include <QGroupBox>
#include <QScrollArea>
#include <QTableWidget>
#include <QHeaderView>
#include <QDateTime>
#include <QPainter>
#include <QPainterPath>
#include <QRandomGenerator>
#include <QSizePolicy>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QScatterSeries>
#include <QtCharts/QValueAxis>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QChart>
#include <openssl/sha.h>
#include <vector>
#include <array>
#include <string>
#include <sstream>
#include <iomanip>
#include <random>
#include <chrono>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include <cmath>
#include <cstdint>
#include <cstring>
using namespace std;
// ============================================================
// 一、CEH-Orbit Blockchain Fire Seed 核心
// ============================================================
namespace CEH_Orbit_Blockchain_FireSeed {
// ------------------------------------------------------------
// 协议元数据
// ------------------------------------------------------------
static const char* PROTOCOL_NAME = "CEH-Orbit Blockchain Fire Seed V1";
static const char* ARCH_IDENTIFIER = "CEH_ORBIT_BLOCKCHAIN_FIRESEED_V1_BY_CHEN_ENHUA";
static const char* AUTHOR_NAME = "Chen Enhua";
static const char* AUTHOR_EMAIL = "a106079595@qq.com";
static const char* DOMAIN_CHALLENGE = "CEH_ORBIT_CHALLENGE_V1";
static const char* DOMAIN_BIND = "CEH_ORBIT_BIND_V1";
static const char* DOMAIN_ADDRESS = "CEH_ORBIT_ADDRESS_V1";
static const char* DOMAIN_TXID = "CEH_ORBIT_TXID_V1";
static const char* DOMAIN_BLOCK = "CEH_ORBIT_BLOCK_V1";
// ------------------------------------------------------------
// 参数
// ------------------------------------------------------------
struct Params {
int N = 128;
int Q = 3329;
int NAV_ZONES = 16;
int DELTA = 32;
int SIG_BOUND = 260;
int CHALLENGE_WT = 8;
int Y_MIN = -200;
int Y_MAX = 200;
int genesis_balance = 1000;
int mining_reward = 50;
int pow_difficulty = 2;
int attack_rounds = 10000;
int collision_trials = 2000;
int basin_rounds = 500;
};
// ------------------------------------------------------------
// 基础类型
// ------------------------------------------------------------
using Poly = std::vector<int>;
struct OrbitHead {
uint64_t lsh0 = 0;
uint64_t lsh1 = 0;
std::vector<int> phase;
};
struct KeyPair {
Poly a;
Poly s;
Poly t;
};
struct Signature {
std::vector<int> z;
OrbitHead head;
Poly c;
uint64_t bind_hash = 0;
};
struct VerifyResult {
bool ok = false;
bool z_bound_ok = false;
bool bind_ok = false;
bool head_ok = false;
bool chal_ok = false;
int lsh_dist = -1;
int phase_dist = -1;
Poly recovered_w;
OrbitHead recovered_head;
Poly recovered_c;
};
enum class TxType {
TRANSFER = 0,
COINBASE = 1
};
struct Transaction {
TxType type = TxType::TRANSFER;
std::string from;
std::string to;
uint64_t amount = 0;
uint64_t nonce = 0;
uint64_t timestamp_ms = 0;
std::string memo;
Signature sig;
std::string txid;
};
struct BlockHeader {
uint64_t height = 0;
std::string prev_hash;
std::string merkle_root;
uint64_t timestamp_ms = 0;
uint64_t difficulty = 0;
uint64_t nonce = 0;
};
struct Block {
BlockHeader header;
std::vector<Transaction> txs;
std::string block_hash;
};
struct AccountState {
uint64_t balance = 0;
uint64_t nonce = 0;
};
struct Wallet {
std::string owner;
KeyPair keypair;
std::string address;
};
struct BenchmarkResult {
double keygen_ms = 0.0;
double sign_ms = 0.0;
double verify_ms = 0.0;
int serialized_size = 0;
};
struct AttackResult {
int success = 0;
int rounds = 0;
};
struct BasinPoint {
int amplitude = 0;
int pass = 0;
int rounds = 0;
};
// ------------------------------------------------------------
// 工具函数
// ------------------------------------------------------------
inline int mod_q(long long x, int Q) {
int r = static_cast<int>(x % Q);
if (r < 0) r += Q;
return r;
}
inline int centered(int x, int Q) {
x = mod_q(x, Q);
if (x > Q / 2) x -= Q;
return x;
}
template<typename T>
std::string prefix_vec(const std::vector<T>& v, int cnt = 8) {
std::ostringstream oss;
int lim = std::min<int>(cnt, static_cast<int>(v.size()));
for (int i = 0; i < lim; ++i) {
if (i) oss << ", ";
oss << v[i];
}
return oss.str();
}
uint64_t now_ms() {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count()
);
}
// ------------------------------------------------------------
// SHA256
// ------------------------------------------------------------
std::vector<uint8_t> sha256_bytes(const std::vector<uint8_t>& input) {
uint8_t hash[SHA256_DIGEST_LENGTH];
SHA256(input.data(), input.size(), hash);
return std::vector<uint8_t>(hash, hash + SHA256_DIGEST_LENGTH);
}
std::string sha256_hex(const std::vector<uint8_t>& input) {
auto digest = sha256_bytes(input);
std::ostringstream oss;
for (unsigned char c : digest) {
oss << std::hex << std::setw(2) << std::setfill('0') << (int)c;
}
return oss.str();
}
std::string sha256_hex_str(const std::string& s) {
std::vector<uint8_t> in(s.begin(), s.end());
return sha256_hex(in);
}
uint64_t sha256_u64(const std::vector<uint8_t>& input) {
auto digest = sha256_bytes(input);
uint64_t out = 0;
for (int i = 7; i >= 0; --i) {
out = (out << 8) | digest[i];
}
return out;
}
void append_u16_modq(std::vector<uint8_t>& out, int v, int Q) {
int x = mod_q(v, Q);
out.push_back(static_cast<uint8_t>(x & 0xff));
out.push_back(static_cast<uint8_t>((x >> 8) & 0xff));
}
void append_u64_le(std::vector<uint8_t>& out, uint64_t x) {
for (int i = 0; i < 8; ++i) {
out.push_back(static_cast<uint8_t>((x >> (8 * i)) & 0xff));
}
}
void append_ascii(std::vector<uint8_t>& out, const std::string& s) {
for (unsigned char ch : s) out.push_back(ch);
}
void append_message(std::vector<uint8_t>& out, const std::string& s) {
for (unsigned char ch : s) out.push_back(ch);
}
// ------------------------------------------------------------
// 代数核心:负循环卷积
// ------------------------------------------------------------
Poly poly_mul_negacyclic(const Poly& a, const Poly& b, const Params& p) {
Poly r(p.N, 0);
for (int i = 0; i < p.N; ++i) {
if (a[i] == 0) continue;
for (int j = 0; j < p.N; ++j) {
if (b[j] == 0) continue;
long long prod = 1LL * a[i] * b[j];
int k = i + j;
if (k < p.N) {
r[k] = mod_q(r[k] + prod, p.Q);
} else {
r[k - p.N] = mod_q(r[k - p.N] - prod, p.Q);
}
}
}
return r;
}
Poly vec_to_poly(const std::vector<int>& v, const Params& p) {
Poly poly(p.N, 0);
for (int i = 0; i < p.N && i < static_cast<int>(v.size()); ++i) {
poly[i] = v[i];
}
return poly;
}
// ------------------------------------------------------------
// OrbitHead
// ------------------------------------------------------------
int phase_cyclic_distance(int a, int b) {
int d = std::abs(a - b);
return std::min(d, 4 - d);
}
int lsh_hamming_distance(const OrbitHead& a, const OrbitHead& b) {
return __builtin_popcountll(a.lsh0 ^ b.lsh0) +
__builtin_popcountll(a.lsh1 ^ b.lsh1);
}
int phase_total_distance(const OrbitHead& a, const OrbitHead& b) {
int s = 0;
int lim = std::min<int>(a.phase.size(), b.phase.size());
for (int i = 0; i < lim; ++i) {
s += phase_cyclic_distance(a.phase[i], b.phase[i]);
}
return s;
}
OrbitHead build_head(const Poly& w, const Params& p) {
OrbitHead h;
h.lsh0 = 0;
h.lsh1 = 0;
h.phase.assign(p.NAV_ZONES, 0);
for (int i = 0; i < p.N; ++i) {
int v = centered(w[i], p.Q);
bool bit = ((((v / p.DELTA)) ^ i) & 1) != 0;
if (i < 64) {
if (bit) h.lsh0 |= (1ULL << i);
} else if (i < 128) {
if (bit) h.lsh1 |= (1ULL << (i - 64));
}
}
int seg_len = std::max(1, p.N / p.NAV_ZONES);
for (int seg = 0; seg < p.NAV_ZONES; ++seg) {
int begin = seg * seg_len;
int end = std::min(p.N, begin + seg_len);
int sum = 0;
for (int i = begin; i < end; ++i) {
sum += centered(w[i], p.Q);
}
h.phase[seg] = (sum % 4 + 4) % 4;
}
return h;
}
// ------------------------------------------------------------
// Challenge / Bind
// ------------------------------------------------------------
Poly derive_challenge(const OrbitHead& head, const std::string& msg, const Params& p) {
std::vector<uint8_t> seed_bytes;
append_ascii(seed_bytes, DOMAIN_CHALLENGE);
append_ascii(seed_bytes, ARCH_IDENTIFIER);
append_u64_le(seed_bytes, head.lsh0);
append_u64_le(seed_bytes, head.lsh1);
for (int ph : head.phase) {
seed_bytes.push_back(static_cast<uint8_t>(ph & 0xff));
}
append_message(seed_bytes, msg);
auto digest = sha256_bytes(seed_bytes);
uint64_t seed = 0;
for (int i = 0; i < 8; ++i) {
seed |= (static_cast<uint64_t>(digest[i]) << (8 * i));
}
std::mt19937_64 rng(seed);
Poly c(p.N, 0);
std::set<int> used;
while ((int)used.size() < p.CHALLENGE_WT) {
int pos = static_cast<int>(rng() % p.N);
if (used.count(pos)) continue;
used.insert(pos);
c[pos] = (rng() & 1ULL) ? 1 : (p.Q - 1);
}
return c;
}
uint64_t hash_binding(const std::string& msg,
const std::vector<int>& z,
const Poly& c,
const OrbitHead& head,
const Params& p) {
std::vector<uint8_t> bytes;
append_ascii(bytes, DOMAIN_BIND);
append_ascii(bytes, ARCH_IDENTIFIER);
append_message(bytes, msg);
for (int v : z) append_u16_modq(bytes, v, p.Q);
for (int v : c) append_u16_modq(bytes, v, p.Q);
append_u64_le(bytes, head.lsh0);
append_u64_le(bytes, head.lsh1);
for (int ph : head.phase) {
bytes.push_back(static_cast<uint8_t>(ph & 0xff));
}
return sha256_u64(bytes);
}
// ------------------------------------------------------------
// KeyGen / Sign / Verify
// ------------------------------------------------------------
KeyPair keygen(std::mt19937_64& rng, const Params& p) {
KeyPair k;
k.a.assign(p.N, 0);
k.s.assign(p.N, 0);
k.t.assign(p.N, 0);
std::uniform_int_distribution<int> dist_q(0, p.Q - 1);
std::uniform_int_distribution<int> dist_s(0, 11);
for (int i = 0; i < p.N; ++i) {
k.a[i] = dist_q(rng);
int r = dist_s(rng);
if (r == 0) k.s[i] = 1;
else if (r == 1) k.s[i] = -1;
else k.s[i] = 0;
}
k.t = poly_mul_negacyclic(k.a, k.s, p);
return k;
}
Signature sign(const std::string& msg, const KeyPair& k, std::mt19937_64& rng, const Params& p) {
std::uniform_int_distribution<int> dist_y(p.Y_MIN, p.Y_MAX);
while (true) {
Poly y(p.N, 0);
for (int i = 0; i < p.N; ++i) y[i] = dist_y(rng);
Poly w = poly_mul_negacyclic(k.a, y, p);
OrbitHead head = build_head(w, p);
Poly c = derive_challenge(head, msg, p);
Poly cs = poly_mul_negacyclic(c, k.s, p);
Signature sig;
sig.z.resize(p.N);
int max_abs = 0;
for (int i = 0; i < p.N; ++i) {
sig.z[i] = y[i] + centered(cs[i], p.Q);
max_abs = std::max(max_abs, std::abs(sig.z[i]));
}
if (max_abs > p.SIG_BOUND) continue;
sig.head = head;
sig.c = c;
sig.bind_hash = hash_binding(msg, sig.z, sig.c, sig.head, p);
return sig;
}
}
VerifyResult verify(const std::string& msg, const KeyPair& k, const Signature& sig, const Params& p) {
VerifyResult vr;
vr.recovered_w.assign(p.N, 0);
vr.recovered_c.assign(p.N, 0);
vr.z_bound_ok = true;
for (int v : sig.z) {
if (std::abs(v) > p.SIG_BOUND) {
vr.z_bound_ok = false;
vr.ok = false;
return vr;
}
}
vr.bind_ok = (hash_binding(msg, sig.z, sig.c, sig.head, p) == sig.bind_hash);
if (!vr.bind_ok) {
vr.ok = false;
return vr;
}
Poly z_poly = vec_to_poly(sig.z, p);
Poly az = poly_mul_negacyclic(k.a, z_poly, p);
Poly ct = poly_mul_negacyclic(sig.c, k.t, p);
for (int i = 0; i < p.N; ++i) {
vr.recovered_w[i] = mod_q(az[i] - ct[i], p.Q);
}
vr.recovered_head = build_head(vr.recovered_w, p);
vr.lsh_dist = lsh_hamming_distance(sig.head, vr.recovered_head);
vr.phase_dist = phase_total_distance(sig.head, vr.recovered_head);
vr.head_ok = (vr.lsh_dist == 0 && vr.phase_dist == 0);
vr.recovered_c = derive_challenge(vr.recovered_head, msg, p);
vr.chal_ok = true;
for (int i = 0; i < p.N; ++i) {
if (vr.recovered_c[i] != sig.c[i]) {
vr.chal_ok = false;
break;
}
}
vr.ok = vr.z_bound_ok && vr.bind_ok && vr.head_ok && vr.chal_ok;
return vr;
}
std::vector<uint8_t> serialize_signature(const Signature& sig, const Params& p) {
std::vector<uint8_t> out;
out.push_back('C');
out.push_back('E');
out.push_back('H');
out.push_back('1');
out.push_back(0x01);
append_u16_modq(out, p.N, p.Q);
append_u16_modq(out, p.Q, p.Q);
append_u16_modq(out, p.N, p.Q);
for (int v : sig.z) append_u16_modq(out, v, p.Q);
out.push_back(0x02);
append_u64_le(out, sig.head.lsh0);
append_u64_le(out, sig.head.lsh1);
out.push_back(static_cast<uint8_t>(p.NAV_ZONES));
for (int ph : sig.head.phase) out.push_back(static_cast<uint8_t>(ph & 0xff));
append_u16_modq(out, p.N, p.Q);
for (int v : sig.c) append_u16_modq(out, v, p.Q);
append_u64_le(out, sig.bind_hash);
return out;
}
// ------------------------------------------------------------
// Wallet / Address
// ------------------------------------------------------------
std::string derive_address_from_pub(const KeyPair& kp, const Params& p) {
std::vector<uint8_t> bytes;
append_ascii(bytes, DOMAIN_ADDRESS);
append_ascii(bytes, ARCH_IDENTIFIER);
for (int v : kp.a) append_u16_modq(bytes, v, p.Q);
for (int v : kp.t) append_u16_modq(bytes, v, p.Q);
std::string h = sha256_hex(bytes);
return "ceh1_" + h.substr(0, 40);
}
Wallet create_wallet(const std::string& owner, std::mt19937_64& rng, const Params& p) {
Wallet w;
w.owner = owner;
w.keypair = keygen(rng, p);
w.address = derive_address_from_pub(w.keypair, p);
return w;
}
// ------------------------------------------------------------
// Tx / TxID
// ------------------------------------------------------------
std::string tx_payload_string(const Transaction& tx) {
std::ostringstream oss;
oss << static_cast<int>(tx.type) << "|"
<< tx.from << "|"
<< tx.to << "|"
<< tx.amount << "|"
<< tx.nonce << "|"
<< tx.timestamp_ms << "|"
<< tx.memo;
return oss.str();
}
std::string compute_txid(const Transaction& tx, const Params& p) {
std::vector<uint8_t> bytes;
append_ascii(bytes, DOMAIN_TXID);
append_ascii(bytes, ARCH_IDENTIFIER);
append_message(bytes, tx_payload_string(tx));
auto sig_bytes = serialize_signature(tx.sig, p);
bytes.insert(bytes.end(), sig_bytes.begin(), sig_bytes.end());
return sha256_hex(bytes);
}
Transaction make_signed_transfer(const Wallet& from,
const std::string& to,
uint64_t amount,
uint64_t nonce,
const std::string& memo,
std::mt19937_64& rng,
const Params& p) {
Transaction tx;
tx.type = TxType::TRANSFER;
tx.from = from.address;
tx.to = to;
tx.amount = amount;
tx.nonce = nonce;
tx.timestamp_ms = now_ms();
tx.memo = memo;
std::string payload = tx_payload_string(tx);
tx.sig = sign(payload, from.keypair, rng, p);
tx.txid = compute_txid(tx, p);
return tx;
}
Transaction make_coinbase_tx(const std::string& to, uint64_t amount, uint64_t height) {
Transaction tx;
tx.type = TxType::COINBASE;
tx.from = "COINBASE";
tx.to = to;
tx.amount = amount;
tx.nonce = height;
tx.timestamp_ms = now_ms();
tx.memo = "block reward";
tx.txid = sha256_hex_str("COINBASE|" + to + "|" + std::to_string(amount) + "|" + std::to_string(height));
return tx;
}
// ------------------------------------------------------------
// Merkle
// ------------------------------------------------------------
std::string merkle_root(std::vector<std::string> hashes) {
if (hashes.empty()) {
return sha256_hex_str("EMPTY_MERKLE");
}
while (hashes.size() > 1) {
if (hashes.size() % 2 == 1) hashes.push_back(hashes.back());
std::vector<std::string> next;
for (size_t i = 0; i < hashes.size(); i += 2) {
next.push_back(sha256_hex_str(hashes[i] + hashes[i + 1]));
}
hashes = std::move(next);
}
return hashes[0];
}
// ------------------------------------------------------------
// Block / PoW
// ------------------------------------------------------------
std::string header_to_string(const BlockHeader& h) {
std::ostringstream oss;
oss << h.height << "|"
<< h.prev_hash << "|"
<< h.merkle_root << "|"
<< h.timestamp_ms << "|"
<< h.difficulty << "|"
<< h.nonce;
return oss.str();
}
bool hash_meets_difficulty(const std::string& hex_hash, uint64_t difficulty) {
if (difficulty == 0) return true;
if (difficulty > hex_hash.size()) return false;
for (uint64_t i = 0; i < difficulty; ++i) {
if (hex_hash[i] != '0') return false;
}
return true;
}
std::string mine_block_hash(BlockHeader& header) {
while (true) {
std::string h = sha256_hex_str(header_to_string(header));
if (hash_meets_difficulty(h, header.difficulty)) return h;
header.nonce++;
}
}
// ------------------------------------------------------------
// StateDB
// ------------------------------------------------------------
class StateDB {
public:
void credit(const std::string& addr, uint64_t amount) {
states_[addr].balance += amount;
}
bool can_spend(const std::string& addr, uint64_t amount, uint64_t nonce) const {
auto it = states_.find(addr);
if (it == states_.end()) return false;
return it->second.balance >= amount && it->second.nonce == nonce;
}
bool apply_tx(const Transaction& tx) {
if (tx.type == TxType::COINBASE) {
states_[tx.to].balance += tx.amount;
return true;
}
auto it = states_.find(tx.from);
if (it == states_.end()) return false;
if (it->second.balance < tx.amount) return false;
if (it->second.nonce != tx.nonce) return false;
it->second.balance -= tx.amount;
it->second.nonce += 1;
states_[tx.to].balance += tx.amount;
return true;
}
uint64_t balance_of(const std::string& addr) const {
auto it = states_.find(addr);
if (it == states_.end()) return 0;
return it->second.balance;
}
uint64_t nonce_of(const std::string& addr) const {
auto it = states_.find(addr);
if (it == states_.end()) return 0;
return it->second.nonce;
}
const std::unordered_map<std::string, AccountState>& raw() const {
return states_;
}
private:
std::unordered_map<std::string, AccountState> states_;
};
struct TxVerifyContext {
const std::unordered_map<std::string, KeyPair>* pub_registry = nullptr;
const Params* params = nullptr;
};
bool verify_transaction_signature(const Transaction& tx, const TxVerifyContext& ctx) {
if (tx.type == TxType::COINBASE) return true;
auto it = ctx.pub_registry->find(tx.from);
if (it == ctx.pub_registry->end()) return false;
std::string payload = tx_payload_string(tx);
auto vr = verify(payload, it->second, tx.sig, *ctx.params);
return vr.ok;
}
// ------------------------------------------------------------
// Node
// ------------------------------------------------------------
class Node {
public:
explicit Node(std::string name, const Params& params)
: name_(std::move(name)), params_(params) {}
void connect(Node* other) {
if (other == this) return;
peers_.push_back(other);
}
void set_pub_registry(const std::unordered_map<std::string, KeyPair>* reg) {
ctx_.pub_registry = reg;
ctx_.params = ¶ms_;
}
void init_genesis(const std::string& treasury, uint64_t amount) {
if (!chain_.empty()) return;
Block genesis;
genesis.header.height = 0;
genesis.header.prev_hash = "GENESIS";
genesis.header.timestamp_ms = now_ms();
genesis.header.difficulty = 1;
genesis.txs.push_back(make_coinbase_tx(treasury, amount, 0));
std::vector<std::string> txids;
for (auto& tx : genesis.txs) txids.push_back(tx.txid);
genesis.header.merkle_root = merkle_root(txids);
genesis.block_hash = mine_block_hash(genesis.header);
chain_.push_back(genesis);
state_.apply_tx(genesis.txs[0]);
}
bool receive_tx(const Transaction& tx) {
if (seen_txs_.count(tx.txid)) return false;
seen_txs_.insert(tx.txid);
if (!verify_transaction_signature(tx, ctx_)) {
last_reject_reason_ = "signature invalid";
return false;
}
if (tx.type == TxType::TRANSFER && !state_.can_spend(tx.from, tx.amount, tx.nonce)) {
last_reject_reason_ = "state invalid";
return false;
}
mempool_.push_back(tx);
gossip_tx(tx);
return true;
}
void mine_one_block(const std::string& miner_addr, uint64_t reward, uint64_t difficulty) {
Block b;
b.header.height = chain_.size();
b.header.prev_hash = chain_.back().block_hash;
b.header.timestamp_ms = now_ms();
b.header.difficulty = difficulty;
b.header.nonce = 0;
b.txs.push_back(make_coinbase_tx(miner_addr, reward, b.header.height));
std::vector<Transaction> remain;
for (const auto& tx : mempool_) {
if (tx.type == TxType::TRANSFER && state_.can_spend(tx.from, tx.amount, tx.nonce)) {
b.txs.push_back(tx);
} else {
remain.push_back(tx);
}
}
mempool_.swap(remain);
std::vector<std::string> txids;
for (const auto& tx : b.txs) txids.push_back(tx.txid);
b.header.merkle_root = merkle_root(txids);
auto t0 = std::chrono::high_resolution_clock::now();
b.block_hash = mine_block_hash(b.header);
auto t1 = std::chrono::high_resolution_clock::now();
last_mine_ms_ = std::chrono::duration<double, std::milli>(t1 - t0).count();
bool all_ok = true;
for (const auto& tx : b.txs) {
if (!state_.apply_tx(tx)) {
all_ok = false;
break;
}
}
if (!all_ok) {
last_reject_reason_ = "block apply failed";
return;
}
chain_.push_back(b);
}
const std::vector<Block>& chain() const { return chain_; }
const std::vector<Transaction>& mempool() const { return mempool_; }
const StateDB& state() const { return state_; }
const std::string& name() const { return name_; }
double last_mine_ms() const { return last_mine_ms_; }
const std::string& last_reject_reason() const { return last_reject_reason_; }
private:
void gossip_tx(const Transaction& tx) {
for (auto* p : peers_) {
if (p) p->receive_tx_no_gossip(tx);
}
}
void receive_tx_no_gossip(const Transaction& tx) {
if (seen_txs_.count(tx.txid)) return;
seen_txs_.insert(tx.txid);
if (!verify_transaction_signature(tx, ctx_)) return;
if (tx.type == TxType::TRANSFER && !state_.can_spend(tx.from, tx.amount, tx.nonce)) return;
mempool_.push_back(tx);
}
private:
std::string name_;
Params params_;
TxVerifyContext ctx_;
std::vector<Node*> peers_;
std::vector<Block> chain_;
std::vector<Transaction> mempool_;
std::set<std::string> seen_txs_;
StateDB state_;
double last_mine_ms_ = 0.0;
std::string last_reject_reason_;
};
// ------------------------------------------------------------
// Benchmark / Attack / Basin
// ------------------------------------------------------------
BenchmarkResult run_benchmark(const Params& p) {
BenchmarkResult br;
std::mt19937_64 rng(static_cast<uint64_t>(
std::chrono::high_resolution_clock::now().time_since_epoch().count()
));
std::string msg = "CEH_ORBIT_BENCHMARK_MESSAGE";
auto t0 = std::chrono::high_resolution_clock::now();
KeyPair k = keygen(rng, p);
auto t1 = std::chrono::high_resolution_clock::now();
Signature sig = sign(msg, k, rng, p);
auto t2 = std::chrono::high_resolution_clock::now();
auto vr = verify(msg, k, sig, p);
auto t3 = std::chrono::high_resolution_clock::now();
br.keygen_ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
br.sign_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
br.verify_ms = std::chrono::duration<double, std::milli>(t3 - t2).count();
br.serialized_size = static_cast<int>(serialize_signature(sig, p).size());
(void)vr;
return br;
}
AttackResult random_forgery_attack(const Params& p) {
AttackResult ar;
ar.rounds = p.attack_rounds;
ar.success = 0;
std::mt19937_64 rng(1);
std::string msg = "CEH_ORBIT_ATTACK_MESSAGE";
KeyPair k = keygen(rng, p);
Signature base = sign(msg, k, rng, p);
for (int i = 0; i < ar.rounds; ++i) {
Signature fake = base;
int idx = static_cast<int>(rng() % p.N);
fake.z[idx] += (rng() & 1ULL) ? 1 : -1;
fake.bind_hash = hash_binding(msg, fake.z, fake.c, fake.head, p);
auto vr = verify(msg, k, fake, p);
if (vr.ok) ar.success++;
}
return ar;
}
double head_collision_rate(const Params& p) {
std::mt19937_64 rng(2);
std::string msg = "CEH_ORBIT_COLLISION_MESSAGE";
KeyPair k = keygen(rng, p);
std::set<std::pair<uint64_t, uint64_t>> seen;
int collisions = 0;
for (int i = 0; i < p.collision_trials; ++i) {
Signature sig = sign(msg, k, rng, p);
auto hh = std::make_pair(sig.head.lsh0, sig.head.lsh1);
if (seen.count(hh)) collisions++;
else seen.insert(hh);
}
return static_cast<double>(collisions) / std::max(1, p.collision_trials);
}
std::vector<BasinPoint> basin_scan_single_point(const Params& p) {
std::mt19937_64 rng(3);
std::string msg = "CEH_ORBIT_BASIN_MESSAGE";
KeyPair k = keygen(rng, p);
Signature sig = sign(msg, k, rng, p);
std::vector<int> amps = {1, 2, 5, 9, 10};
std::vector<BasinPoint> out;