Class: CITA::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/cita/utils.rb

Constant Summary collapse

HEX_PREFIX =
"0x"

Class Method Summary collapse

Class Method Details

.add_hex_prefix(hex) ⇒ Object

add ‘0x` prefix to hex string

Parameters:

  • hex (String)


11
12
13
14
15
16
# File 'lib/cita/utils.rb', line 11

def add_hex_prefix(hex)
  return if hex.nil?
  return hex if hex.start_with?(HEX_PREFIX)

  HEX_PREFIX + hex
end

.add_prefix_for_not_blank(hex) ⇒ Object

add ‘0x` prefix to not blank hex string

Parameters:

  • hex (String)


21
22
23
24
25
# File 'lib/cita/utils.rb', line 21

def add_prefix_for_not_blank(hex)
  return add_hex_prefix(hex) unless hex.blank?

  hex
end

.from_bytes(bytes_str) ⇒ String

byte code to string value, with ‘0x` prefix

Parameters:

  • bytes_str (String)

    byte code string

Returns:

  • (String)

    normal string



66
67
68
69
70
71
# File 'lib/cita/utils.rb', line 66

def from_bytes(bytes_str)
  hex = bytes_str.unpack1("H*")
  return CITA::Utils.add_hex_prefix(hex) unless hex.blank?

  hex
end

.keccak256(*data) ⇒ Object

keccak 256 hash



75
76
77
# File 'lib/cita/utils.rb', line 75

def keccak256(*data)
  Ciri::Utils.keccak(*data)
end

.nonceString

get nonce

Returns:

  • (String)


82
83
84
# File 'lib/cita/utils.rb', line 82

def nonce
  SecureRandom.hex
end

.remove_hex_prefix(hex) ⇒ Object

remove ‘0x` prefix from hex string

Parameters:

  • hex (String)


30
31
32
33
34
35
# File 'lib/cita/utils.rb', line 30

def remove_hex_prefix(hex)
  return if hex.nil?
  return hex.gsub(HEX_PREFIX, "") if hex.start_with?(HEX_PREFIX)

  hex
end

.to_bytes(str) ⇒ String

to byte code value remove ‘0x` prefix first

Parameters:

  • str (String)

    normal string

Returns:

  • (String)

    byte code string



58
59
60
# File 'lib/cita/utils.rb', line 58

def to_bytes(str)
  [CITA::Utils.remove_hex_prefix(str)].pack("H*")
end

.to_decimal(hex) ⇒ Integer

convert hex string to decimal value

Parameters:

  • hex (String)

Returns:

  • (Integer)


49
50
51
# File 'lib/cita/utils.rb', line 49

def to_decimal(hex)
  hex.hex
end

.to_hex(decimal) ⇒ String

convert decimal value to hex string without ‘0x` prefix

Parameters:

  • decimal (Integer)

Returns:

  • (String)


41
42
43
# File 'lib/cita/utils.rb', line 41

def to_hex(decimal)
  add_hex_prefix decimal.to_s(16)
end