Class: CoinAddressValidators::TrxValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/coin-address-validators.rb

Instance Method Summary collapse

Instance Method Details

#bytes_to_str(bytes) ⇒ Object



138
139
140
# File 'lib/coin-address-validators.rb', line 138

def bytes_to_str(bytes)
  bytes.pack("c*").unpack1("H*")
end

#hex_str_to_bytes(hex_str) ⇒ Object



134
135
136
# File 'lib/coin-address-validators.rb', line 134

def hex_str_to_bytes(hex_str)
  hex_str.scan(/../).map(&:hex)
end

#sha256(hex_str) ⇒ Object



142
143
144
# File 'lib/coin-address-validators.rb', line 142

def sha256(hex_str)
  Digest::SHA2.new(256).hexdigest([hex_str].pack("H*"))
end

#to_base58_address(hex) ⇒ Object



126
127
128
129
130
131
132
# File 'lib/coin-address-validators.rb', line 126

def to_base58_address(hex)
  return "" unless hex

  sha256ed = sha256(sha256(hex))
  bytes = hex_str_to_bytes(hex) + hex_str_to_bytes(sha256ed).first(4)
  Base58.encode(bytes_to_str(bytes).to_i(16), :bitcoin)
end

#valid?(address) ⇒ Boolean

Returns:

  • (Boolean)


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/coin-address-validators.rb', line 105

def valid?(address)
  return false unless address.is_a?(String)
  return false unless address.size == 34
  return false unless address.start_with?("T")
  addr = BaseX::BitcoinBase58.decode(address)
  return false unless addr.size == 25
  return false unless addr.unpack1("H*").start_with?("41")

  checksum = addr[-4..-1]
  real_addr = addr[0..-5]

  # TODO checksum properly
  # hash0 = sha256(real_addr)
  # hash1 = sha256(hash0)
  # checksum1 = hash1[0..3]
  # return (checksum[0] == checksum1[0] && checksum[1] == checksum1[1] && checksum[2] ==
  #   checksum1[2] && checksum[3] == checksum1[3])

  return address == to_base58_address(real_addr.unpack1("H*"))
end