Class: Bech32::SegwitAddr

Inherits:
Object
  • Object
show all
Defined in:
lib/bech32/segwit_addr.rb

Constant Summary collapse

HRP_MAINNET =
'bc'
HRP_TESTNET =
'tb'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(addr = nil) ⇒ SegwitAddr

Returns a new instance of SegwitAddr.



12
13
14
15
# File 'lib/bech32/segwit_addr.rb', line 12

def initialize(addr = nil)
  @hrp = HRP_MAINNET
  parse_addr(addr) if addr
end

Instance Attribute Details

#hrpObject

human-readable part



8
9
10
# File 'lib/bech32/segwit_addr.rb', line 8

def hrp
  @hrp
end

#progObject

witness program



10
11
12
# File 'lib/bech32/segwit_addr.rb', line 10

def prog
  @prog
end

#verObject

witness version



9
10
11
# File 'lib/bech32/segwit_addr.rb', line 9

def ver
  @ver
end

Instance Method Details

#addrObject

Returns segwit address string which generated from hrp, witness version and witness program.



31
32
33
# File 'lib/bech32/segwit_addr.rb', line 31

def addr
  Bech32.encode(hrp, [ver] + convert_bits(prog, 8, 5))
end

#script_pubkey=(script_pubkey) ⇒ Object

parse script pubkey into witness version and witness program



24
25
26
27
28
# File 'lib/bech32/segwit_addr.rb', line 24

def script_pubkey=(script_pubkey)
  values = [script_pubkey].pack('H*').unpack("C*")
  @ver = values[0] == 0 ? values[0] : values[0] - 0x50
  @prog = values[2..-1]
end

#to_script_pubkeyObject

Returns segwit script pubkey which generated from witness version and witness program.



18
19
20
21
# File 'lib/bech32/segwit_addr.rb', line 18

def to_script_pubkey
  v = ver == 0 ? ver : ver + 0x50
  ([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first
end