forked from microsoft/merklecpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerklecpp.h
2597 lines (2297 loc) · 78.2 KB
/
merklecpp.h
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <array>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <list>
#include <memory>
#include <sstream>
#include <stack>
#include <variant>
#include <vector>
#ifdef HAVE_OPENSSL
# include <openssl/sha.h>
#endif
#ifdef HAVE_MBEDTLS
# include <mbedtls/sha256.h>
#endif
#ifdef MERKLECPP_TRACE_ENABLED
// Hashes in the trace output are truncated to TRACE_HASH_SIZE bytes.
# define TRACE_HASH_SIZE 3
# ifndef MERKLECPP_TRACE
# include <iostream>
# define MERKLECPP_TOUT std::cout
# define MERKLECPP_TRACE(X) \
{ \
X; \
MERKLECPP_TOUT.flush(); \
};
# endif
#else
# define MERKLECPP_TRACE(X)
#endif
#define MERKLECPP_VERSION_MAJOR 1
#define MERKLECPP_VERSION_MINOR 0
#define MERKLECPP_VERSION_PATCH 0
namespace merkle
{
static inline uint32_t convert_endianness(uint32_t n)
{
const uint32_t sz = sizeof(uint32_t);
#if defined(htobe32)
// If htobe32 happens to be a macro, use it.
return htobe32(n);
#elif defined(__LITTLE_ENDIAN__) || defined(__LITTLE_ENDIAN)
// Just as fast.
uint32_t r = 0;
for (size_t i = 0; i < sz; i++)
r |= ((n >> (8 * ((sz - 1) - i))) & 0xFF) << (8 * i);
return *reinterpret_cast<uint32_t*>(&r);
#else
// A little slower, but works for both endiannesses.
uint8_t r[8];
for (size_t i = 0; i < sz; i++)
r[i] = (n >> (8 * ((sz - 1) - i))) & 0xFF;
return *reinterpret_cast<uint32_t*>(&r);
#endif
}
static inline void serialise_uint16_t(uint16_t n, std::vector<uint8_t>& bytes)
{
size_t sz = sizeof(uint16_t);
bytes.reserve(bytes.size() + sz);
for (uint64_t i = 0; i < sz; i++)
bytes.push_back((n >> (8 * (sz - i - 1))) & 0xFF);
}
static inline uint64_t deserialise_uint16_t(
const std::vector<uint8_t>& bytes, size_t& index)
{
uint16_t r = 0;
uint64_t sz = sizeof(uint16_t);
for (uint64_t i = 0; i < sz; i++)
r |= static_cast<uint16_t>(bytes.at(index++)) << (8 * (sz - i - 1));
return r;
}
static inline void serialise_uint64_t(uint64_t n, std::vector<uint8_t>& bytes)
{
size_t sz = sizeof(uint64_t);
bytes.reserve(bytes.size() + sz);
for (uint64_t i = 0; i < sz; i++)
bytes.push_back((n >> (8 * (sz - i - 1))) & 0xFF);
}
static inline uint64_t deserialise_uint64_t(
const std::vector<uint8_t>& bytes, size_t& index)
{
uint64_t r = 0;
uint64_t sz = sizeof(uint64_t);
for (uint64_t i = 0; i < sz; i++)
r |= static_cast<uint64_t>(bytes.at(index++)) << (8 * (sz - i - 1));
return r;
}
/// @brief Template for fixed-size hashes
/// @tparam SIZE Size of the hash in number of bytes
template <size_t SIZE>
struct HashT
{
/// Holds the hash bytes
uint8_t bytes[SIZE];
/// @brief Constructs a Hash with all bytes set to zero
HashT<SIZE>()
{
std::fill(bytes, bytes + SIZE, 0);
}
/// @brief Constructs a canonical representation of the first i bits of
/// hash, padded with 10*
HashT<SIZE> copy_prefix(const size_t i) const
{
HashT<SIZE> res;
std::copy(this->bytes, this->bytes + i / 8 + 1, res.bytes);
std::fill(res.bytes + i / 8 + 1, res.bytes + SIZE, 0);
res.bytes[i / 8] &= (255 >> (8 - i % 8));
res.set_bit(i, 1);
return res;
}
/// @brief Constructs a Hash from a byte buffer
/// @param bytes Buffer with hash value
HashT<SIZE>(const uint8_t* bytes)
{
std::copy(bytes, bytes + SIZE, this->bytes);
}
/// @brief Constructs a Hash from an integer
/// @param n0 provides the first bytes; the rest are zeros.
HashT<SIZE>(const size_t n)
{
auto len = sizeof(size_t);
if (len > SIZE)
printf("invalid hash constructor %lu %lu\n", SIZE, n);
else
{
std::memcpy(bytes, &n, len);
std::fill(bytes + len, bytes + SIZE, 0);
};
}
/// @brief Constructs a Hash from a string
/// @param s String to read the hash value from
HashT<SIZE>(const std::string& s)
{
if (s.length() != 2 * SIZE)
throw std::runtime_error("invalid hash string");
for (size_t i = 0; i < SIZE; i++)
{
int tmp;
sscanf(s.c_str() + 2 * i, "%02x", &tmp);
bytes[i] = tmp;
}
}
/// @brief Deserialises a Hash from a vector of bytes
/// @param bytes Vector to read the hash value from
HashT<SIZE>(const std::vector<uint8_t>& bytes)
{
if (bytes.size() < SIZE)
throw std::runtime_error("not enough bytes");
deserialise(bytes);
}
/// @brief Deserialises a Hash from a vector of bytes
/// @param bytes Vector to read the hash value from
/// @param position Position of the first byte in @p bytes
HashT<SIZE>(const std::vector<uint8_t>& bytes, size_t& position)
{
if (bytes.size() - position < SIZE)
throw std::runtime_error("not enough bytes");
deserialise(bytes, position);
}
/// @brief Deserialises a Hash from an array of bytes
/// @param bytes Array to read the hash value from
HashT<SIZE>(const std::array<uint8_t, SIZE>& bytes)
{
std::copy(bytes.data(), bytes.data() + SIZE, this->bytes);
}
/// @brief The size of the hash (in number of bytes)
size_t size() const
{
return SIZE;
}
/// @brief Reads the ith bit of the hash
inline bool bit(size_t i) const
{
return (bytes[i / 8] >> (i % 8)) & 1;
}
/// @brief Sets the ith bit of the hash
inline void set_bit(size_t i, bool b)
{
uint8_t mask = 1 << i % 8;
bytes[i / 8] = b ? (bytes[i / 8] | mask) : (bytes[i / 8] & ~mask);
}
/// @brief zeros out all bytes in the hash
void zero()
{
std::fill(bytes, bytes + SIZE, 0);
}
/// @brief The size of the serialisation of the hash (in number of bytes)
size_t serialised_size() const
{
return SIZE;
}
/// @brief Convert a hash to a hex-encoded string
/// @param num_bytes The maximum number of bytes to convert
/// @param lower_case Enables lower-case hex characters
std::string to_string(size_t num_bytes = SIZE, bool lower_case = true) const
{
size_t num_chars = 2 * num_bytes;
std::string r(num_chars, '_');
for (size_t i = 0; i < num_bytes; i++)
snprintf(
const_cast<char*>(r.data() + 2 * i),
num_chars + 1 - 2 * i,
lower_case ? "%02x" : "%02X",
bytes[i]);
return r;
}
/// @brief Convert a hash to a [01]* string
/// @param cut indicates how many bits to print
std::string to_bitstring(size_t n = SIZE * 8) const
{
size_t m = std::min<size_t>(n, 70); // truncate for readability
std::string r(m, '0');
for (size_t i = 0; i < m; i++)
r[i] = this->bit(i) ? '1' : '0';
if (m < n)
r += "...";
return r;
}
/// @brief Hash assignment operator
HashT<SIZE> operator=(const HashT<SIZE>& other)
{
std::copy(other.bytes, other.bytes + SIZE, bytes);
return *this;
}
/// @brief Hash equality operator
bool operator==(const HashT<SIZE>& other) const
{
return memcmp(bytes, other.bytes, SIZE) == 0;
}
/// @brief Hash inequality operator
bool operator!=(const HashT<SIZE>& other) const
{
return memcmp(bytes, other.bytes, SIZE) != 0;
}
/// @brief Serialises a hash
/// @param buffer Buffer to serialise to
void serialise(std::vector<uint8_t>& buffer) const
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> HashT::serialise " << std::endl);
for (auto& b : bytes)
buffer.push_back(b);
}
/// @brief Deserialises a hash
/// @param buffer Buffer to read the hash from
/// @param position Position of the first byte in @p bytes
void deserialise(const std::vector<uint8_t>& buffer, size_t& position)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> HashT::deserialise " << std::endl);
if (buffer.size() - position < SIZE)
throw std::runtime_error("not enough bytes");
for (size_t i = 0; i < sizeof(bytes); i++)
bytes[i] = buffer[position++];
}
/// @brief Deserialises a hash
/// @param buffer Buffer to read the hash from
void deserialise(const std::vector<uint8_t>& buffer)
{
size_t position = 0;
deserialise(buffer, position);
}
/// @brief Conversion operator to vector of bytes
operator std::vector<uint8_t>() const
{
std::vector<uint8_t> bytes;
serialise(bytes);
return bytes;
}
};
/// @brief Template for Merkle paths
/// @tparam HASH_SIZE Size of each hash in number of bytes
/// @tparam HASH_FUNCTION The hash function
template <
size_t HASH_SIZE,
void HASH_FUNCTION(
const HashT<HASH_SIZE>& l,
const HashT<HASH_SIZE>& r,
HashT<HASH_SIZE>& out)>
class PathT
{
public:
/// @brief Path direction
typedef enum
{
PATH_LEFT,
PATH_RIGHT
} Direction;
/// @brief Path element
typedef struct
{
/// @brief The hash of the path element
HashT<HASH_SIZE> hash;
/// @brief The direction at which @p hash joins at this path element
/// @note If @p direction == PATH_LEFT, @p hash joins at the left, i.e.
/// if t is the current hash, e.g. a leaf, then t' = Hash( @p hash, t );
Direction direction;
} Element;
/// @brief Path constructor
/// @param leaf
/// @param leaf_index
/// @param elements
/// @param max_index
PathT(
const HashT<HASH_SIZE>& leaf,
size_t leaf_index,
std::list<Element>&& elements,
size_t max_index) :
_leaf(leaf),
_leaf_index(leaf_index),
_max_index(max_index),
elements(elements)
{}
/// @brief Path copy constructor
/// @param other Path to copy
PathT(const PathT& other)
{
_leaf = other._leaf;
elements = other.elements;
}
/// @brief Path move constructor
/// @param other Path to move
PathT(PathT&& other)
{
_leaf = std::move(other._leaf);
elements = std::move(other.elements);
}
/// @brief Deserialises a path
/// @param bytes Vector to deserialise from
PathT(const std::vector<uint8_t>& bytes)
{
deserialise(bytes);
}
/// @brief Deserialises a path
/// @param bytes Vector to deserialise from
/// @param position Position of the first byte in @p bytes
PathT(const std::vector<uint8_t>& bytes, size_t& position)
{
deserialise(bytes, position);
}
/// @brief Computes the root at the end of the path
/// @note This (re-)computes the root by hashing the path elements, it does
/// not return a previously saved root hash.
std::shared_ptr<HashT<HASH_SIZE>> root() const
{
std::shared_ptr<HashT<HASH_SIZE>> result =
std::make_shared<HashT<HASH_SIZE>>(_leaf);
MERKLECPP_TRACE(
MERKLECPP_TOUT << "> PathT::root " << _leaf.to_string(TRACE_HASH_SIZE)
<< std::endl);
for (const Element& e : elements)
{
if (e.direction == PATH_LEFT)
{
MERKLECPP_TRACE(
MERKLECPP_TOUT << " - " << e.hash.to_string(TRACE_HASH_SIZE)
<< " x " << result->to_string(TRACE_HASH_SIZE)
<< std::endl);
HASH_FUNCTION(e.hash, *result, *result);
}
else
{
MERKLECPP_TRACE(
MERKLECPP_TOUT << " - " << result->to_string(TRACE_HASH_SIZE)
<< " x " << e.hash.to_string(TRACE_HASH_SIZE)
<< std::endl);
HASH_FUNCTION(*result, e.hash, *result);
}
}
MERKLECPP_TRACE(
MERKLECPP_TOUT << " = " << result->to_string(TRACE_HASH_SIZE)
<< std::endl);
return result;
}
/// @brief Verifies that the root at the end of the path is expected
/// @param expected_root The root hash that the elements on the path are
/// expected to hash to.
bool verify(const HashT<HASH_SIZE>& expected_root) const
{
return *root() == expected_root;
}
/// @brief Serialises a path
/// @param bytes Vector of bytes to serialise to
void serialise(std::vector<uint8_t>& bytes) const
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> PathT::serialise " << std::endl);
_leaf.serialise(bytes);
serialise_uint64_t(_leaf_index, bytes);
serialise_uint64_t(_max_index, bytes);
serialise_uint64_t(elements.size(), bytes);
for (auto& e : elements)
{
e.hash.serialise(bytes);
bytes.push_back(e.direction == PATH_LEFT ? 1 : 0);
}
}
/// @brief Deserialises a path
/// @param bytes Vector of bytes to serialise from
/// @param position Position of the first byte in @p bytes
void deserialise(const std::vector<uint8_t>& bytes, size_t& position)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> PathT::deserialise " << std::endl);
elements.clear();
_leaf.deserialise(bytes, position);
_leaf_index = deserialise_uint64_t(bytes, position);
_max_index = deserialise_uint64_t(bytes, position);
size_t num_elements = deserialise_uint64_t(bytes, position);
for (size_t i = 0; i < num_elements; i++)
{
HashT<HASH_SIZE> hash(bytes, position);
PathT::Direction direction =
bytes[position++] != 0 ? PATH_LEFT : PATH_RIGHT;
PathT::Element e;
e.hash = hash;
e.direction = direction;
elements.push_back(std::move(e));
}
}
/// @brief Deserialises a path
/// @param bytes Vector of bytes to serialise from
void deserialise(const std::vector<uint8_t>& bytes)
{
size_t position = 0;
deserialise(bytes, position);
}
/// @brief Conversion operator to vector of bytes
operator std::vector<uint8_t>() const
{
std::vector<uint8_t> bytes;
serialise(bytes);
return bytes;
}
/// @brief The number of elements on the path
size_t size() const
{
return elements.size();
}
/// @brief The size of the serialised path in number of bytes
size_t serialised_size() const
{
return sizeof(_leaf) + elements.size() * sizeof(Element);
}
/// @brief Index of the leaf of the path
size_t leaf_index() const
{
return _leaf_index;
}
/// @brief Maximum index of the tree at the time the path was extracted
size_t max_index() const
{
return _max_index;
}
/// @brief Operator to extract the hash of a given path element
/// @param i Index of the path element
const HashT<HASH_SIZE>& operator[](size_t i) const
{
return std::next(begin(), i)->hash;
}
/// @brief Iterator for path elements
typedef typename std::list<Element>::const_iterator const_iterator;
/// @brief Start iterator for path elements
const_iterator begin() const
{
return elements.begin();
}
/// @brief End iterator for path elements
const_iterator end() const
{
return elements.end();
}
/// @brief Convert a path to a string
/// @param num_bytes The maximum number of bytes to convert
/// @param lower_case Enables lower-case hex characters
std::string to_string(
size_t num_bytes = HASH_SIZE, bool lower_case = true) const
{
std::stringstream stream;
stream << _leaf.to_string(num_bytes);
for (auto& e : elements)
stream << " " << e.hash.to_string(num_bytes, lower_case)
<< (e.direction == PATH_LEFT ? "(L)" : "(R)");
return stream.str();
}
/// @brief The leaf hash of the path
const HashT<HASH_SIZE>& leaf() const
{
return _leaf;
}
/// @brief Equality operator for paths
bool operator==(const PathT<HASH_SIZE, HASH_FUNCTION>& other) const
{
if (_leaf != other._leaf || elements.size() != other.elements.size())
return false;
auto it = elements.begin();
auto other_it = other.elements.begin();
while (it != elements.end() && other_it != other.elements.end())
{
if (it->hash != other_it->hash || it->direction != other_it->direction)
return false;
it++;
other_it++;
}
return true;
}
/// @brief Inequality operator for paths
bool operator!=(const PathT<HASH_SIZE, HASH_FUNCTION>& other)
{
return !this->operator==(other);
}
protected:
/// @brief The leaf hash
HashT<HASH_SIZE> _leaf;
/// @brief The index of the leaf
size_t _leaf_index;
/// @brief The maximum leaf index of the tree at the time of path extraction
size_t _max_index;
/// @brief The elements of the path
std::list<Element> elements;
};
/// @brief Template for Prefix Merkle paths
/// @tparam HASH_SIZE is the size of each hash output in number of bytes
/// @tparam HASH_NODE re-hashes a prefix and two hashes.
template <
size_t HASH_SIZE,
void HASH_NODE(
const HashT<HASH_SIZE>& prefix,
const HashT<HASH_SIZE>& left,
const HashT<HASH_SIZE>& right,
HashT<HASH_SIZE>& out)>
struct PPathT
{
public:
typedef HashT<HASH_SIZE> hash_t;
std::vector<hash_t> path;
void print()
{
printf("| %s | flags\n", path.at(0).to_string().c_str());
for (size_t i = 1; i < path.size(); i++)
printf("| %s |\n", path[i].to_string().c_str());
}
/// @brief Computes the root at the end of the path
hash_t root(const hash_t index, const hash_t leaf) const
{
printf(
"| %s | %s\n", leaf.to_string().c_str(), index.to_bitstring().c_str());
size_t pos = 0;
hash_t flags = path.at(pos++);
hash_t hash = leaf;
for (size_t i = 8 * HASH_SIZE - 1; i + 1 > 0;
i--) // todo improve iteration
{
if (flags.bit(i))
{
hash_t prefix = index.copy_prefix(i);
hash_t side = path.at(path.size() - pos++); // ugly reversal
if (index.bit(i))
HASH_NODE(prefix, side, hash, hash);
else
HASH_NODE(prefix, hash, side, hash);
printf(
"| %s | %s*\n",
hash.to_string().c_str(),
prefix.to_bitstring(i).c_str());
}
};
if (pos != path.size())
throw std::runtime_error("path is too long");
return hash;
}
/// @brief Verifies that the root at the end of the path is expected
/// @param expected_root The root hash that the elements on the path are
/// expected to hash to.
bool verify(const HashT<HASH_SIZE>& expected_root) const
{
return *root() == expected_root;
}
};
/// @brief Placeholder for the prefix tree leaves.
struct Leaf
{
size_t key;
size_t value;
Leaf(size_t k, size_t v)
{
key = k;
value = v;
};
Leaf()
{
Leaf(0, 0);
}
};
/// @brief Online prefix-tree-root computation, from a sorted stream of
/// leaves.
/// @note This yields the same hash as if we built a tree then computed its
/// root, but uses much less memory.
template <
size_t HASH_SIZE,
void HASH_KEY(size_t key, HashT<HASH_SIZE>& out),
void HASH_LEAF(Leaf leaf, HashT<HASH_SIZE>& out),
void HASH_NODE(
const HashT<HASH_SIZE>& prefix,
const HashT<HASH_SIZE>& left,
const HashT<HASH_SIZE>& right,
HashT<HASH_SIZE>& out)>
struct StreamT
{
public:
typedef HashT<HASH_SIZE> hash_t;
typedef struct
{
size_t
length; // prefix of a branch to be hashed with the rest of the stream
hash_t hash; // root of the corresponding sub-tree
} entry_t;
// Index of the last leaf we hashed.
hash_t index;
// Stack for all already-hashed leaves,
// ordered by strictly-increasing lengths.
// with at most one entry for each length such that index.bit[i] == 1
std::vector<entry_t> stack;
StreamT()
{
index.zero(); // starting from 0* for now
stack = {};
};
// Debug-only.
void print()
{
for (entry_t e : stack)
printf(
" %s | %s%s\n",
e.hash.to_string().c_str(),
index.to_bitstring(e.length).c_str(),
(e.length < 256 ? "0*" : ""));
printf("\n");
};
// Compresses the stack, now that we won't add any leaf with index p0*
// where p is the lenght-prefix of the current index
void compress(size_t length)
{
while (stack.size() >= 2 && stack[stack.size() - 2].length >= length)
{
entry_t last = stack.back();
stack.pop_back();
HashT prefix = index.copy_prefix(stack.back().length);
HASH_NODE(prefix, stack.back().hash, last.hash, stack.back().hash);
// printf("compressing %lu
// %s*\n",length,prefix.to_bitstring(stack.back().length).c_str());
// print();
};
if (stack.size() > 0 && stack.back().length > length)
stack.back().length = length;
};
// Adds a leaf to the stack.
// NB the hashed leaf key must be larger than the index.
void add(Leaf& leaf)
{
hash_t next;
HASH_KEY(leaf.key, next);
size_t i = 0;
while (i < HASH_SIZE * 8 && index.bit(i) == next.bit(i))
i++;
assert(i < HASH_SIZE * 8); // we expect leaves are passed in order!
compress(i);
index = next;
entry_t top;
top.length = 256;
HASH_LEAF(leaf, top.hash);
stack.push_back(top);
// print();
};
void root(hash_t& out)
{
compress(0);
out = stack.at(0).hash;
};
static void stream(size_t size, Leaf leaf[], hash_t& out)
{
auto s = StreamT();
for (size_t i = 0; i < size; i++)
s.add(leaf[i]);
s.root(out);
}
};
template <
size_t HASH_SIZE,
void HASH_KEY(size_t key, HashT<HASH_SIZE>& out),
void HASH_LEAF(Leaf leaf, HashT<HASH_SIZE>& out),
void HASH_NODE(
const HashT<HASH_SIZE>& prefix,
const HashT<HASH_SIZE>& left,
const HashT<HASH_SIZE>& right,
HashT<HASH_SIZE>& out)>
struct PTreeT
{
public:
typedef HashT<HASH_SIZE> hash_t;
std::vector<hash_t> path;
typedef StreamT<HASH_SIZE, HASH_KEY, HASH_LEAF, HASH_NODE> stream_t;
static inline auto hash_key = HASH_KEY;
static inline auto hash_leaf = HASH_LEAF;
struct Node
{
/// @brief The longest prefix shared between all leaves in this subtree,
/// of length 0..8*HASH_SIZE - 1, skewed towards 0
uint8_t length;
hash_t prefix;
/// @brief The children, for now with explicit tagging between
/// intermediate nodes and leaves
std::variant<Node*, Leaf*> child[2];
/// @brief The children hashes, when available
hash_t chash[2];
/// @brief Dirty flag for the hash
/// @note The @p hash is only correct if this flag is false, otherwise
/// it needs to be computed by calling hash() on the node.
/// would a variant be better?
bool dirty;
static inline void vardel(std::variant<Node*, Leaf*> x)
{
if (x.index() == 0)
delete (std::get<0>(x));
else
delete (std::get<1>(x));
}
~Node()
{
// printf("deleting node\n");
vardel(child[0]);
vardel(child[1]);
}
};
typedef std::variant<Node*, Leaf*> position;
/// @brief Computes the root
static void root(const position x, hash_t& out)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
if (node->dirty)
{
root(node->child[0], node->chash[0]);
root(node->child[1], node->chash[1]);
node->dirty = 0;
}
HASH_NODE(node->prefix, node->chash[0], node->chash[1], out);
// printf("| %s | %s*\n",
// out.to_string().c_str(),node->prefix.to_bitstring(node->length).c_str());
}
else
{
auto leaf = std::get<Leaf*>(x);
HASH_LEAF(*leaf, out);
// printf("| %s | key=%lu value=%lu.\n", out.to_string().c_str(),
// leaf->key, leaf->value);
};
}
// TODO avoid copying prefix bytes
static void get_prefix(size_t& length, hash_t& prefix, position x)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
length = node->length;
prefix = HashT<HASH_SIZE>(node->prefix.bytes);
}
else
{
auto leaf = std::get<Leaf*>(x);
length = HASH_SIZE * 8;
HASH_KEY(leaf->key, prefix);
}
// printf("prefix=%s\n",prefix.to_bitstring(length).c_str());
};
static void stats(
position x, size_t hist[2 * HASH_SIZE], size_t depth = 0, int length = -1)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
hist[HASH_SIZE * 8 + node->length - length]++;
stats(node->child[0], hist, depth + 1, node->length);
stats(node->child[1], hist, depth + 1, node->length);
}
else
hist[depth]++;
}
static void print(position x, size_t depth = 0)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
print(node->child[0], depth + 1);
printf(
"%3lu |%s*\n",
depth,
node->prefix.to_bitstring(node->length).c_str());
print(node->child[1], depth + 1);
}
else
{
auto leaf = std::get<Leaf*>(x);
hash_t index;
HASH_KEY(leaf->key, index);
printf(
"%3lu |%s key=%lu value=%lu.\n",
depth,
index.to_bitstring().c_str(),
leaf->key,
leaf->value);
}
}
/// @brief Inserts (or updates) an entry, ignoring hashes for now.
static void insert(const Leaf leaf, position* pos)
{
hash_t index;
HASH_KEY(leaf.key, index);
// printf("index= %s\n",index.to_bitstring().c_str());
size_t length;
hash_t prefix;
get_prefix(length, prefix, *pos);
for (size_t i = 0; i < 8 * HASH_SIZE; i++)
{
bool b = index.bit(i);
// printf("i=%2lu b=%d.\n",i,b);
if (i == length) // usually no need to look at the prefix
{
// we matched this node's prefix, we insert the leaf below (recursive
// case)
auto node = std::get<Node*>(*pos);
pos = &(node->child[b]);
get_prefix(length, prefix, *pos);
}
else if (prefix.bit(i) != b)
{
// we mismatched this node (or leaf), we create a node above with
// prefix length i.
Node* fresh = new Node();
fresh->length = i;
fresh->dirty = 1; // and don't initialize chash
fresh->prefix = prefix.copy_prefix(i);
fresh->child[b] = new Leaf(leaf);
fresh->child[1 - b] = *pos;
*pos = fresh;
return;
};
}
// we found an existing leaf; we update it.
Leaf* found = std::get<Leaf*>(*pos);
assert(found->key == leaf.key);
found->value = leaf.value;
}
static void stream0(position x, stream_t& s)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
stream0(node->child[0], s);
stream0(node->child[1], s);
}
else
{
auto leaf = std::get<Leaf*>(x);
hash_t index;
HASH_KEY(leaf->key, index);
// printf(" + %s key=%lu
// value=%lu.\n",index.to_bitstring().c_str(),leaf->key, leaf->value);
s.add(*leaf);
}
}
static void extract(position x, Leaf l[], size_t& i)
{
if (x.index() == 0)
{
auto node = std::get<Node*>(x);
extract(node->child[0], l, i);
extract(node->child[1], l, i);
}
else
{
Leaf leaf = *std::get<Leaf*>(x);
l[i++] = leaf;
// printf("k=%4zu v=%4zu\n", (**l).key, (**l).value);
}
}
static void stream(position x, hash_t& out)
{
auto s = stream_t();
stream0(x, s);
s.root(out);
}
static PPathT<HASH_SIZE, HASH_NODE> get_path(const size_t key, position x)
{