Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

eth/util: fix single-byte hex-string nibbles #298

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions lib/eth/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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`.
Expand Down
5 changes: 5 additions & 0 deletions spec/eth/util_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading