From a98d79ed8d1823d5744da40f440b3d16c186b227 Mon Sep 17 00:00:00 2001 From: afr q9f <58883403+q9f@users.noreply.github.com> Date: Tue, 17 Dec 2024 14:04:25 +0100 Subject: [PATCH] eth/util: fix single-byte hex-string nibbles --- lib/eth/util.rb | 7 +++++-- spec/eth/util_spec.rb | 5 +++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/eth/util.rb b/lib/eth/util.rb index 0eeef457..d0bb702f 100644 --- a/lib/eth/util.rb +++ b/lib/eth/util.rb @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +# -*- encoding : ascii-8bit -*- + require "digest/keccak" # Provides the {Eth} module. @@ -48,7 +50,7 @@ def keccak256(str) # @raise [TypeError] if value is not a string. def bin_to_hex(bin) raise TypeError, "Value must be an instance of String" unless bin.instance_of? String - bin.unpack("H*").first + hex = bin.unpack("H*").first end # Packs a hexa-decimal string into a binary string. Also works with @@ -61,7 +63,8 @@ def hex_to_bin(hex) raise TypeError, "Value must be an instance of String" unless hex.instance_of? String hex = remove_hex_prefix hex raise TypeError, "Non-hexadecimal digit found" unless hex? hex - [hex].pack("H*") + hex = "0#{hex}" if hex.size % 2 != 0 + bin = [hex].pack("H*") end # Prefixes a hexa-decimal string with `0x`. diff --git a/spec/eth/util_spec.rb b/spec/eth/util_spec.rb index 811167cf..ae55096c 100644 --- a/spec/eth/util_spec.rb +++ b/spec/eth/util_spec.rb @@ -80,6 +80,11 @@ expect { Util.hex_to_bin "\x00\x00" }.to raise_error TypeError expect { Util.hex_to_bin 1234 }.to raise_error TypeError end + + it "can convert back and forth" do + expect(Util.bin_to_hex Util.hex_to_bin "a").to eq "0a" + expect(Util.hex_to_bin Util.bin_to_hex "a").to eq "a" + end end describe ".prefix_hex .remove_hex_prefix" do