Help language development. Donate to The Perl Foundation

Node::Ethereum::Keccak256::Native zef:knarkhov last updated on 2021-12-06

t/01.t
use v6.d;
use Test;

use Node::Ethereum::Keccak256::Native;

plan 4;

use-ok 'Node::Ethereum::Keccak256::Native';

my $brute_iter = 10000;
my $keccak256  = Node::Ethereum::Keccak256::Native.new;

is-deeply $keccak256.keccak256(:msg("hello")), buf8.new(0x1C, 0x8A, 0xFF, 0x95, 0x06, 0x85, 0xC2, 0xED, 0x4B, 0xC3, 0x17, 0x4F, 0x34, 0x72, 0x28, 0x7B, 0x56, 0xD9, 0x51, 0x7B, 0x9C, 0x94, 0x81, 0x27, 0x31, 0x9A, 0x09, 0xA7, 0xA3, 0x6D, 0xEA, 0xC8), 'hello keccak256';

ok keccak_brute_test(:iters($brute_iter)), sprintf("generated %d hashes from strings", $brute_iter);
ok keccak_brute_test(:iters($brute_iter), :buffer(True)), sprintf("generated %d hashes from buffers", $brute_iter);

done-testing;

sub buf_to_hex(buf8 $buf) returns Str {
    my @encoded;

    for $buf.list -> $member {
        my $hex = $member.base(16);
        @encoded.push($member < 16 ?? '0' ~ $hex !! $hex);
    }

    return @encoded.join(q{});
}

sub keccak_brute_test(UInt :$iters, Bool :$buffer = False) returns Bool {
    my $result = True;

    for ^$iters -> $i {
        my $keccak256 = Node::Ethereum::Keccak256::Native.new;

        my $hex = $buffer ??
            buf_to_hex($keccak256.keccak256(:msg(buf8.new(sprintf("iteration_%d", $i).encode)))) !!
                buf_to_hex($keccak256.keccak256(:msg(sprintf("iteration_%d", $i))));

        if $hex !~~ m/^^ <xdigit> ** 64 $$/ {
            $result = False;

            last;
        }
    }

    return $result;
}