-
Notifications
You must be signed in to change notification settings - Fork 2k
/
data_store.py
2009 lines (1792 loc) · 84.9 KB
/
data_store.py
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
from __future__ import annotations
import contextlib
import logging
from collections import defaultdict
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, AsyncIterator, Awaitable, BinaryIO, Callable, Dict, List, Optional, Set, Tuple, Union
import aiosqlite
from chia.data_layer.data_layer_errors import KeyNotFoundError, NodeHashError, TreeGenerationIncrementingError
from chia.data_layer.data_layer_util import (
DiffData,
InsertResult,
InternalNode,
KeysPaginationData,
KeysValuesCompressed,
KeysValuesPaginationData,
KVDiffPaginationData,
Node,
NodeType,
OperationType,
ProofOfInclusion,
ProofOfInclusionLayer,
Root,
SerializedNode,
ServerInfo,
Side,
Status,
Subscription,
TerminalNode,
get_hashes_for_page,
internal_hash,
key_hash,
leaf_hash,
row_to_node,
)
from chia.types.blockchain_format.program import Program
from chia.types.blockchain_format.sized_bytes import bytes32
from chia.util.db_wrapper import DBWrapper2
log = logging.getLogger(__name__)
# TODO: review exceptions for values that shouldn't be displayed
# TODO: pick exception types other than Exception
@dataclass
class DataStore:
"""A key/value store with the pairs being terminal nodes in a CLVM object tree."""
db_wrapper: DBWrapper2
@classmethod
@contextlib.asynccontextmanager
async def managed(
cls, database: Union[str, Path], uri: bool = False, sql_log_path: Optional[Path] = None
) -> AsyncIterator[DataStore]:
async with DBWrapper2.managed(
database=database,
uri=uri,
journal_mode="WAL",
# Setting to FULL despite other locations being configurable. If there are
# performance issues we can consider other the implications of other options.
synchronous="FULL",
# If foreign key checking gets turned off, please add corresponding check
# methods and enable foreign key checking in the tests.
foreign_keys=True,
row_factory=aiosqlite.Row,
log_path=sql_log_path,
) as db_wrapper:
self = cls(db_wrapper=db_wrapper)
async with db_wrapper.writer() as writer:
await writer.execute(
f"""
CREATE TABLE IF NOT EXISTS node(
hash BLOB PRIMARY KEY NOT NULL CHECK(length(hash) == 32),
node_type INTEGER NOT NULL CHECK(
(
node_type == {int(NodeType.INTERNAL)}
AND left IS NOT NULL
AND right IS NOT NULL
AND key IS NULL
AND value IS NULL
)
OR
(
node_type == {int(NodeType.TERMINAL)}
AND left IS NULL
AND right IS NULL
AND key IS NOT NULL
AND value IS NOT NULL
)
),
left BLOB REFERENCES node,
right BLOB REFERENCES node,
key BLOB,
value BLOB
)
"""
)
await writer.execute(
"""
CREATE TRIGGER IF NOT EXISTS no_node_updates
BEFORE UPDATE ON node
BEGIN
SELECT RAISE(FAIL, 'updates not allowed to the node table');
END
"""
)
await writer.execute(
f"""
CREATE TABLE IF NOT EXISTS root(
tree_id BLOB NOT NULL CHECK(length(tree_id) == 32),
generation INTEGER NOT NULL CHECK(generation >= 0),
node_hash BLOB,
status INTEGER NOT NULL CHECK(
{" OR ".join(f"status == {status}" for status in Status)}
),
PRIMARY KEY(tree_id, generation),
FOREIGN KEY(node_hash) REFERENCES node(hash)
)
"""
)
# TODO: Add ancestor -> hash relationship, this might involve temporarily
# deferring the foreign key enforcement due to the insertion order
# and the node table also enforcing a similar relationship in the
# other direction.
# FOREIGN KEY(ancestor) REFERENCES ancestors(ancestor)
await writer.execute(
"""
CREATE TABLE IF NOT EXISTS ancestors(
hash BLOB NOT NULL REFERENCES node,
ancestor BLOB CHECK(length(ancestor) == 32),
tree_id BLOB NOT NULL CHECK(length(tree_id) == 32),
generation INTEGER NOT NULL,
PRIMARY KEY(hash, tree_id, generation),
FOREIGN KEY(ancestor) REFERENCES node(hash)
)
"""
)
await writer.execute(
"""
CREATE TABLE IF NOT EXISTS subscriptions(
tree_id BLOB NOT NULL CHECK(length(tree_id) == 32),
url TEXT,
ignore_till INTEGER,
num_consecutive_failures INTEGER,
from_wallet tinyint CHECK(from_wallet == 0 OR from_wallet == 1),
PRIMARY KEY(tree_id, url)
)
"""
)
await writer.execute(
"""
CREATE INDEX IF NOT EXISTS node_hash ON root(node_hash)
"""
)
await writer.execute(
"""
CREATE INDEX IF NOT EXISTS node_key_index ON node(key)
"""
)
yield self
@asynccontextmanager
async def transaction(self) -> AsyncIterator[None]:
async with self.db_wrapper.writer():
yield
async def _insert_root(
self,
tree_id: bytes32,
node_hash: Optional[bytes32],
status: Status,
generation: Optional[int] = None,
) -> Root:
# This should be replaced by an SQLite schema level check.
# https://github.com/Chia-Network/chia-blockchain/pull/9284
tree_id = bytes32(tree_id)
async with self.db_wrapper.writer() as writer:
if generation is None:
try:
existing_generation = await self.get_tree_generation(tree_id=tree_id)
except Exception as e:
if not str(e).startswith("No generations found for tree ID:"):
raise
generation = 0
else:
generation = existing_generation + 1
new_root = Root(
tree_id=tree_id,
node_hash=None if node_hash is None else node_hash,
generation=generation,
status=status,
)
await writer.execute(
"""
INSERT INTO root(tree_id, generation, node_hash, status)
VALUES(:tree_id, :generation, :node_hash, :status)
""",
new_root.to_row(),
)
# `node_hash` is now a root, so it has no ancestor.
# Don't change the ancestor table unless the root is committed.
if node_hash is not None and status == Status.COMMITTED:
values = {
"hash": node_hash,
"tree_id": tree_id,
"generation": generation,
}
await writer.execute(
"""
INSERT INTO ancestors(hash, ancestor, tree_id, generation)
VALUES (:hash, NULL, :tree_id, :generation)
""",
values,
)
return new_root
async def _insert_node(
self,
node_hash: bytes32,
node_type: NodeType,
left_hash: Optional[bytes32],
right_hash: Optional[bytes32],
key: Optional[bytes],
value: Optional[bytes],
) -> None:
# TODO: can we get sqlite to do this check?
values = {
"hash": node_hash,
"node_type": node_type,
"left": left_hash,
"right": right_hash,
"key": key,
"value": value,
}
async with self.db_wrapper.writer() as writer:
try:
await writer.execute(
"""
INSERT INTO node(hash, node_type, left, right, key, value)
VALUES(:hash, :node_type, :left, :right, :key, :value)
""",
values,
)
except aiosqlite.IntegrityError as e:
if not e.args[0].startswith("UNIQUE constraint"):
# UNIQUE constraint failed: node.hash
raise
async with writer.execute(
"SELECT * FROM node WHERE hash == :hash LIMIT 1",
{"hash": node_hash},
) as cursor:
result = await cursor.fetchone()
if result is None:
# some ideas for causes:
# an sqlite bug
# bad queries in this function
# unexpected db constraints
raise Exception("Unable to find conflicting row") from e # pragma: no cover
result_dict = dict(result)
if result_dict != values:
raise Exception(
f"Requested insertion of node with matching hash but other values differ: {node_hash}"
) from None
async def insert_node(self, node_type: NodeType, value1: bytes, value2: bytes) -> None:
if node_type == NodeType.INTERNAL:
left_hash = bytes32(value1)
right_hash = bytes32(value2)
node_hash = internal_hash(left_hash, right_hash)
await self._insert_node(node_hash, node_type, bytes32(value1), bytes32(value2), None, None)
else:
node_hash = leaf_hash(key=value1, value=value2)
await self._insert_node(node_hash, node_type, None, None, value1, value2)
async def _insert_internal_node(self, left_hash: bytes32, right_hash: bytes32) -> bytes32:
node_hash: bytes32 = internal_hash(left_hash=left_hash, right_hash=right_hash)
await self._insert_node(
node_hash=node_hash,
node_type=NodeType.INTERNAL,
left_hash=left_hash,
right_hash=right_hash,
key=None,
value=None,
)
return node_hash
async def _insert_ancestor_table(
self,
left_hash: bytes32,
right_hash: bytes32,
tree_id: bytes32,
generation: int,
) -> None:
node_hash = internal_hash(left_hash=left_hash, right_hash=right_hash)
async with self.db_wrapper.writer() as writer:
for hash in (left_hash, right_hash):
values = {
"hash": hash,
"ancestor": node_hash,
"tree_id": tree_id,
"generation": generation,
}
try:
await writer.execute(
"""
INSERT INTO ancestors(hash, ancestor, tree_id, generation)
VALUES (:hash, :ancestor, :tree_id, :generation)
""",
values,
)
except aiosqlite.IntegrityError as e:
if not e.args[0].startswith("UNIQUE constraint"):
# UNIQUE constraint failed: ancestors.hash, ancestors.tree_id, ancestors.generation
raise
async with writer.execute(
"""
SELECT *
FROM ancestors
WHERE hash == :hash AND generation == :generation AND tree_id == :tree_id
LIMIT 1
""",
{"hash": hash, "generation": generation, "tree_id": tree_id},
) as cursor:
result = await cursor.fetchone()
if result is None:
# some ideas for causes:
# an sqlite bug
# bad queries in this function
# unexpected db constraints
raise Exception("Unable to find conflicting row") from e # pragma: no cover
result_dict = dict(result)
if result_dict != values:
raise Exception(
"Requested insertion of ancestor, where ancestor differ, but other values are identical: "
f"{hash} {generation} {tree_id}"
) from None
async def _insert_terminal_node(self, key: bytes, value: bytes) -> bytes32:
# forcing type hint here for:
# https://github.com/Chia-Network/clvm/pull/102
# https://github.com/Chia-Network/clvm/pull/106
node_hash: bytes32 = Program.to((key, value)).get_tree_hash()
await self._insert_node(
node_hash=node_hash,
node_type=NodeType.TERMINAL,
left_hash=None,
right_hash=None,
key=key,
value=value,
)
return node_hash
async def get_pending_root(self, tree_id: bytes32) -> Optional[Root]:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute(
"""
SELECT * FROM root WHERE tree_id == :tree_id
AND status IN (:pending_status, :pending_batch_status) LIMIT 2
""",
{
"tree_id": tree_id,
"pending_status": Status.PENDING.value,
"pending_batch_status": Status.PENDING_BATCH.value,
},
)
row = await cursor.fetchone()
if row is None:
return None
maybe_extra_result = await cursor.fetchone()
if maybe_extra_result is not None:
raise Exception(f"multiple pending roots found for id: {tree_id.hex()}")
return Root.from_row(row=row)
async def clear_pending_roots(self, tree_id: bytes32) -> Optional[Root]:
async with self.db_wrapper.writer() as writer:
pending_root = await self.get_pending_root(tree_id=tree_id)
if pending_root is not None:
await writer.execute(
"DELETE FROM root WHERE tree_id == :tree_id AND status IN (:pending_status, :pending_batch_status)",
{
"tree_id": tree_id,
"pending_status": Status.PENDING.value,
"pending_batch_status": Status.PENDING_BATCH.value,
},
)
return pending_root
async def shift_root_generations(self, tree_id: bytes32, shift_size: int) -> None:
async with self.db_wrapper.writer():
root = await self.get_tree_root(tree_id=tree_id)
for _ in range(shift_size):
await self._insert_root(tree_id=tree_id, node_hash=root.node_hash, status=Status.COMMITTED)
async def change_root_status(self, root: Root, status: Status = Status.PENDING) -> None:
async with self.db_wrapper.writer() as writer:
await writer.execute(
"UPDATE root SET status = ? WHERE tree_id=? and generation = ?",
(
status.value,
root.tree_id,
root.generation,
),
)
# `node_hash` is now a root, so it has no ancestor.
# Don't change the ancestor table unless the root is committed.
if root.node_hash is not None and status == Status.COMMITTED:
values = {
"hash": root.node_hash,
"tree_id": root.tree_id,
"generation": root.generation,
}
await writer.execute(
"""
INSERT INTO ancestors(hash, ancestor, tree_id, generation)
VALUES (:hash, NULL, :tree_id, :generation)
""",
values,
)
async def check(self) -> None:
for check in self._checks:
# pylint seems to think these are bound methods not unbound methods.
await check(self) # pylint: disable=too-many-function-args
async def _check_roots_are_incrementing(self) -> None:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute("SELECT * FROM root ORDER BY tree_id, generation")
roots = [Root.from_row(row=row) async for row in cursor]
roots_by_tree: Dict[bytes32, List[Root]] = defaultdict(list)
for root in roots:
roots_by_tree[root.tree_id].append(root)
bad_trees = []
for tree_id, roots in roots_by_tree.items():
current_generation = roots[-1].generation
expected_generations = list(range(current_generation + 1))
actual_generations = [root.generation for root in roots]
if actual_generations != expected_generations:
bad_trees.append(tree_id)
if len(bad_trees) > 0:
raise TreeGenerationIncrementingError(tree_ids=bad_trees)
async def _check_hashes(self) -> None:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute("SELECT * FROM node")
bad_node_hashes: List[bytes32] = []
async for row in cursor:
node = row_to_node(row=row)
if isinstance(node, InternalNode):
expected_hash = internal_hash(left_hash=node.left_hash, right_hash=node.right_hash)
elif isinstance(node, TerminalNode):
expected_hash = Program.to((node.key, node.value)).get_tree_hash()
if node.hash != expected_hash:
bad_node_hashes.append(node.hash)
if len(bad_node_hashes) > 0:
raise NodeHashError(node_hashes=bad_node_hashes)
_checks: Tuple[Callable[[DataStore], Awaitable[None]], ...] = (
_check_roots_are_incrementing,
_check_hashes,
)
async def create_tree(self, tree_id: bytes32, status: Status = Status.PENDING) -> bool:
await self._insert_root(tree_id=tree_id, node_hash=None, status=status)
return True
async def table_is_empty(self, tree_id: bytes32) -> bool:
tree_root = await self.get_tree_root(tree_id=tree_id)
return tree_root.node_hash is None
async def get_tree_ids(self) -> Set[bytes32]:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute("SELECT DISTINCT tree_id FROM root")
tree_ids = {bytes32(row["tree_id"]) async for row in cursor}
return tree_ids
async def get_tree_generation(self, tree_id: bytes32) -> int:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute(
"SELECT MAX(generation) FROM root WHERE tree_id == :tree_id AND status == :status",
{"tree_id": tree_id, "status": Status.COMMITTED.value},
)
row = await cursor.fetchone()
if row is not None:
generation: Optional[int] = row["MAX(generation)"]
if generation is not None:
return generation
raise Exception(f"No generations found for tree ID: {tree_id.hex()}")
async def get_tree_root(self, tree_id: bytes32, generation: Optional[int] = None) -> Root:
async with self.db_wrapper.reader() as reader:
if generation is None:
generation = await self.get_tree_generation(tree_id=tree_id)
cursor = await reader.execute(
"""
SELECT *
FROM root
WHERE tree_id == :tree_id AND generation == :generation AND status == :status
LIMIT 1
""",
{"tree_id": tree_id, "generation": generation, "status": Status.COMMITTED.value},
)
row = await cursor.fetchone()
if row is None:
raise Exception(f"unable to find root for id, generation: {tree_id.hex()}, {generation}")
return Root.from_row(row=row)
async def tree_id_exists(self, tree_id: bytes32) -> bool:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute(
"SELECT 1 FROM root WHERE tree_id == :tree_id AND status == :status LIMIT 1",
{"tree_id": tree_id, "status": Status.COMMITTED.value},
)
row = await cursor.fetchone()
if row is None:
return False
return True
async def get_roots_between(self, tree_id: bytes32, generation_begin: int, generation_end: int) -> List[Root]:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute(
"SELECT * FROM root WHERE tree_id == :tree_id "
"AND generation >= :generation_begin AND generation < :generation_end ORDER BY generation ASC",
{"tree_id": tree_id, "generation_begin": generation_begin, "generation_end": generation_end},
)
roots = [Root.from_row(row=row) async for row in cursor]
return roots
async def get_last_tree_root_by_hash(
self, tree_id: bytes32, hash: Optional[bytes32], max_generation: Optional[int] = None
) -> Optional[Root]:
async with self.db_wrapper.reader() as reader:
max_generation_str = f"AND generation < {max_generation} " if max_generation is not None else ""
node_hash_str = "AND node_hash == :node_hash " if hash is not None else "AND node_hash is NULL "
cursor = await reader.execute(
"SELECT * FROM root WHERE tree_id == :tree_id "
f"{max_generation_str}"
f"{node_hash_str}"
"ORDER BY generation DESC LIMIT 1",
{"tree_id": tree_id, "node_hash": None if hash is None else hash},
)
row = await cursor.fetchone()
if row is None:
return None
return Root.from_row(row=row)
async def get_ancestors(
self,
node_hash: bytes32,
tree_id: bytes32,
root_hash: Optional[bytes32] = None,
) -> List[InternalNode]:
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id)
root_hash = root.node_hash
if root_hash is None:
raise Exception(f"Root hash is unspecified for tree ID: {tree_id.hex()}")
cursor = await reader.execute(
"""
WITH RECURSIVE
tree_from_root_hash(hash, node_type, left, right, key, value, depth) AS (
SELECT node.*, 0 AS depth FROM node WHERE node.hash == :root_hash
UNION ALL
SELECT node.*, tree_from_root_hash.depth + 1 AS depth FROM node, tree_from_root_hash
WHERE node.hash == tree_from_root_hash.left OR node.hash == tree_from_root_hash.right
),
ancestors(hash, node_type, left, right, key, value, depth) AS (
SELECT node.*, NULL AS depth FROM node
WHERE node.left == :reference_hash OR node.right == :reference_hash
UNION ALL
SELECT node.*, NULL AS depth FROM node, ancestors
WHERE node.left == ancestors.hash OR node.right == ancestors.hash
)
SELECT * FROM tree_from_root_hash INNER JOIN ancestors
WHERE tree_from_root_hash.hash == ancestors.hash
ORDER BY tree_from_root_hash.depth DESC
""",
{"reference_hash": node_hash, "root_hash": root_hash},
)
# The resulting rows must represent internal nodes. InternalNode.from_row()
# does some amount of validation in the sense that it will fail if left
# or right can't turn into a bytes32 as expected. There is room for more
# validation here if desired.
ancestors = [InternalNode.from_row(row=row) async for row in cursor]
return ancestors
async def get_ancestors_optimized(
self,
node_hash: bytes32,
tree_id: bytes32,
generation: Optional[int] = None,
root_hash: Optional[bytes32] = None,
) -> List[InternalNode]:
async with self.db_wrapper.reader():
nodes = []
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id, generation=generation)
root_hash = root.node_hash
if root_hash is None:
return []
while True:
internal_node = await self._get_one_ancestor(node_hash, tree_id, generation)
if internal_node is None:
break
nodes.append(internal_node)
node_hash = internal_node.hash
if len(nodes) > 0:
if root_hash != nodes[-1].hash:
raise RuntimeError("Ancestors list didn't produce the root as top result.")
return nodes
async def get_internal_nodes(self, tree_id: bytes32, root_hash: Optional[bytes32] = None) -> List[InternalNode]:
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id)
root_hash = root.node_hash
cursor = await reader.execute(
"""
WITH RECURSIVE
tree_from_root_hash(hash, node_type, left, right, key, value) AS (
SELECT node.* FROM node WHERE node.hash == :root_hash
UNION ALL
SELECT node.* FROM node, tree_from_root_hash WHERE node.hash == tree_from_root_hash.left
OR node.hash == tree_from_root_hash.right
)
SELECT * FROM tree_from_root_hash
WHERE node_type == :node_type
""",
{"root_hash": None if root_hash is None else root_hash, "node_type": NodeType.INTERNAL},
)
internal_nodes: List[InternalNode] = []
async for row in cursor:
node = row_to_node(row=row)
if not isinstance(node, InternalNode):
raise Exception(f"Unexpected internal node found: {node.hash.hex()}")
internal_nodes.append(node)
return internal_nodes
async def get_keys_values_cursor(
self, reader: aiosqlite.Connection, root_hash: Optional[bytes32]
) -> aiosqlite.Cursor:
return await reader.execute(
"""
WITH RECURSIVE
tree_from_root_hash(hash, node_type, left, right, key, value, depth, rights) AS (
SELECT node.*, 0 AS depth, 0 AS rights FROM node WHERE node.hash == :root_hash
UNION ALL
SELECT
node.*,
tree_from_root_hash.depth + 1 AS depth,
CASE
WHEN node.hash == tree_from_root_hash.right
THEN tree_from_root_hash.rights + (1 << (62 - tree_from_root_hash.depth))
ELSE tree_from_root_hash.rights
END AS rights
FROM node, tree_from_root_hash
WHERE node.hash == tree_from_root_hash.left OR node.hash == tree_from_root_hash.right
)
SELECT * FROM tree_from_root_hash
WHERE node_type == :node_type
ORDER BY depth ASC, rights ASC
""",
{"root_hash": root_hash, "node_type": NodeType.TERMINAL},
)
async def get_keys_values(self, tree_id: bytes32, root_hash: Optional[bytes32] = None) -> List[TerminalNode]:
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id)
root_hash = root.node_hash
cursor = await self.get_keys_values_cursor(reader, root_hash)
terminal_nodes: List[TerminalNode] = []
async for row in cursor:
if row["depth"] > 62:
# TODO: Review the value and implementation of left-to-right order
# reporting. Initial use is for balanced insertion with the
# work done in the query.
# This is limited based on the choice of 63 for the maximum left
# shift in the query. This is in turn based on the SQLite integers
# ranging in size up to signed 8 bytes, 64 bits. If we exceed this then
# we no longer guarantee the left-to-right ordering of the node
# list. While 63 allows for a lot of nodes in a balanced tree, in
# the worst case it allows only 62 terminal nodes.
raise Exception("Tree depth exceeded 62, unable to guarantee left-to-right node order.")
node = row_to_node(row=row)
if not isinstance(node, TerminalNode):
raise Exception(f"Unexpected internal node found: {node.hash.hex()}")
terminal_nodes.append(node)
return terminal_nodes
async def get_keys_values_compressed(
self, tree_id: bytes32, root_hash: Optional[bytes32] = None
) -> KeysValuesCompressed:
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id)
root_hash = root.node_hash
cursor = await self.get_keys_values_cursor(reader, root_hash)
keys_values_hashed: Dict[bytes32, bytes32] = {}
key_hash_to_length: Dict[bytes32, int] = {}
leaf_hash_to_length: Dict[bytes32, int] = {}
async for row in cursor:
if row["depth"] > 62:
raise Exception("Tree depth exceeded 62, unable to guarantee left-to-right node order.")
node = row_to_node(row=row)
if not isinstance(node, TerminalNode):
raise Exception(f"Unexpected internal node found: {node.hash.hex()}")
keys_values_hashed[key_hash(node.key)] = leaf_hash(node.key, node.value)
key_hash_to_length[key_hash(node.key)] = len(node.key)
leaf_hash_to_length[leaf_hash(node.key, node.value)] = len(node.key) + len(node.value)
return KeysValuesCompressed(keys_values_hashed, key_hash_to_length, leaf_hash_to_length, root_hash)
async def get_keys_paginated(
self, tree_id: bytes32, page: int, max_page_size: int, root_hash: Optional[bytes32] = None
) -> KeysPaginationData:
keys_values_compressed = await self.get_keys_values_compressed(tree_id, root_hash)
pagination_data = get_hashes_for_page(page, keys_values_compressed.key_hash_to_length, max_page_size)
keys: List[bytes] = []
for hash in pagination_data.hashes:
leaf_hash = keys_values_compressed.keys_values_hashed[hash]
node = await self.get_node(leaf_hash)
assert isinstance(node, TerminalNode)
keys.append(node.key)
return KeysPaginationData(
pagination_data.total_pages,
pagination_data.total_bytes,
keys,
keys_values_compressed.root_hash,
)
async def get_keys_values_paginated(
self, tree_id: bytes32, page: int, max_page_size: int, root_hash: Optional[bytes32] = None
) -> KeysValuesPaginationData:
keys_values_compressed = await self.get_keys_values_compressed(tree_id, root_hash)
pagination_data = get_hashes_for_page(page, keys_values_compressed.leaf_hash_to_length, max_page_size)
keys_values: List[TerminalNode] = []
for hash in pagination_data.hashes:
node = await self.get_node(hash)
assert isinstance(node, TerminalNode)
keys_values.append(node)
return KeysValuesPaginationData(
pagination_data.total_pages,
pagination_data.total_bytes,
keys_values,
keys_values_compressed.root_hash,
)
async def get_kv_diff_paginated(
self, tree_id: bytes32, page: int, max_page_size: int, hash1: bytes32, hash2: bytes32
) -> KVDiffPaginationData:
old_pairs = await self.get_keys_values_compressed(tree_id, hash1)
new_pairs = await self.get_keys_values_compressed(tree_id, hash2)
if len(old_pairs.keys_values_hashed) == 0 and hash1 != bytes32([0] * 32):
return KVDiffPaginationData(1, 0, [])
if len(new_pairs.keys_values_hashed) == 0 and hash2 != bytes32([0] * 32):
return KVDiffPaginationData(1, 0, [])
old_pairs_leaf_hashes = {v for v in old_pairs.keys_values_hashed.values()}
new_pairs_leaf_hashes = {v for v in new_pairs.keys_values_hashed.values()}
insertions = {k for k in new_pairs_leaf_hashes if k not in old_pairs_leaf_hashes}
deletions = {k for k in old_pairs_leaf_hashes if k not in new_pairs_leaf_hashes}
lengths = {}
for hash in insertions:
lengths[hash] = new_pairs.leaf_hash_to_length[hash]
for hash in deletions:
lengths[hash] = old_pairs.leaf_hash_to_length[hash]
pagination_data = get_hashes_for_page(page, lengths, max_page_size)
kv_diff: List[DiffData] = []
for hash in pagination_data.hashes:
node = await self.get_node(hash)
assert isinstance(node, TerminalNode)
if hash in insertions:
kv_diff.append(DiffData(OperationType.INSERT, node.key, node.value))
else:
kv_diff.append(DiffData(OperationType.DELETE, node.key, node.value))
return KVDiffPaginationData(
pagination_data.total_pages,
pagination_data.total_bytes,
kv_diff,
)
async def get_node_type(self, node_hash: bytes32) -> NodeType:
async with self.db_wrapper.reader() as reader:
cursor = await reader.execute(
"SELECT node_type FROM node WHERE hash == :hash LIMIT 1",
{"hash": node_hash},
)
raw_node_type = await cursor.fetchone()
if raw_node_type is None:
raise Exception(f"No node found for specified hash: {node_hash.hex()}")
return NodeType(raw_node_type["node_type"])
async def get_terminal_node_for_seed(
self, tree_id: bytes32, seed: bytes32, root_hash: Optional[bytes32] = None
) -> Optional[bytes32]:
path = "".join(reversed("".join(f"{b:08b}" for b in seed)))
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id)
root_hash = root.node_hash
if root_hash is None:
return None
async with reader.execute(
"""
WITH RECURSIVE
random_leaf(hash, node_type, left, right, depth, side) AS (
SELECT
node.hash AS hash,
node.node_type AS node_type,
node.left AS left,
node.right AS right,
1 AS depth,
SUBSTR(:path, 1, 1) as side
FROM node
WHERE node.hash == :root_hash
UNION ALL
SELECT
node.hash AS hash,
node.node_type AS node_type,
node.left AS left,
node.right AS right,
random_leaf.depth + 1 AS depth,
SUBSTR(:path, random_leaf.depth + 1, 1) as side
FROM node, random_leaf
WHERE (
(random_leaf.side == "0" AND node.hash == random_leaf.left)
OR (random_leaf.side != "0" AND node.hash == random_leaf.right)
)
)
SELECT hash AS hash FROM random_leaf
WHERE node_type == :node_type
LIMIT 1
""",
{"root_hash": root_hash, "node_type": NodeType.TERMINAL, "path": path},
) as cursor:
row = await cursor.fetchone()
if row is None:
# No cover since this is an error state that should be unreachable given the code
# above has already verified that there is a non-empty tree.
raise Exception("No terminal node found for seed") # pragma: no cover
return bytes32(row["hash"])
def get_side_for_seed(self, seed: bytes32) -> Side:
side_seed = bytes(seed)[0]
return Side.LEFT if side_seed < 128 else Side.RIGHT
async def autoinsert(
self,
key: bytes,
value: bytes,
tree_id: bytes32,
use_optimized: bool = True,
status: Status = Status.PENDING,
root: Optional[Root] = None,
) -> InsertResult:
async with self.db_wrapper.writer():
if root is None:
root = await self.get_tree_root(tree_id=tree_id)
was_empty = root.node_hash is None
if was_empty:
reference_node_hash = None
side = None
else:
seed = leaf_hash(key=key, value=value)
reference_node_hash = await self.get_terminal_node_for_seed(tree_id, seed, root_hash=root.node_hash)
side = self.get_side_for_seed(seed)
return await self.insert(
key=key,
value=value,
tree_id=tree_id,
reference_node_hash=reference_node_hash,
side=side,
use_optimized=use_optimized,
status=status,
root=root,
)
async def get_keys_values_dict(self, tree_id: bytes32, root_hash: Optional[bytes32] = None) -> Dict[bytes, bytes]:
pairs = await self.get_keys_values(tree_id=tree_id, root_hash=root_hash)
return {node.key: node.value for node in pairs}
async def get_keys(self, tree_id: bytes32, root_hash: Optional[bytes32] = None) -> List[bytes]:
async with self.db_wrapper.reader() as reader:
if root_hash is None:
root = await self.get_tree_root(tree_id=tree_id)
root_hash = root.node_hash
cursor = await reader.execute(
"""
WITH RECURSIVE
tree_from_root_hash(hash, node_type, left, right, key) AS (
SELECT node.hash, node.node_type, node.left, node.right, node.key
FROM node WHERE node.hash == :root_hash
UNION ALL
SELECT
node.hash, node.node_type, node.left, node.right, node.key FROM node, tree_from_root_hash
WHERE node.hash == tree_from_root_hash.left OR node.hash == tree_from_root_hash.right
)
SELECT key FROM tree_from_root_hash WHERE node_type == :node_type
""",
{"root_hash": None if root_hash is None else root_hash, "node_type": NodeType.TERMINAL},
)
keys: List[bytes] = [row["key"] async for row in cursor]
return keys
async def get_ancestors_common(
self,
node_hash: bytes32,
tree_id: bytes32,
root_hash: Optional[bytes32],
generation: Optional[int] = None,
use_optimized: bool = True,
) -> List[InternalNode]:
if use_optimized:
ancestors: List[InternalNode] = await self.get_ancestors_optimized(
node_hash=node_hash,
tree_id=tree_id,
generation=generation,
root_hash=root_hash,
)
else:
ancestors = await self.get_ancestors_optimized(
node_hash=node_hash,