From 721f3b138449bfad710315a3ef05c0608524c5d5 Mon Sep 17 00:00:00 2001 From: Bastien CHAMAGNE Date: Wed, 14 Jun 2023 17:56:02 +0200 Subject: [PATCH] String.to_hex/1 may return nil instead of crashing --- .../interpreter/library/common/string.ex | 12 ++++--- .../library/common/string_test.exs | 34 ++++++------------- 2 files changed, 19 insertions(+), 27 deletions(-) diff --git a/lib/archethic/contracts/interpreter/library/common/string.ex b/lib/archethic/contracts/interpreter/library/common/string.ex index 2d6922350..432063b1a 100644 --- a/lib/archethic/contracts/interpreter/library/common/string.ex +++ b/lib/archethic/contracts/interpreter/library/common/string.ex @@ -14,11 +14,15 @@ defmodule Archethic.Contracts.Interpreter.Library.Common.String do to: String, as: :contains? - @spec to_hex(String.t()) :: String.t() + @spec to_hex(String.t()) :: String.t() | nil def to_hex(str) do - str - |> Base.decode16!(case: :mixed) - |> Base.encode16() + case Base.decode16(str, case: :mixed) do + {:ok, bin} -> + Base.encode16(bin) + + :error -> + nil + end end @spec to_uppercase(String.t()) :: String.t() diff --git a/test/archethic/contracts/interpreter/library/common/string_test.exs b/test/archethic/contracts/interpreter/library/common/string_test.exs index 37180506b..00c644cef 100644 --- a/test/archethic/contracts/interpreter/library/common/string_test.exs +++ b/test/archethic/contracts/interpreter/library/common/string_test.exs @@ -229,40 +229,28 @@ defmodule Archethic.Contracts.Interpreter.Library.Common.StringTest do {:error, _, "invalid function arguments"} = sanitize_parse_execute(code) end - test "should raise when not a hex" do - # string with non-hex characters + test "should return nil if size of string is incorrect" do code = ~s""" actions triggered_by: transaction do - Contract.set_content String.to_hex("zzz") - end - """ - - assert_raise(ArgumentError, fn -> - sanitize_parse_execute(code) - end) - - # variable - code = ~s""" - actions triggered_by: transaction do - var = "ZZZ" - Contract.set_content String.to_hex(var) + if nil == String.to_hex("abc") do + Contract.set_content "ok" + end end """ - assert_raise(ArgumentError, fn -> - sanitize_parse_execute(code) - end) + assert %Transaction{data: %TransactionData{content: "ok"}} = sanitize_parse_execute(code) + end - # string with invalid size + test "should return nil if size of string contains non hexadecimal chars" do code = ~s""" actions triggered_by: transaction do - Contract.set_content String.to_hex("abc") + if nil == String.to_hex("fghijk") do + Contract.set_content "ok" + end end """ - assert_raise(ArgumentError, fn -> - sanitize_parse_execute(code) - end) + assert %Transaction{data: %TransactionData{content: "ok"}} = sanitize_parse_execute(code) end end