Class: Crypto::Keys::Address

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto/keys/address.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hex_address, network = MAINNET, name = "generic") ⇒ Address

Returns a new instance of Address.



10
11
12
13
14
15
16
17
# File 'lib/crypto/keys/address.rb', line 10

def initialize(hex_address, network = MAINNET, name = "generic")
  @hex_address = hex_address
  @network = network
  @name = name
  unless is_valid?
    raise AxentroError, "invalid '#{@name}' address checksum for: '#{@hex_address}'"
  end
end

Instance Attribute Details

#networkObject (readonly)

Returns the value of attribute network.



8
9
10
# File 'lib/crypto/keys/address.rb', line 8

def network
  @network
end

Class Method Details

.from(hex_address, name = "") ⇒ Object



23
24
25
26
# File 'lib/crypto/keys/address.rb', line 23

def self.from(hex_address, name = "")
  network = get_network_from_address(hex_address)
  Address.new(hex_address, network, name)
end

.get_network_from_address(hex_address) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/crypto/keys/address.rb', line 45

def self.get_network_from_address(hex_address)
  begin
    decoded_address = Base64.strict_decode64(hex_address)
  rescue => e
    raise AxentroError, "invalid address: #{e}"
  end

  case decoded_address[0..1]
  when MAINNET[:prefix]
    MAINNET
  when TESTNET[:prefix]
    TESTNET
  else
    raise AxentroError, "invalid network: #{decoded_address[0..1]} for address: #{hex_address}"
  end
end

.is_valid?(hex_address) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/crypto/keys/address.rb', line 32

def self.is_valid?(hex_address)
  begin
    decoded_address = Base64.strict_decode64(hex_address)
    return false unless decoded_address.size == 48
    version_address = decoded_address[0..-7]
    hashed_address = Crypto::Hashes.sha256(Crypto::Hashes.sha256(version_address))
    checksum = decoded_address[-6..-1]
    checksum == hashed_address[0..5]
  rescue AxentroError => e
    false
  end
end

Instance Method Details

#as_hexObject



19
20
21
# File 'lib/crypto/keys/address.rb', line 19

def as_hex
  @hex_address
end

#is_valid?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/crypto/keys/address.rb', line 28

def is_valid?
  Address.is_valid?(@hex_address)
end

#to_sObject



62
63
64
# File 'lib/crypto/keys/address.rb', line 62

def to_s
  as_hex
end