1010# in the LICENSE file.
1111
1212from bitcoin import base58
13+ from bitcoin .bech32 import CBech32Data
1314from .utils import btc_ripemd160 , double_sha256
1415
1516
1617class Address (object ):
1718 """Represents a bitcoin address"""
1819
19- def __init__ (self , hash , public_key , address , type ):
20+ def __init__ (self , hash , public_key , address , type , segwit_version ):
2021 self ._hash = hash
2122 self .public_key = public_key
2223 self ._address = address
2324 self .type = type
25+ self ._segwit_version = segwit_version
2426
2527 def __repr__ (self ):
2628 return "Address(addr=%s)" % self .address
2729
2830 @classmethod
2931 def from_public_key (cls , public_key ):
3032 """Constructs an Address object from a public key"""
31- return cls (None , public_key , None , "normal" )
33+ return cls (None , public_key , None , "normal" , None )
3234
3335 @classmethod
3436 def from_ripemd160 (cls , hash , type = "normal" ):
3537 """Constructs an Address object from a RIPEMD-160 hash, it may be a
3638 normal address or a P2SH address, the latter is indicated by setting
3739 type to 'p2sh'"""
38- return cls (hash , None , None , type )
40+ return cls (hash , None , None , type , None )
41+
42+ @classmethod
43+ def from_bech32 (cls , hash , segwit_version ):
44+ """Constructs an Address object from a bech32 hash."""
45+ return cls (hash , None , None , "bech32" , segwit_version )
3946
4047 @property
4148 def hash (self ):
@@ -47,12 +54,18 @@ def hash(self):
4754
4855 @property
4956 def address (self ):
50- """Returns the base58 encoded representation of this address"""
57+ """Returns the encoded representation of this address.
58+ If SegWit, it's encoded using bech32, otherwise using base58
59+ """
5160 if self ._address is None :
52- version = b'\x00 ' if self .type == "normal" else b'\x05 '
53- checksum = double_sha256 (version + self .hash )
61+ if self .type != "bech32" :
62+ version = b'\x00 ' if self .type == "normal" else b'\x05 '
63+ checksum = double_sha256 (version + self .hash )
5464
55- self ._address = base58 .encode (version + self .hash + checksum [:4 ])
65+ self ._address = base58 .encode (version + self .hash + checksum [:4 ])
66+ else :
67+ bech_encoded = CBech32Data .from_bytes (self ._segwit_version , self ._hash )
68+ self ._address = str (bech_encoded )
5669 return self ._address
5770
5871 def is_p2sh (self ):
0 commit comments