forked from microsoft/merklecpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merklecpp.h
1966 lines (1723 loc) · 60.9 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 <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_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[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 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 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 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 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 Merkle trees
/// @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 TreeT
{
protected:
/// @brief The structure of tree nodes
struct Node
{
/// @brief Constructs a new tree node
/// @param hash The hash of the node
static Node* make(const HashT<HASH_SIZE>& hash)
{
auto r = new Node();
r->left = r->right = nullptr;
r->hash = hash;
r->dirty = false;
r->update_sizes();
assert(r->invariant());
return r;
}
/// @brief Constructs a new tree node
/// @param left The left child of the new node
/// @param right The right child of the new node
static Node* make(Node* left, Node* right)
{
assert(left && right);
auto r = new Node();
r->left = left;
r->right = right;
r->dirty = true;
r->update_sizes();
assert(r->invariant());
return r;
}
/// @brief Copies a tree node
/// @param from Node to copy
/// @param leaf_nodes Current leaf nodes of the tree
/// @param num_flushed Number of flushed nodes of the tree
/// @param min_index Minimum leaf index of the tree
/// @param max_index Maximum leaf index of the tree
/// @param indent Indentation of trace output
static Node* copy_node(
const Node* from,
std::vector<Node*>* leaf_nodes = nullptr,
size_t* num_flushed = nullptr,
size_t min_index = 0,
size_t max_index = SIZE_MAX,
size_t indent = 0)
{
if (from == nullptr)
return nullptr;
Node* r = make(from->hash);
r->size = from->size;
r->height = from->height;
r->dirty = from->dirty;
r->left = copy_node(
from->left,
leaf_nodes,
num_flushed,
min_index,
max_index,
indent + 1);
r->right = copy_node(
from->right,
leaf_nodes,
num_flushed,
min_index,
max_index,
indent + 1);
if (leaf_nodes && r->size == 1 && !r->left && !r->right)
{
if (*num_flushed == 0)
leaf_nodes->push_back(r);
else
*num_flushed = *num_flushed - 1;
}
return r;
}
/// @brief Checks invariant of a tree node
/// @note This indicates whether some basic properties of the tree
/// construction are violated.
bool invariant()
{
bool c1 = (left && right) || (!left && !right);
bool c2 = !left || !right || (size == left->size + right->size + 1);
bool cl = !left || left->invariant();
bool cr = !right || right->invariant();
bool ch = height <= sizeof(size) * 8;
bool r = c1 && c2 && cl && cr && ch;
return r;
}
~Node()
{
assert(invariant());
// Potential future improvement: remove recursion and keep nodes for
// future insertions
delete (left);
delete (right);
}
/// @brief Indicates whether a subtree is full
/// @note A subtree is full if the number of nodes under a tree is
/// 2**height-1.
bool is_full() const
{
size_t max_size = (1 << height) - 1;
assert(size <= max_size);
return size == max_size;
}
/// @brief Updates the tree size and height of the subtree under a node
void update_sizes()
{
if (left && right)
{
size = left->size + right->size + 1;
height = std::max(left->height, right->height) + 1;
}
else
size = height = 1;
}
/// @brief The Hash of the node
HashT<HASH_SIZE> hash;
/// @brief The left child of the node
Node* left;
/// @brief The right child of the node
Node* right;
/// @brief The size of the subtree
size_t size;
/// @brief The height of the subtree
uint8_t height;
/// @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.
bool dirty;
};
public:
/// @brief The type of hashes in the tree
typedef HashT<HASH_SIZE> Hash;
/// @brief The type of paths in the tree
typedef PathT<HASH_SIZE, HASH_FUNCTION> Path;
/// @brief The type of the tree
typedef TreeT<HASH_SIZE, HASH_FUNCTION> Tree;
/// @brief Constructs an empty tree
TreeT() {}
/// @brief Copies a tree
TreeT(const TreeT& other)
{
*this = other;
}
/// @brief Moves a tree
/// @param other Tree to move
TreeT(TreeT&& other) :
leaf_nodes(std::move(other.leaf_nodes)),
uninserted_leaf_nodes(std::move(other.uninserted_leaf_nodes)),
_root(std::move(other._root)),
num_flushed(other.num_flushed),
insertion_stack(std::move(other.insertion_stack)),
hashing_stack(std::move(other.hashing_stack)),
walk_stack(std::move(other.walk_stack))
{}
/// @brief Deserialises a tree
/// @param bytes Byte buffer containing a serialised tree
TreeT(const std::vector<uint8_t>& bytes)
{
deserialise(bytes);
}
/// @brief Deserialises a tree
/// @param bytes Byte buffer containing a serialised tree
/// @param position Position of the first byte within @p bytes
TreeT(const std::vector<uint8_t>& bytes, size_t& position)
{
deserialise(bytes, position);
}
/// @brief Constructs a tree containing one root hash
/// @param root Root hash of the tree
TreeT(const Hash& root)
{
insert(root);
}
/// @brief Deconstructor
~TreeT()
{
delete (_root);
for (auto n : uninserted_leaf_nodes)
delete (n);
}
/// @brief Invariant of the tree
bool invariant()
{
return _root ? _root->invariant() : true;
}
/// @brief Inserts a hash into the tree
/// @param hash Hash to insert
void insert(const uint8_t* hash)
{
insert(Hash(hash));
}
/// @brief Inserts a hash into the tree
/// @param hash Hash to insert
void insert(const Hash& hash)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> insert "
<< hash.to_string(TRACE_HASH_SIZE)
<< std::endl;);
uninserted_leaf_nodes.push_back(Node::make(hash));
statistics.num_insert++;
}
/// @brief Inserts multiple hashes into the tree
/// @param hashes Vector of hashes to insert
void insert(const std::vector<Hash>& hashes)
{
for (auto hash : hashes)
insert(hash);
}
/// @brief Inserts multiple hashes into the tree
/// @param hashes List of hashes to insert
void insert(const std::list<Hash>& hashes)
{
for (auto hash : hashes)
insert(hash);
}
/// @brief Flush the tree to some leaf
/// @param index Leaf index to flush the tree to
/// @note This invalidates all indicies smaller than @p index and
/// no paths from them to the root can be extracted anymore.
void flush_to(size_t index)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> flush_to " << index << std::endl;);
statistics.num_flush++;
if (index <= min_index())
return;
walk_to(index, false, [this](Node*& n, bool go_right) {
if (go_right && n->left)
{
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - conflate "
<< n->left->hash.to_string(TRACE_HASH_SIZE)
<< std::endl;);
if (n->left && n->left->dirty)
hash(n->left);
delete (n->left->left);
n->left->left = nullptr;
delete (n->left->right);
n->left->right = nullptr;
}
return true;
});
size_t num_newly_flushed = index - num_flushed;
leaf_nodes.erase(
leaf_nodes.begin(), leaf_nodes.begin() + num_newly_flushed);
num_flushed += num_newly_flushed;
}
/// @brief Retracts a tree up to some leaf index
/// @param index Leaf index to retract the tree to
/// @note This invalidates all indicies greater than @p index and
/// no paths from them to the root can be extracted anymore.
void retract_to(size_t index)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> retract_to " << index << std::endl;);
statistics.num_retract++;
if (max_index() < index)
return;
if (index < min_index())
throw std::runtime_error("leaf index out of bounds");
if (index >= num_flushed + leaf_nodes.size())
{
size_t over = index - (num_flushed + leaf_nodes.size()) + 1;
while (uninserted_leaf_nodes.size() > over)
{
delete (uninserted_leaf_nodes.back());
uninserted_leaf_nodes.pop_back();
}
return;
}
Node* new_leaf_node =
walk_to(index, true, [this](Node*& n, bool go_right) {
bool go_left = !go_right;
n->dirty = true;
if (go_left && n->right)
{
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - eliminate "
<< n->right->hash.to_string(TRACE_HASH_SIZE)
<< std::endl;);
bool is_root = n == _root;
Node* old_left = n->left;
delete (n->right);
n->right = nullptr;
*n = *old_left;
old_left->left = old_left->right = nullptr;
delete (old_left);
old_left = nullptr;
if (n->left && n->right)
n->dirty = true;
if (is_root)
{
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - new root: "
<< n->hash.to_string(TRACE_HASH_SIZE)
<< std::endl;);
assert(_root == n);
}
assert(n->invariant());
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - after elimination: " << std::endl
<< to_string(TRACE_HASH_SIZE) << std::endl;);
return false;
}
else
return true;
});
// The leaf is now elsewhere, save the pointer.
leaf_nodes[index - num_flushed] = new_leaf_node;
size_t num_retracted = num_leaves() - index - 1;
if (num_retracted < leaf_nodes.size())
leaf_nodes.resize(leaf_nodes.size() - num_retracted);
else
leaf_nodes.clear();
assert(num_leaves() == index + 1);
}
/// @brief Assigns a tree
/// @param other The tree to assign
/// @return The tree
Tree& operator=(const Tree& other)
{
leaf_nodes.clear();
for (auto n : uninserted_leaf_nodes)
delete (n);
uninserted_leaf_nodes.clear();
insertion_stack.clear();
hashing_stack.clear();
walk_stack.clear();
size_t to_skip = (other.num_flushed % 2 == 0) ? 0 : 1;
_root = Node::copy_node(
other._root,
&leaf_nodes,
&to_skip,
other.min_index(),
other.max_index());
for (auto n : other.uninserted_leaf_nodes)
uninserted_leaf_nodes.push_back(Node::copy_node(n));
num_flushed = other.num_flushed;
assert(min_index() == other.min_index());
assert(max_index() == other.max_index());
return *this;
}
/// @brief Extracts the root hash of the tree
/// @return The root hash
const Hash& root()
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> root" << std::endl;);
statistics.num_root++;
compute_root();
assert(_root && !_root->dirty);
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - root: " << _root->hash.to_string(TRACE_HASH_SIZE)
<< std::endl;);
return _root->hash;
}
/// @brief Extracts a past root hash
/// @param index The last leaf index to consider
/// @return The root hash
/// @note This extracts the root hash of the tree at a past state, when
/// @p index was the last, right-most leaf index in the tree. It is
/// equivalent to retracting the tree to @p index and then extracting the
/// root.
std::shared_ptr<Hash> past_root(size_t index)
{
MERKLECPP_TRACE(MERKLECPP_TOUT << "> past_root " << index << std::endl;);
statistics.num_past_root++;
auto p = path(index);
auto result = std::make_shared<Hash>(p->leaf());
MERKLECPP_TRACE(
MERKLECPP_TOUT << " - " << p->to_string(TRACE_HASH_SIZE) << std::endl;
MERKLECPP_TOUT << " - " << result->to_string(TRACE_HASH_SIZE)
<< std::endl;);
for (auto e : *p)
if (e.direction == Path::Direction::PATH_LEFT)
HASH_FUNCTION(e.hash, *result, *result);
return result;
}
/// @brief Walks along the path from the root of a tree to a leaf
/// @param index The leaf index to walk to
/// @param update Flag to enable re-computation of node fields (like
/// subtree size) while walking
/// @param f Function to call for each node on the path; the Boolean
/// indicates whether the current step is a right or left turn.
/// @return The final leaf node in the walk
inline Node* walk_to(
size_t index, bool update, const std::function<bool(Node*&, bool)>&& f)
{
if (index < min_index() || max_index() < index)
throw std::runtime_error("invalid leaf index");
compute_root();
assert(index < _root->size);
Node* cur = _root;
size_t it = 0;
if (_root->height > 1)
it = index << (sizeof(index) * 8 - _root->height + 1);
assert(walk_stack.empty());
for (uint8_t height = _root->height; height > 1;)
{
assert(cur->invariant());
bool go_right = (it >> (8 * sizeof(it) - 1)) & 0x01;
if (update)
walk_stack.push_back(cur);
MERKLECPP_TRACE(MERKLECPP_TOUT
<< " - at " << cur->hash.to_string(TRACE_HASH_SIZE)
<< " (" << cur->size << "/" << (unsigned)cur->height
<< ")"
<< " (" << (go_right ? "R" : "L") << ")"
<< std::endl;);
if (cur->height == height)
{
if (!f(cur, go_right))
continue;
cur = (go_right ? cur->right : cur->left);
}
it <<= 1;
height--;
}