From 7abfae5b4a148dd9d793381bccd550fafe71edd6 Mon Sep 17 00:00:00 2001 From: hswick Date: Tue, 26 Jun 2018 17:27:10 -0400 Subject: [PATCH] Added keccak256 hash --- lib/exw3.ex | 7 +++++++ test/exw3_test.exs | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/exw3.ex b/lib/exw3.ex index 883d776..a058cc1 100644 --- a/lib/exw3.ex +++ b/lib/exw3.ex @@ -1,4 +1,11 @@ defmodule ExW3 do + + @spec keccak256(binary()) :: binary() + @doc "Returns a 0x prepended 32 byte hash of the input string" + def keccak256(string) do + Enum.join(["0x", ExthCrypto.Hash.Keccak.kec(string) |> Base.encode16(case: :lower)], "") + end + @spec bytes_to_string(binary()) :: binary() @doc "converts Ethereum style bytes to string" def bytes_to_string(bytes) do diff --git a/test/exw3_test.exs b/test/exw3_test.exs index 1a8eaf7..ddd023b 100644 --- a/test/exw3_test.exs +++ b/test/exw3_test.exs @@ -41,6 +41,18 @@ defmodule EXW3Test do assert ExW3.block_number() == block_number + 5 end + test "keccak256 hash some data" do + hash = ExW3.keccak256("foo") + assert String.slice(hash, 0..1) == "0x" + + num_bytes = + hash |> + String.slice(2..-1) |> + byte_size + + assert trunc(num_bytes / 2) == 32 + end + test "starts a Contract GenServer for simple storage contract", context do ExW3.Contract.start_link(SimpleStorage, abi: context[:simple_storage_abi])