@@ -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
0 commit comments