From eb8e9d85f7f0f627d6d49fba7bb555228e15d50a Mon Sep 17 00:00:00 2001 From: Ryan Collingham Date: Wed, 27 Dec 2023 11:17:01 +0000 Subject: [PATCH] check that tree is non-empty for root generation --- merkly/mtree.py | 3 +++ test/errors/test_errors.py | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/merkly/mtree.py b/merkly/mtree.py index 079ad38..49309f6 100644 --- a/merkly/mtree.py +++ b/merkly/mtree.py @@ -80,6 +80,9 @@ def concat_nodes(left: Node, right: Node) -> Node: return reduce(concat_nodes, full_proof).data == self.root def make_root(self, leaves: List[bytes]) -> bytes: + if len(leaves) == 0: + raise ValueError("Cannot get root of an empty tree") + while len(leaves) > 1: next_level = [] for i in range(0, len(leaves) - 1, 2): diff --git a/test/errors/test_errors.py b/test/errors/test_errors.py index b584e3b..55790bc 100644 --- a/test/errors/test_errors.py +++ b/test/errors/test_errors.py @@ -25,3 +25,13 @@ def invalid_hash_function(data): ["a", "b", "c", "d"], invalid_hash_function, ) + + +def test_empty_tree_root(): + mtree = MerkleTree(['a', 'b', 'c', 'd']) + mtree.leaves = [] + + with raises(ValueError) as error: + mtree.root + + assert str(error.value) == 'Cannot get root of an empty tree'