From 4c4b72f22bff519f8f476a103683611d8d2742a8 Mon Sep 17 00:00:00 2001 From: steffenix <87598469+steffenix@users.noreply.github.com> Date: Fri, 5 Jul 2024 12:20:37 +0100 Subject: [PATCH] make keccak module configurable (#169) --- README.md | 8 ++++++++ lib/abi/function_selector.ex | 6 ++++-- lib/abi/type_encoder.ex | 3 ++- mix.exs | 2 +- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6c2016a..8adb254 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,14 @@ Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_do and published on [HexDocs](https://hexdocs.pm). Once published, the docs can be found at [https://hexdocs.pm/ex_abi](https://hexdocs.pm/ex_abi). +## Confiiguration + +The default keccak library is set to `ex_keccak` but that can be ovveriden for a different libary: + +```elixir +config :ex_abi, keccak_module: KeccakEx +``` + ## Usage ### Encoding diff --git a/lib/abi/function_selector.ex b/lib/abi/function_selector.ex index 65789ba..f4c457b 100644 --- a/lib/abi/function_selector.ex +++ b/lib/abi/function_selector.ex @@ -403,8 +403,9 @@ defmodule ABI.FunctionSelector do defp add_method_id(selector) do signature = encode(selector) + keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak) - case ExKeccak.hash_256(signature) do + case keccak_module.hash_256(signature) do <> -> %{selector | method_id: method_id} @@ -414,9 +415,10 @@ defmodule ABI.FunctionSelector do end defp add_event_id(selector) do + keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak) signature = encode(selector) - %{selector | method_id: ExKeccak.hash_256(signature)} + %{selector | method_id: keccak_module.hash_256(signature)} end defp get_types(function_selector) do diff --git a/lib/abi/type_encoder.ex b/lib/abi/type_encoder.ex index a105e7c..4f836d4 100644 --- a/lib/abi/type_encoder.ex +++ b/lib/abi/type_encoder.ex @@ -244,11 +244,12 @@ defmodule ABI.TypeEncoder do defp encode_method_id(%FunctionSelector{function: nil}), do: "" defp encode_method_id(function_selector) do + keccak_module = Application.get_env(:ex_abi, :keccak_module, ExKeccak) # Encode selector e.g. "baz(uint32,bool)" and take keccak kec = function_selector |> FunctionSelector.encode() - |> ExKeccak.hash_256() + |> keccak_module.hash_256() # Take first four bytes <> = kec diff --git a/mix.exs b/mix.exs index 18dc01e..3b8f4e7 100644 --- a/mix.exs +++ b/mix.exs @@ -33,7 +33,7 @@ defmodule ABI.Mixfile do {:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}, {:ex_doc, "~> 0.24", only: :dev, runtime: false}, {:jason, "~> 1.4"}, - {:ex_keccak, "~> 0.7.5"}, + {:ex_keccak, "~> 0.7.5", optional: true}, {:propcheck, "~> 1.4", only: [:test, :dev]} ] end