Skip to content

Commit

Permalink
String.to_hex/1 may return nil instead of crashing
Browse files Browse the repository at this point in the history
  • Loading branch information
bchamagne authored and Neylix committed Jun 19, 2023
1 parent fe06341 commit 721f3b1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 27 deletions.
12 changes: 8 additions & 4 deletions lib/archethic/contracts/interpreter/library/common/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
34 changes: 11 additions & 23 deletions test/archethic/contracts/interpreter/library/common/string_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 721f3b1

Please sign in to comment.