Repository navigation
Expand file tree
/
Copy pathpearl_verify.cc
More file actions
1432 lines (1337 loc) · 55.8 KB
/
Copy pathpearl_verify.cc
File metadata and controls
1432 lines (1337 loc) · 55.8 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
#include "pearl_verify.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <exception>
#include <limits>
#include <utility>
#include <vector>
namespace pearl_verify {
namespace {
using pearl_blake3::Hash;
constexpr uint64_t CHUNK = pearl_blake3::CHUNK_LEN;
constexpr uint64_t MAX_VECTOR_ITEMS = MAX_PROOF_BYTES;
constexpr uint64_t MAX_PATTERN_ITEMS = 256;
constexpr uint64_t MAX_EXPERTS = 1024;
constexpr uint64_t MAX_M = 1u << 24;
constexpr uint64_t MAX_N = 1u << 24;
constexpr uint64_t MAX_K = 1u << 16;
bool same_hash(const Hash& a, const Hash& b) {
uint8_t different = 0;
for (size_t i = 0; i < a.size(); ++i) different |= static_cast<uint8_t>(a[i] ^ b[i]);
return different == 0;
}
bool checked_add_u64(uint64_t a, uint64_t b, uint64_t* out) {
if (b > std::numeric_limits<uint64_t>::max() - a) return false;
*out = a + b;
return true;
}
bool checked_mul_u64(uint64_t a, uint64_t b, uint64_t* out) {
if (a != 0 && b > std::numeric_limits<uint64_t>::max() / a) return false;
*out = a * b;
return true;
}
bool padded_bytes(uint64_t raw, uint64_t* out) {
if (raw == 0) {
*out = 0;
return true;
}
uint64_t with_rounding = 0;
if (!checked_add_u64(raw, CHUNK - 1, &with_rounding)) return false;
*out = (with_rounding / CHUNK) * CHUNK;
return true;
}
class Reader {
public:
Reader(const uint8_t* data, size_t length) : data_(data), length_(length) {}
size_t remaining() const { return length_ - position_; }
size_t position() const { return position_; }
const std::string& error() const { return error_; }
bool read_u8(uint8_t* out) {
if (remaining() < 1) return fail("truncated byte");
*out = data_[position_++];
return true;
}
bool read_u16(uint16_t* out) {
if (remaining() < 2) return fail("truncated u16");
*out = static_cast<uint16_t>(data_[position_]) |
static_cast<uint16_t>(data_[position_ + 1]) << 8;
position_ += 2;
return true;
}
bool read_u32(uint32_t* out) {
if (remaining() < 4) return fail("truncated u32");
*out = static_cast<uint32_t>(data_[position_]) |
static_cast<uint32_t>(data_[position_ + 1]) << 8 |
static_cast<uint32_t>(data_[position_ + 2]) << 16 |
static_cast<uint32_t>(data_[position_ + 3]) << 24;
position_ += 4;
return true;
}
bool read_u64(uint64_t* out) {
if (remaining() < 8) return fail("truncated u64");
uint64_t value = 0;
for (unsigned i = 0; i < 8; ++i) value |= static_cast<uint64_t>(data_[position_ + i]) << (8 * i);
position_ += 8;
*out = value;
return true;
}
bool read_bytes(uint8_t* out, size_t count) {
if (count > remaining()) return fail("truncated byte array");
if (count != 0) std::memcpy(out, data_ + position_, count);
position_ += count;
return true;
}
bool read_hash(Hash* out) { return read_bytes(out->data(), out->size()); }
bool fail(const char* message) {
if (error_.empty()) error_ = message;
return false;
}
private:
const uint8_t* data_;
size_t length_;
size_t position_ = 0;
std::string error_;
};
struct Merkle {
std::vector<std::array<uint8_t, pearl_blake3::CHUNK_LEN>> leaves;
std::vector<uint64_t> leaf_indices;
uint64_t total_leaves = 0;
Hash root{};
std::vector<Hash> siblings;
};
struct MatrixProof {
Merkle proof;
std::vector<uint64_t> rows;
};
struct MoeProof {
uint64_t experts = 0;
uint64_t top_k = 0;
uint16_t expert_index = 0;
std::vector<uint32_t> routing_offsets;
std::vector<uint64_t> inner_a_rows;
Merkle routing;
};
struct PlainProof {
uint64_t m = 0;
uint64_t n = 0;
uint64_t k = 0;
uint64_t noise_rank = 0;
MatrixProof a;
MatrixProof bt;
bool has_moe = false;
MoeProof moe;
bool legacy_dense = false;
};
struct PreparedProof {
PlainProof proof;
ConfigInfo config;
Hash job_key{};
Hash root_a{};
Hash root_b{};
Hash root_routing{};
std::vector<uint8_t> solution_data;
uint64_t total_b_cols = 0;
uint32_t m = 0;
uint32_t n = 0;
uint32_t k = 0;
uint16_t rank = 0;
};
template <typename T>
bool start_vector(Reader* reader, uint64_t* count, size_t item_size, const char* label) {
if (!reader->read_u64(count)) return false;
if (*count > MAX_VECTOR_ITEMS || (*count != 0 && item_size > reader->remaining() / *count)) {
return reader->fail(label);
}
return true;
}
bool read_hash_vector(Reader* reader, std::vector<Hash>* output, const char* label) {
uint64_t count = 0;
if (!start_vector<Hash>(reader, &count, sizeof(Hash), label)) return false;
output->clear();
output->reserve(static_cast<size_t>(count));
for (uint64_t i = 0; i < count; ++i) {
Hash value{};
if (!reader->read_hash(&value)) return false;
output->push_back(value);
}
return true;
}
bool read_u64_vector(Reader* reader, std::vector<uint64_t>* output, const char* label) {
uint64_t count = 0;
if (!start_vector<uint64_t>(reader, &count, sizeof(uint64_t), label)) return false;
output->clear();
output->reserve(static_cast<size_t>(count));
for (uint64_t i = 0; i < count; ++i) {
uint64_t value = 0;
if (!reader->read_u64(&value)) return false;
output->push_back(value);
}
return true;
}
bool read_u32_vector(Reader* reader, std::vector<uint32_t>* output, const char* label) {
uint64_t count = 0;
if (!start_vector<uint32_t>(reader, &count, sizeof(uint32_t), label)) return false;
output->clear();
output->reserve(static_cast<size_t>(count));
for (uint64_t i = 0; i < count; ++i) {
uint32_t value = 0;
if (!reader->read_u32(&value)) return false;
output->push_back(value);
}
return true;
}
bool read_leaf_vector(Reader* reader,
std::vector<std::array<uint8_t, pearl_blake3::CHUNK_LEN>>* output,
const char* label) {
uint64_t count = 0;
if (!start_vector<std::array<uint8_t, pearl_blake3::CHUNK_LEN>>(
reader, &count, pearl_blake3::CHUNK_LEN, label)) return false;
output->clear();
output->reserve(static_cast<size_t>(count));
for (uint64_t i = 0; i < count; ++i) {
// Upstream serde_chunk_vec encodes each fixed chunk as a byte slice.
uint64_t length = 0;
if (!reader->read_u64(&length)) return false;
if (length != pearl_blake3::CHUNK_LEN) {
return reader->fail("leaf_data item is not a 1024-byte BLAKE3 chunk");
}
std::array<uint8_t, pearl_blake3::CHUNK_LEN> value{};
if (!reader->read_bytes(value.data(), value.size())) return false;
output->push_back(value);
}
return true;
}
bool read_merkle(Reader* reader, Merkle* output) {
if (!read_leaf_vector(reader, &output->leaves, "leaf_data length exceeds proof bounds")) return false;
if (!read_u64_vector(reader, &output->leaf_indices, "leaf_indices length exceeds proof bounds")) return false;
if (!reader->read_u64(&output->total_leaves)) return false;
if (!reader->read_hash(&output->root)) return false;
if (!read_hash_vector(reader, &output->siblings, "siblings length exceeds proof bounds")) return false;
return true;
}
bool read_matrix(Reader* reader, MatrixProof* output) {
if (!read_merkle(reader, &output->proof)) return false;
return read_u64_vector(reader, &output->rows, "row_indices length exceeds proof bounds");
}
bool parse_plain(const uint8_t* data, size_t length, PlainProof* output, bool* legacy, std::string* error) {
if (data == nullptr || length == 0 || length > MAX_PROOF_BYTES) {
*error = "proof length is outside the bounded V3 range";
return false;
}
Reader reader(data, length);
if (!reader.read_u64(&output->m) || !reader.read_u64(&output->n) ||
!reader.read_u64(&output->k) || !reader.read_u64(&output->noise_rank) ||
!read_matrix(&reader, &output->a) || !read_matrix(&reader, &output->bt)) {
*error = reader.error();
return false;
}
output->has_moe = false;
output->legacy_dense = false;
if (reader.remaining() == 0) {
// V1 dense blobs omitted the trailing serde Option tag. V3 keeps this
// compatibility accepted, but the canonical identity appends 0x00.
output->legacy_dense = true;
*legacy = true;
return true;
}
uint8_t option_tag = 0;
if (!reader.read_u8(&option_tag)) {
*error = reader.error();
return false;
}
if (option_tag == 0) {
output->has_moe = false;
} else if (option_tag == 1) {
output->has_moe = true;
if (!reader.read_u64(&output->moe.experts) || !reader.read_u64(&output->moe.top_k) ||
!reader.read_u16(&output->moe.expert_index) ||
!read_u32_vector(&reader, &output->moe.routing_offsets, "routing offsets length exceeds proof bounds") ||
!read_u64_vector(&reader, &output->moe.inner_a_rows, "inner A rows length exceeds proof bounds") ||
!read_merkle(&reader, &output->moe.routing)) {
*error = reader.error();
return false;
}
} else {
*error = "invalid serde Option tag";
return false;
}
if (reader.remaining() != 0) {
*error = "trailing bytes after PlainProof";
return false;
}
*legacy = false;
return true;
}
bool validate_merkle_shape(const Merkle& proof, std::string* error) {
if (proof.total_leaves == 0) {
*error = "Merkle proof has no leaves";
return false;
}
if (proof.leaf_indices.empty() || proof.leaf_indices.size() != proof.leaves.size()) {
*error = "Merkle leaf indices/data are empty or mismatched";
return false;
}
for (size_t i = 0; i < proof.leaf_indices.size(); ++i) {
if (proof.leaf_indices[i] >= proof.total_leaves) {
*error = "Merkle leaf index is outside total_leaves";
return false;
}
if (i != 0 && proof.leaf_indices[i - 1] >= proof.leaf_indices[i]) {
*error = "Merkle leaf indices are not strictly sorted";
return false;
}
}
return true;
}
struct MerkleNode {
uint64_t index;
Hash value;
};
bool compute_merkle_root(const Merkle& proof, const Hash& key, Hash* output, std::string* error) {
if (!validate_merkle_shape(proof, error)) return false;
std::vector<MerkleNode> current;
current.reserve(proof.leaves.size());
for (size_t i = 0; i < proof.leaves.size(); ++i) {
current.push_back({proof.leaf_indices[i], pearl_blake3::chunk_cv(
proof.leaves[i].data(), proof.leaves[i].size(), proof.leaf_indices[i], key)});
}
size_t sibling_position = 0;
uint64_t level_length = proof.total_leaves;
if (level_length == 1) {
if (current.size() != 1 || current[0].index != 0 || !proof.siblings.empty()) {
*error = "invalid single-leaf Merkle proof";
return false;
}
// Pearl's MerkleTree hashes a <=1024-byte tree as a complete keyed
// BLAKE3 root (including ROOT), rather than exposing the non-root
// chunk chaining value used for multi-leaf trees.
*output = pearl_blake3::keyed_hash(
proof.leaves[0].data(), proof.leaves[0].size(), key);
return true;
}
while (level_length > 2) {
std::vector<MerkleNode> next;
next.reserve((current.size() + 1) / 2);
for (size_t i = 0; i < current.size(); ++i) {
const uint64_t index = current[i].index;
if ((index & 1u) != 0 && i > 0 && current[i - 1].index == index - 1) continue;
const Hash left = current[i].value;
Hash right{};
bool have_right = false;
if ((index & 1u) == 0) {
if (i + 1 < current.size() && current[i + 1].index == index + 1) {
right = current[i + 1].value;
have_right = true;
} else if (index + 1 < level_length) {
if (sibling_position >= proof.siblings.size()) {
*error = "Merkle proof is missing a sibling";
return false;
}
right = proof.siblings[sibling_position++];
have_right = true;
}
} else {
if (sibling_position >= proof.siblings.size()) {
*error = "Merkle proof is missing a left sibling";
return false;
}
right = left;
next.push_back({index / 2, pearl_blake3::parent_cv(
proof.siblings[sibling_position++], right, key, false)});
continue;
}
if (have_right) {
next.push_back({index / 2, pearl_blake3::parent_cv(left, right, key, false)});
} else {
next.push_back({index / 2, left});
}
}
current.swap(next);
// Avoid overflowing level_length + 1 for hostile wire values.
level_length = level_length / 2 + level_length % 2;
}
Hash left{};
Hash right{};
bool have_left = false;
bool have_right = false;
for (const auto& node : current) {
if (node.index == 0) {
left = node.value;
have_left = true;
} else if (node.index == 1) {
right = node.value;
have_right = true;
} else {
*error = "Merkle level has an invalid node index";
return false;
}
}
if (!have_left) {
if (sibling_position >= proof.siblings.size()) {
*error = "Merkle proof is missing the final left node";
return false;
}
left = proof.siblings[sibling_position++];
}
if (!have_right) {
if (sibling_position >= proof.siblings.size()) {
*error = "Merkle proof is missing the final right node";
return false;
}
right = proof.siblings[sibling_position++];
}
if (sibling_position != proof.siblings.size()) {
*error = "Merkle proof has trailing siblings (consumed " +
std::to_string(sibling_position) + " of " +
std::to_string(proof.siblings.size()) + ")";
return false;
}
*output = pearl_blake3::parent_cv(left, right, key, true);
return true;
}
bool extract_bytes(const Merkle& proof, uint64_t total_bytes, uint64_t start,
size_t length, std::vector<uint8_t>* output, std::string* error) {
uint64_t end = 0;
if (!checked_add_u64(start, static_cast<uint64_t>(length), &end) || end > total_bytes) {
*error = "requested bytes exceed the committed matrix";
return false;
}
output->assign(length, 0);
size_t copied = 0;
for (size_t i = 0; i < proof.leaf_indices.size(); ++i) {
uint64_t leaf_start = 0;
if (!checked_mul_u64(proof.leaf_indices[i], CHUNK, &leaf_start)) {
*error = "Merkle leaf byte offset overflow";
return false;
}
uint64_t leaf_end = 0;
if (!checked_add_u64(leaf_start, CHUNK, &leaf_end)) {
*error = "Merkle leaf byte end overflow";
return false;
}
if (leaf_start >= end) break;
if (start >= leaf_end) continue;
const uint64_t copy_start = std::max(start, leaf_start);
const uint64_t copy_end = std::min(end, leaf_end);
const size_t count = static_cast<size_t>(copy_end - copy_start);
const size_t output_offset = static_cast<size_t>(copy_start - start);
const size_t leaf_offset = static_cast<size_t>(copy_start - leaf_start);
std::memcpy(output->data() + output_offset, proof.leaves[i].data() + leaf_offset, count);
copied += count;
}
if (copied != length) {
*error = "Merkle proof does not cover the requested bytes";
return false;
}
return true;
}
bool pattern_from_list(const std::vector<uint64_t>& input, PatternInfo* output,
uint32_t* offset, std::string* error) {
if (input.empty() || input.size() > MAX_PATTERN_ITEMS) {
*error = "pattern has an unsupported number of indices";
return false;
}
std::vector<uint32_t> normalized;
normalized.reserve(input.size());
uint64_t first = input[0];
if (first > std::numeric_limits<uint32_t>::max()) {
*error = "pattern offset exceeds u32";
return false;
}
for (size_t i = 0; i < input.size(); ++i) {
if (input[i] > std::numeric_limits<uint32_t>::max() ||
(i != 0 && input[i - 1] >= input[i])) {
*error = "pattern indices are not sorted u32 values";
return false;
}
normalized.push_back(static_cast<uint32_t>(input[i] - first));
}
if (normalized[0] != 0) {
*error = "pattern does not start at zero after normalization";
return false;
}
std::vector<std::pair<uint32_t, uint32_t>> shapes;
std::vector<uint32_t> p = normalized;
while (p.size() > 1) {
bool found = false;
for (size_t period = 1; period < p.size(); ++period) {
if (p.size() % period != 0) continue;
const uint32_t stride = p[period];
bool periodic = true;
for (size_t i = 0; i + period < p.size(); ++i) {
if (static_cast<uint64_t>(p[i]) + stride != p[i + period]) {
periodic = false;
break;
}
}
if (periodic) {
shapes.emplace_back(stride, static_cast<uint32_t>(p.size() / period));
p.resize(period);
found = true;
break;
}
}
if (!found) {
*error = "pattern is not periodic";
return false;
}
}
if (shapes.size() > 3) {
*error = "pattern needs more than three dimensions";
return false;
}
std::reverse(shapes.begin(), shapes.end());
uint64_t period = shapes.empty() ? 1 : static_cast<uint64_t>(shapes.back().first) * shapes.back().second;
while (shapes.size() < 3) {
if (period > std::numeric_limits<uint32_t>::max()) {
*error = "pattern period overflows u32";
return false;
}
shapes.emplace_back(static_cast<uint32_t>(period), 1);
}
uint64_t min_stride = 1;
bool is_done = false;
uint64_t count = 1;
for (size_t i = 0; i < 3; ++i) {
const uint64_t stride = shapes[i].first;
const uint64_t length = shapes[i].second;
if (stride == 0 || length == 0 || stride % min_stride != 0) {
*error = "pattern contains an invalid stride";
return false;
}
const uint64_t factor = stride / min_stride;
if (factor == 0 || factor > 256 || length > 256 ||
min_stride > (1u << 24) / (factor * length)) {
*error = "pattern exceeds canonical bounds";
return false;
}
if (length == 1 || is_done) {
if (factor != 1 || length != 1) {
*error = "pattern has a non-canonical trailing dimension";
return false;
}
is_done = true;
} else if (factor == 1 && min_stride != 1) {
*error = "pattern splits a single stride";
return false;
}
output->stride[i] = static_cast<uint32_t>(stride);
output->length[i] = static_cast<uint32_t>(length);
output->bytes[2 * i] = static_cast<uint8_t>(factor - 1);
output->bytes[2 * i + 1] = static_cast<uint8_t>(length - 1);
if (!checked_mul_u64(count, length, &count) || count > MAX_PATTERN_ITEMS) {
*error = "pattern has too many indices";
return false;
}
if (!checked_mul_u64(min_stride, factor * length, &min_stride)) {
*error = "pattern stride overflow";
return false;
}
}
if (count != input.size()) {
*error = "pattern shape does not round-trip its index count";
return false;
}
output->count = static_cast<uint32_t>(count);
output->maximum = normalized.back();
*offset = static_cast<uint32_t>(first);
// This is the inverse of PeriodicPattern::to_list and also checks that
// the generated sequence is exactly the source sequence.
std::vector<uint32_t> generated(1, 0);
for (size_t i = 0; i < 3; ++i) {
std::vector<uint32_t> next;
next.reserve(generated.size() * output->length[i]);
for (uint32_t j = 0; j < output->length[i]; ++j) {
for (uint32_t value : generated) {
const uint64_t candidate = static_cast<uint64_t>(value) +
static_cast<uint64_t>(j) * output->stride[i];
if (candidate > std::numeric_limits<uint32_t>::max()) {
*error = "pattern index overflows u32";
return false;
}
next.push_back(static_cast<uint32_t>(candidate));
}
}
generated.swap(next);
}
if (generated != normalized) {
*error = "pattern is not canonical";
return false;
}
return true;
}
bool offset_is_valid(const PatternInfo& pattern, uint32_t offset) {
for (size_t i = pattern.stride.size(); i-- > 0;) {
const uint64_t period = static_cast<uint64_t>(pattern.stride[i]) * pattern.length[i];
if (period == 0) return false;
offset = static_cast<uint32_t>(offset % period);
if (offset >= pattern.stride[i]) return false;
}
return true;
}
bool expected_leaves(uint64_t rows, uint64_t cols, uint64_t* output) {
uint64_t bytes = 0;
uint64_t padded = 0;
if (!checked_mul_u64(rows, cols, &bytes) || !padded_bytes(bytes, &padded)) return false;
*output = padded / CHUNK;
return true;
}
bool check_tree_size(const Merkle& proof, uint64_t expected, const char* label, std::string* error) {
if (proof.total_leaves != expected) {
*error = std::string(label) + " Merkle total_leaves does not match dimensions";
return false;
}
return validate_merkle_shape(proof, error);
}
bool u32_from_u64(uint64_t value, uint32_t* out, const char* label, std::string* error) {
if (value > std::numeric_limits<uint32_t>::max()) {
*error = label;
return false;
}
*out = static_cast<uint32_t>(value);
return true;
}
bool sanity_check(const PlainProof& proof, const PatternInfo& rows, uint32_t t_rows,
const PatternInfo& cols, uint32_t t_cols, uint32_t total_b_cols,
std::string* error) {
const uint64_t m = proof.m;
const uint64_t n = proof.n;
const uint64_t k = proof.k;
const uint64_t rank = proof.noise_rank;
const uint64_t h = rows.count;
const uint64_t w = cols.count;
// The production V3 softfork applies the rank work-factor rule only to
// ranks at or above the 128 baseline. Keep the upstream shape checks too.
if (m > MAX_M || n > MAX_N || k > MAX_K || rank < 128 || rank > 1024 ||
(rank & (rank - 1)) != 0 || rank % 16 != 0) {
*error = "V3 dimensions or noise rank are outside public bounds";
return false;
}
if (k % 64 != 0 || k < 1024 || k < 16 * rank || k > 4 * rank * rank) {
*error = "V3 common dimension/rank constraints failed";
return false;
}
const uint64_t dot = k - (k % rank);
if (dot % 8 != 0 || h % 2 != 0 || w % 2 != 0 || h * w < 32 || h * w > 256) {
*error = "V3 tile or dot-product constraints failed";
return false;
}
if ((h + w) * dot > (1u << 22)) {
*error = "V3 worker input bound exceeded";
return false;
}
if (static_cast<uint64_t>(t_rows) + rows.maximum >= m ||
static_cast<uint64_t>(t_cols) + cols.maximum >= n ||
m == 0 || n == 0) {
*error = "V3 pattern offset exceeds matrix dimensions";
return false;
}
if (!proof.has_moe) return true;
const MoeProof& moe = proof.moe;
if (moe.experts == 0 || moe.top_k == 0 || moe.experts > MAX_EXPERTS ||
moe.top_k >= moe.experts || moe.expert_index >= moe.experts ||
moe.routing_offsets.size() != moe.experts ||
proof.bt.rows.size() >= proof.n ||
static_cast<uint64_t>(proof.n) * moe.experts > MAX_N) {
*error = "MoE public configuration constraints failed";
return false;
}
uint64_t routing_entries = 0;
if (!checked_mul_u64(m, moe.top_k, &routing_entries) || routing_entries > UINT32_MAX ||
moe.routing_offsets.empty() || moe.routing_offsets.back() != routing_entries) {
*error = "MoE routing entry count is invalid";
return false;
}
for (size_t i = 0; i < moe.routing_offsets.size(); ++i) {
if (i != 0 && moe.routing_offsets[i - 1] > moe.routing_offsets[i]) {
*error = "MoE routing offsets are not monotonic";
return false;
}
if (moe.routing_offsets[i] > routing_entries ||
(i != 0 && static_cast<uint64_t>(moe.routing_offsets[i] - moe.routing_offsets[i - 1]) > m) ||
(i == 0 && moe.routing_offsets[i] > m)) {
*error = "MoE routing offset exceeds its per-expert bound";
return false;
}
}
const uint64_t expert_start = moe.expert_index == 0 ? 0 : moe.routing_offsets[moe.expert_index - 1];
const uint64_t expert_end = moe.routing_offsets[moe.expert_index];
if (moe.inner_a_rows.size() != proof.a.rows.size() || rows.count != moe.inner_a_rows.size()) {
*error = "MoE inner and outer A row counts differ";
return false;
}
if (proof.a.rows.size() != rows.count) {
*error = "A row count does not match rows pattern";
return false;
}
for (size_t i = 0; i < proof.a.rows.size(); ++i) {
if (proof.a.rows[i] >= m || moe.inner_a_rows[i] >= expert_end - expert_start ||
expert_start + moe.inner_a_rows[i] >= routing_entries ||
expert_start + moe.inner_a_rows[i] >= expert_end) {
*error = "MoE A/routing index is outside the selected expert region";
return false;
}
}
const uint64_t column_offset = static_cast<uint64_t>(moe.expert_index) * proof.n;
for (uint64_t index : proof.bt.rows) {
if (index < column_offset || index >= column_offset + proof.n) {
*error = "MoE B row is outside the selected expert columns";
return false;
}
}
if (moe.experts * proof.n > MAX_N) {
*error = "MoE total columns exceed 24-bit bound";
return false;
}
for (size_t i = 1; i < proof.a.rows.size(); ++i) {
if (proof.a.rows[i - 1] >= proof.a.rows[i] || moe.inner_a_rows[i - 1] >= moe.inner_a_rows[i]) {
*error = "MoE A rows are not strictly sorted";
return false;
}
}
(void)total_b_cols;
return true;
}
uint32_t load_u32(const uint8_t* data) {
return static_cast<uint32_t>(data[0]) |
static_cast<uint32_t>(data[1]) << 8 |
static_cast<uint32_t>(data[2]) << 16 |
static_cast<uint32_t>(data[3]) << 24;
}
void store_u32(uint8_t* data, uint32_t value) {
data[0] = static_cast<uint8_t>(value);
data[1] = static_cast<uint8_t>(value >> 8);
data[2] = static_cast<uint8_t>(value >> 16);
data[3] = static_cast<uint8_t>(value >> 24);
}
std::vector<uint8_t> make_config_bytes(uint32_t k, uint16_t rank,
const PatternInfo& rows, const PatternInfo& cols,
bool moe, uint16_t experts, uint16_t top_k) {
std::vector<uint8_t> bytes(52, 0);
store_u32(bytes.data(), k);
bytes[4] = static_cast<uint8_t>(rank);
bytes[5] = static_cast<uint8_t>(rank >> 8);
// MMAType::Int7xInt7ToInt32 is enum value zero.
std::memcpy(bytes.data() + 8, rows.bytes.data(), rows.bytes.size());
std::memcpy(bytes.data() + 14, cols.bytes.data(), cols.bytes.size());
if (moe) {
bytes[20] = static_cast<uint8_t>(experts);
bytes[21] = static_cast<uint8_t>(experts >> 8);
bytes[22] = static_cast<uint8_t>(top_k);
bytes[23] = static_cast<uint8_t>(top_k >> 8);
}
return bytes;
}
Hash hash_concat(const uint8_t* first, size_t first_length,
const uint8_t* second, size_t second_length) {
std::vector<uint8_t> bytes;
bytes.reserve(first_length + second_length);
bytes.insert(bytes.end(), first, first + first_length);
bytes.insert(bytes.end(), second, second + second_length);
return pearl_blake3::hash(bytes);
}
Hash bind_root(const Hash& root, uint32_t dimension, const Hash& salt) {
std::array<uint8_t, 64> message{};
std::memcpy(message.data(), root.data(), root.size());
store_u32(message.data() + 32, dimension);
return pearl_blake3::keyed_hash(message.data(), message.size(), salt);
}
const Hash SEED_SALT_A = {
0x82, 0x49, 0x40, 0x6c, 0xa0, 0xed, 0x15, 0x16,
0x96, 0x16, 0xf6, 0x92, 0xfc, 0xf0, 0x76, 0xf8,
0x92, 0xdb, 0xdb, 0x2a, 0x70, 0x23, 0xb8, 0x52,
0xf0, 0xd4, 0x77, 0x19, 0xc3, 0x90, 0x01, 0x7b
};
const Hash SEED_SALT_B = {
0x11, 0x30, 0x06, 0x32, 0xec, 0x63, 0x01, 0xca,
0x2b, 0xe2, 0xaf, 0x71, 0x8b, 0x3f, 0x4d, 0x4f,
0x1a, 0xe9, 0xc6, 0x39, 0x88, 0xe8, 0xcc, 0x04,
0x48, 0x44, 0x30, 0x1d, 0x71, 0xb8, 0x9a, 0xa9
};
const Hash SEED_LABEL_A = {
'A', '_', 't', 'e', 'n', 's', 'o', 'r',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
const Hash SEED_LABEL_B = {
'B', '_', 't', 'e', 'n', 's', 'o', 'r',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
bool random_hash(uint64_t index, const Hash& seed, const Hash& key,
unsigned prepend_index, Hash* output, std::string* error) {
if (prepend_index > 1 || index >= static_cast<uint64_t>(INT32_MAX)) {
*error = "noise hash index exceeds signed V3 bounds";
return false;
}
std::array<uint8_t, 64> message{};
const int32_t value = static_cast<int32_t>(index + 1);
store_u32(message.data() + prepend_index * 4, static_cast<uint32_t>(value));
std::memcpy(message.data() + 32, seed.data(), seed.size());
*output = pearl_blake3::keyed_hash(message.data(), message.size(), key);
return true;
}
bool uniform_row(uint64_t row, uint32_t rank, const Hash& seed, const Hash& key,
std::vector<int16_t>* output, std::string* error) {
uint64_t start = 0;
uint64_t end = 0;
if (!checked_mul_u64(row, rank, &start) || !checked_add_u64(start, rank, &end)) {
*error = "uniform noise index overflow";
return false;
}
const uint64_t first_block = start / 32;
const uint64_t last_block = (end + 31) / 32;
output->clear();
output->reserve(rank);
for (uint64_t block = first_block; block < last_block; ++block) {
Hash random{};
if (!random_hash(block, seed, key, 0, &random, error)) return false;
for (size_t byte = 0; byte < random.size(); ++byte) {
const uint64_t index = block * 32 + byte;
if (index >= start && index < end) {
output->push_back(static_cast<int16_t>(static_cast<int>(random[byte] & 63u) - 32));
}
}
}
if (output->size() != rank) {
*error = "uniform noise row has the wrong length";
return false;
}
return true;
}
uint32_t mul_hi_u32(uint32_t a, uint32_t b) {
return static_cast<uint32_t>((static_cast<uint64_t>(a) * b) >> 32);
}
bool permutation(uint32_t k, uint32_t rank, const Hash& seed, const Hash& key,
std::vector<std::pair<uint32_t, uint32_t>>* output, std::string* error) {
output->clear();
output->resize(k);
const uint32_t mask = rank - 1;
for (uint32_t i = 0; i < k; ++i) {
Hash random{};
if ((i % 8) == 0 && !random_hash(i / 8, seed, key, 1, &random, error)) return false;
// Keep the hash for the current eight entries without a second keyed
// call. The fixed-size cache is reconstructed per group below.
if ((i % 8) == 0) {
for (uint32_t j = 0; j < 8 && i + j < k; ++j) {
const uint32_t random_value = load_u32(random.data() + j * 4);
const uint32_t first = random_value & mask;
const uint32_t second = first ^ (1u + mul_hi_u32(mask, random_value));
(*output)[i + j] = {first, second};
}
i += 7;
}
}
return true;
}
bool signed_strips(const Merkle& proof, const std::vector<uint64_t>& indices,
uint64_t k, size_t strip_length, uint64_t total_bytes,
std::vector<std::vector<int16_t>>* output, std::string* error) {
output->clear();
output->reserve(indices.size());
for (uint64_t index : indices) {
uint64_t start = 0;
if (!checked_mul_u64(index, k, &start)) {
*error = "matrix strip offset overflow";
return false;
}
std::vector<uint8_t> bytes;
if (!extract_bytes(proof, total_bytes, start, strip_length, &bytes, error)) return false;
std::vector<int16_t> strip;
strip.reserve(bytes.size());
for (uint8_t byte : bytes) {
const int value = byte < 128 ? byte : static_cast<int>(byte) - 256;
if (value < -64 || value > 64) {
*error = "matrix strip value is outside [-64, 64]";
return false;
}
strip.push_back(static_cast<int16_t>(value));
}
output->push_back(std::move(strip));
}
return true;
}
bool compute_jackpot(const PlainProof& proof, const ConfigInfo& config,
const Hash& a_noise_seed, const Hash& b_noise_seed,
const std::vector<std::vector<int16_t>>& secret_a,
const std::vector<std::vector<int16_t>>& secret_b,
Hash* jackpot_hash, std::string* error) {
const uint32_t h = config.rows_pattern.count;
const uint32_t w = config.cols_pattern.count;
const uint32_t k = config.k;
const uint32_t rank = config.rank;
std::vector<std::vector<int16_t>> noise_a(h, std::vector<int16_t>(k));
std::vector<std::vector<int16_t>> noise_b(w, std::vector<int16_t>(k));
std::vector<std::pair<uint32_t, uint32_t>> perm_a;
std::vector<std::pair<uint32_t, uint32_t>> perm_b;
if (!permutation(k, rank, SEED_LABEL_A, a_noise_seed, &perm_a, error) ||
!permutation(k, rank, SEED_LABEL_B, b_noise_seed, &perm_b, error)) return false;
const std::vector<uint64_t>& a_indices = proof.a.rows;
const std::vector<uint64_t>& b_indices = proof.bt.rows;
if (a_indices.size() != h || b_indices.size() != w ||
secret_a.size() != h || secret_b.size() != w) {
*error = "matrix strip count does not match the public pattern";
return false;
}
for (uint32_t i = 0; i < h; ++i) {
std::vector<int16_t> uniform;
if (!uniform_row(a_indices[i], rank, SEED_LABEL_A, a_noise_seed, &uniform, error)) return false;
for (uint32_t l = 0; l < k; ++l) {
const auto pair = perm_a[l];
noise_a[i][l] = static_cast<int16_t>(uniform[pair.first] - uniform[pair.second]);
}
}
for (uint32_t i = 0; i < w; ++i) {
std::vector<int16_t> uniform;
if (!uniform_row(b_indices[i], rank, SEED_LABEL_B, b_noise_seed, &uniform, error)) return false;
for (uint32_t l = 0; l < k; ++l) {
const auto pair = perm_b[l];
noise_b[i][l] = static_cast<int16_t>(uniform[pair.first] - uniform[pair.second]);
}
}
std::vector<int64_t> accum(static_cast<size_t>(h) * w, 0);
std::array<uint32_t, 16> jackpot{};
const uint32_t dot = k - (k % rank);
for (uint32_t ll = rank; ll <= dot; ll += rank) {
const uint32_t begin = ll - rank;
for (uint32_t u = 0; u < h; ++u) {
for (uint32_t v = 0; v < w; ++v) {
int64_t& value = accum[static_cast<size_t>(u) * w + v];
for (uint32_t l = begin; l < ll; ++l) {
const int64_t a = secret_a[u][l] + noise_a[u][l];
const int64_t b = secret_b[v][l] + noise_b[v][l];
value += a * b;
}
}
}
uint32_t xored_tile = 0;
for (int64_t value : accum) xored_tile ^= static_cast<uint32_t>(value);
const uint32_t tid = ((ll / rank) - 1) % 16;
jackpot[tid] = (jackpot[tid] << 13) | (jackpot[tid] >> 19);
jackpot[tid] ^= xored_tile;
}
std::array<uint8_t, 64> message{};
for (size_t i = 0; i < jackpot.size(); ++i) store_u32(message.data() + i * 4, jackpot[i]);
*jackpot_hash = pearl_blake3::keyed_hash(message.data(), message.size(), a_noise_seed);
return true;
}
bool scale_target(const uint8_t* target, uint64_t factor, Hash* output) {
if (output == nullptr) return false;
output->fill(0);
uint64_t carry = 0;
for (size_t i = 0; i < 8; ++i) {
const uint32_t input = load_u32(target + i * 4);
// factor is checked to fit u32 before reaching this function, so the
// product plus carry is strictly below 2^64 and needs no wider type.
const uint64_t product = static_cast<uint64_t>(input) * factor + carry;
store_u32(output->data() + i * 4, static_cast<uint32_t>(product));
carry = product >> 32;
}
// A full-width pool share target is not a compact consensus target. If
// scaling it does not fit in 256 bits, the share target is unusable; do