from exploits.hashes.collisions import lrc
from test.exploits.dummy_output import DummyOutput


def z3lrc_hash(bytes, hash_table_size):
    lrc = 0
    for byte in bytes:
        lrc = (lrc + ord(byte)) & 0xff
    lrc = (((lrc ^ 0xff) + 1) & 0xff)
    return lrc % hash_table_size


def test_run():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 256
    target = '42'
    length = 10
    lrc.options['n_collisions'] = n_collisions
    lrc.options['length'] = length
    lrc.options['target_type'] = 'image'
    lrc.options['target'] = target
    lrc.options['hash_table_size'] = hash_table_size
    lrc.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert z3lrc_hash(i, hash_table_size) == int(target)
        assert len(i) == length


def test_run_larger_hash_table_size():
    output = DummyOutput()
    n_collisions = 10
    hash_table_size = 1024
    target = '42'
    length = 10
    lrc.options['n_collisions'] = n_collisions
    lrc.options['length'] = length
    lrc.options['target_type'] = 'image'
    lrc.options['target'] = target
    lrc.options['hash_table_size'] = hash_table_size
    lrc.run(output)
    assert output.count() == n_collisions
    for i in output:
        assert z3lrc_hash(i, hash_table_size) == int(target)
        assert len(i) == length
