Skip to content

Commit 85deb34

Browse files
committed
support variable length address_version
1 parent 48b8897 commit 85deb34

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

lib/bitcoin.rb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ module Trezor
4747
module Util
4848

4949
def address_version; Bitcoin.network[:address_version]; end
50+
def version_bytes; address_version.size / 2; end
5051
def p2sh_version; Bitcoin.network[:p2sh_version]; end
5152

5253
# hash160 is a 20 bytes (160bits) rmd610-sha256 hexdigest.
@@ -65,7 +66,7 @@ def checksum(hex)
6566
def base58_checksum?(base58)
6667
hex = decode_base58(base58) rescue nil
6768
return false unless hex
68-
checksum( hex[0...42] ) == hex[-8..-1]
69+
checksum(hex[0...(version_bytes + 20) * 2]) == hex[-8..-1]
6970
end
7071
alias :address_checksum? :base58_checksum?
7172

@@ -95,7 +96,9 @@ def hash160_from_address(address)
9596
_, witness_program_hex = decode_segwit_address(address)
9697
witness_program_hex
9798
when :hash160, :p2sh
98-
decode_base58(address)[2...42]
99+
start_idx = version_bytes * 2
100+
stop_idx = start_idx + 40 # 20 bytes (2 chars per byte)
101+
decode_base58(address)[start_idx...stop_idx]
99102
end
100103
end
101104

@@ -116,14 +119,16 @@ def address_type(address)
116119
end
117120

118121
hex = decode_base58(address) rescue nil
119-
if hex && hex.bytesize == 50 && address_checksum?(address)
122+
123+
target_size = (version_bytes + 20 + 4) * 2 # version_bytes + 20 bytes hash + 4 bytes checksum
124+
if hex && hex.bytesize == target_size && address_checksum?(address)
120125
# Litecoin updates the P2SH version byte, and this method should recognize both.
121126
p2sh_versions = [p2sh_version]
122127
if Bitcoin.network[:legacy_p2sh_versions]
123128
p2sh_versions += Bitcoin.network[:legacy_p2sh_versions]
124129
end
125130

126-
case hex[0...2]
131+
case hex[0...(version_bytes * 2)]
127132
when address_version
128133
return :hash160
129134
when *p2sh_versions

spec/unit/bitcoin/bitcoin_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,28 @@
426426
).to be_nil
427427
end
428428
end
429+
430+
context 'zcash' do
431+
before {
432+
Bitcoin::NETWORKS[:zcash] = Bitcoin::NETWORKS[:bitcoin].merge(
433+
project: :zcash,
434+
address_version: '1cb8',
435+
p2sh_version: '1cbd',
436+
)
437+
Bitcoin.network = :zcash
438+
}
439+
440+
it 'works for a hash160 address' do
441+
expect(Bitcoin.address_type('t1KBT8oCGAfisNNWnSD3h7TSsZ7qKah935g'))
442+
.to eq(:hash160)
443+
end
444+
445+
it 'is nil for invalid addresses' do
446+
expect(
447+
Bitcoin.address_type('2MyLngQnhzjzatKsB7XfHYoP9e2XUXSiBMM')
448+
).to be_nil
449+
end
450+
end
429451
end
430452

431453
describe '.checksum' do

0 commit comments

Comments
 (0)