Exemplo n.º 1
0
def test_UndecodableRecord_upon_update(byte, encoding, security):
    t = MerkleTree('a',
                   'b',
                   'c',
                   encoding=encoding,
                   security=security,
                   raw_bytes=False)
    with pytest.raises(UndecodableRecord):
        t.update(record=byte)
Exemplo n.º 2
0
def test_WrongJSONFormat_with_loadFromFile():
    parent_dir = os.path.dirname(os.path.dirname(__file__))
    with pytest.raises(WrongJSONFormat):
        MerkleTree.loadFromFile(
            os.path.join(
                parent_dir,
                'json_files',
                'sample.json'
            )
        )
Exemplo n.º 3
0
def test_LeafConstructionError_upon_update():
    """
    Tests that a `LeafConstructionError` is raised if both `record` and
    `digest` are provided as arguments to the `MerkleTree.update()` method
    """
    t = MerkleTree()
    with pytest.raises(LeafConstructionError):
        t.update(
            record='some record',
            digest=
            '540ef8fc9eefa3ec0fbe55bc5d10dbea03d5bac5591b3d7db3af79ec24b3f74c')
Exemplo n.º 4
0
def test___repr__non_default_empty_tree():
    tree = MerkleTree(hash_type='sha512', encoding='UTF-32', security=False)
    assert tree.__repr__() == '\n    uuid      : %s\
                \n\
                \n    hash-type : SHA512\
                \n    encoding  : UTF-32\
                \n    raw-bytes : TRUE\
                \n    security  : DEACTIVATED\
                \n\
                \n    root-hash : [None]\
                \n\
                \n    length    : 0\
                \n    size      : 0\
                \n    height    : 0\n' % tree.uuid
Exemplo n.º 5
0
def test___repr__default_non_empty_tree():
    tree = MerkleTree(b'first', b'second', b'third')
    assert tree.__repr__() == '\n    uuid      : %s\
                \n\
                \n    hash-type : SHA256\
                \n    encoding  : UTF-8\
                \n    raw-bytes : TRUE\
                \n    security  : ACTIVATED\
                \n\
                \n    root-hash : %s\
                \n\
                \n    length    : 3\
                \n    size      : 5\
                \n    height    : 2\n' % (
                    tree.uuid, tree.rootHash.decode(tree.encoding))
Exemplo n.º 6
0
def test_rootHash_of_non_empty_MerkleTree():
    """
    Tests the root-hash of a Merkle-tree with one and two leaves
    """
    t = MerkleTree('first record')
    s = MerkleTree('first record', 'second record')
    assert t.rootHash == t.hash('first record') and \
        s.rootHash == s.hash(s.hash('first record'), s.hash('second record'))
Exemplo n.º 7
0
def test_UnsupportedHashType():
    """
    Tests that a `UnsupportedHashType` is raised when a Merkle-tree
    for an unsupported hash-type is requested
    """
    with pytest.raises(UnsupportedHashType):
        MerkleTree(hash_type='anything unsupported...')
Exemplo n.º 8
0
def test_UnsupportedEncoding():
    """
    Tests that a `UnsupportedEncoding` is raised when a Merkle-tree
    for an unsupported encoding type is requested
    """
    with pytest.raises(UnsupportedEncoding):
        MerkleTree(encoding='anything unsupported...')
Exemplo n.º 9
0
def test_UndecodableRecord_upon_tree_construction(byte, encoding, security):
    with pytest.raises(UndecodableRecord):
        MerkleTree('a',
                   byte,
                   encoding=encoding,
                   security=security,
                   raw_bytes=False)
Exemplo n.º 10
0
def test_rootHash_empty_tree_exception():
    """
    Tests `EmptyTreeException` upon requesting the root-hash
    of an empty Merkle-tree
    """
    with pytest.raises(EmptyTreeException):
        MerkleTree().rootHash
Exemplo n.º 11
0
def consistency_proofs_benchmark():
    write('Generating consistency proofs -be patient...')
    # Generate states
    TREE = MerkleTree('0-th record', encoding=ENCODING, hash_type=HASH_TYPE)
    states = []
    for i in range(1, LENGTH + 3 * ADDITIONAL):
        states.append(TREE.rootHash)
        TREE.encryptRecord('%d-th record' % i)
    states.append(TREE.rootHash)

    # Generate proofs
    global PROOFS
    START = now()
    MAX = None
    MIN = None
    TOTAL = 0.0
    elapsed = []
    for subhash in states:
        cycle = now()
        proof = TREE.consistencyProof(subhash)
        _elapsed = time_elapsed(cycle)
        if MAX is None:
            MIN = MAX = _elapsed
        else:
            MAX = max(_elapsed, MAX)
            MIN = min(_elapsed, MIN)
        PROOFS.append(proof)
        TOTAL += _elapsed
        elapsed.append(_elapsed)
    mean, stdev = mean_value(elapsed, PRECISION_2, with_stdev=True)
    show_stats(message='\nConsistency proof generation (sec)',
               total=quantize(TOTAL, PRECISION_2),
               min=MIN,
               max=MAX,
               mean=mean,
               stdev=stdev)
Exemplo n.º 12
0
def tree_generation_benchmark():
    write(
        '\n\n------------------- Tree generation and size measuremenets -------------------'
    )
    write('\n')

    args = ['%d-th record' % _ for _ in range(LENGTH)]

    global TREE
    start = now()
    TREE = MerkleTree(*args, hash_type=HASH_TYPE, encoding=ENCODING)
    time_needed = time_elapsed(start)

    write('\nNumber of leaves      : %d\n' % TREE.length)
    write('\nGeneration time (sec) : %s' % time_needed)
    write('\nSize of tree (bytes)  : %d' % get_size(TREE))
Exemplo n.º 13
0
def test_clear():
    tree = MerkleTree('a', 'b', 'c')
    tree.clear()
    with pytest.raises(EmptyTreeException):
        tree.root
    assert not tree.leaves and not tree.nodes
Exemplo n.º 14
0
from pymerkle.core import MerkleTree
from pymerkle.exceptions import WrongJSONFormat

# Clean exports dir before running tests
for _file in os.listdir(os.path.join(os.path.dirname(__file__), 'exports')):
    os.remove(
        os.path.join(
            os.path.dirname(__file__),
            'exports',
            _file
        )
    )

# Make tree and export
tree = MerkleTree(*['%d-th record' % i for i in range(12)])
export_path = os.path.join(
    os.path.dirname(__file__),
    'exports',
    '%s.json' % tree.uuid
)
tree.export(filepath=export_path)

# Load tree from export file
with open(export_path, 'rb') as f:
    exported_version = json.load(f)


def test_export():
    assert exported_version == {
        "header": {
Exemplo n.º 15
0
    assert tree.__repr__() == '\n    uuid      : %s\
                \n\
                \n    hash-type : SHA256\
                \n    encoding  : UTF-8\
                \n    raw-bytes : TRUE\
                \n    security  : ACTIVATED\
                \n\
                \n    root-hash : %s\
                \n\
                \n    length    : 3\
                \n    size      : 5\
                \n    height    : 2\n' % (
                    tree.uuid, tree.rootHash.decode(tree.encoding))


empty_tree = MerkleTree()
one_leaf_tree = MerkleTree('first')
three_leaves_tree = MerkleTree('first', 'second', 'third')

serializations = [
    (
        empty_tree,
        {
            "hashes": [],
            "header": {
                "encoding": "utf_8",
                "hash_type": "sha256",
                "raw_bytes": True,
                "security": True
            }
        }
Exemplo n.º 16
0
def test_loadFromFile():
    assert tree.serialize() == MerkleTree.loadFromFile(export_path).serialize()
Exemplo n.º 17
0
def test_properties_of_tree_with_three_leaves():
    tree = MerkleTree('first', 'second', 'third')
    assert (tree.length, tree.size, tree.height) == (3, 5, 2)
Exemplo n.º 18
0
def test_properties_of_empty_tree():
    tree = MerkleTree()
    assert (tree.length, tree.size, tree.height) == (0, 0, 0)
Exemplo n.º 19
0
"""

import pytest
import os
import json

from pymerkle.core import MerkleTree
from pymerkle.exceptions import (
    NoSubtreeException,
    NoPathException,
    NoPrincipalSubroots,
)

# Audit proof implementation

_0_leaves_tree = MerkleTree()
_1_leaves_tree = MerkleTree('a')
_2_leaves_tree = MerkleTree('a', 'b')
_3_leaves_tree = MerkleTree('a', 'b', 'c')
_4_leaves_tree = MerkleTree('a', 'b', 'c', 'd')
_5_leaves_tree = MerkleTree('a', 'b', 'c', 'd', 'e')

no_path_exceptions = [(_0_leaves_tree, +0), (_1_leaves_tree, -1),
                      (_1_leaves_tree, +1), (_2_leaves_tree, -1),
                      (_2_leaves_tree, +2), (_3_leaves_tree, -1),
                      (_3_leaves_tree, +3), (_4_leaves_tree, -1),
                      (_4_leaves_tree, +4), (_5_leaves_tree, -1),
                      (_5_leaves_tree, +5)]


@pytest.mark.parametrize('tree, index', no_path_exceptions)
Exemplo n.º 20
0
def test_MerkleTree_bool_implementation():
    """
    Tests that a Merkle-tree is equivalent to `False` iff it is empty
    """
    assert not MerkleTree() and MerkleTree('some record')