1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
|
# Copyright (C) The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
"""Wallet-related functionality
Includes things like representing addresses and converting them to/from
scriptPubKeys; currently there is no actual wallet support implemented.
"""
import bitcoin
import bitcoin.base58
import bitcoin.bech32
import bitcoin.core
import bitcoin.core.key
import bitcoin.core.script as script
class CBitcoinAddress(object):
def __new__(cls, s):
try:
return CBech32BitcoinAddress(s)
except bitcoin.bech32.Bech32Error:
pass
try:
return CBase58BitcoinAddress(s)
except bitcoin.base58.Base58Error:
pass
raise CBitcoinAddressError('Unrecognized encoding for bitcoin address')
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a subclass of CBitcoinAddress"""
try:
return CBech32BitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
try:
return CBase58BitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
raise CBitcoinAddressError('scriptPubKey is not in a recognized address format')
class CBitcoinAddressError(Exception):
"""Raised when an invalid Bitcoin address is encountered"""
class CBech32BitcoinAddress(bitcoin.bech32.CBech32Data, CBitcoinAddress):
"""A Bech32-encoded Bitcoin address"""
@classmethod
def from_bytes(cls, witver, witprog):
assert witver == 0
self = super(CBech32BitcoinAddress, cls).from_bytes(
witver,
bytes(witprog)
)
if len(self) == 32:
self.__class__ = P2WSHBitcoinAddress
elif len(self) == 20:
self.__class__ = P2WPKHBitcoinAddress
else:
raise CBitcoinAddressError('witness program does not match any known segwit address format')
return self
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a CBech32BitcoinAddress
Returns a CBech32BitcoinAddress subclass, either P2WSHBitcoinAddress or
P2WPKHBitcoinAddress. If the scriptPubKey is not recognized
CBitcoinAddressError will be raised.
"""
try:
return P2WSHBitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
try:
return P2WPKHBitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
raise CBitcoinAddressError('scriptPubKey not a valid bech32-encoded address')
class CBase58BitcoinAddress(bitcoin.base58.CBase58Data, CBitcoinAddress):
"""A Base58-encoded Bitcoin address"""
@classmethod
def from_bytes(cls, data, nVersion):
self = super(CBase58BitcoinAddress, cls).from_bytes(data, nVersion)
if nVersion == bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR']:
self.__class__ = P2SHBitcoinAddress
elif nVersion == bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']:
self.__class__ = P2PKHBitcoinAddress
else:
raise CBitcoinAddressError('Version %d not a recognized Bitcoin Address' % nVersion)
return self
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a CBitcoinAddress
Returns a CBitcoinAddress subclass, either P2SHBitcoinAddress or
P2PKHBitcoinAddress. If the scriptPubKey is not recognized
CBitcoinAddressError will be raised.
"""
try:
return P2SHBitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
try:
return P2PKHBitcoinAddress.from_scriptPubKey(scriptPubKey)
except CBitcoinAddressError:
pass
raise CBitcoinAddressError('scriptPubKey not a valid base58-encoded address')
class P2SHBitcoinAddress(CBase58BitcoinAddress):
@classmethod
def from_bytes(cls, data, nVersion=None):
if nVersion is None:
nVersion = bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR']
elif nVersion != bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR']:
raise ValueError('nVersion incorrect for P2SH address: got %d; expected %d' % \
(nVersion, bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR']))
return super(P2SHBitcoinAddress, cls).from_bytes(data, nVersion)
@classmethod
def from_redeemScript(cls, redeemScript):
"""Convert a redeemScript to a P2SH address
Convenience function: equivalent to P2SHBitcoinAddress.from_scriptPubKey(redeemScript.to_p2sh_scriptPubKey())
"""
return cls.from_scriptPubKey(redeemScript.to_p2sh_scriptPubKey())
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a P2SH address
Raises CBitcoinAddressError if the scriptPubKey isn't of the correct
form.
"""
if scriptPubKey.is_p2sh():
return cls.from_bytes(scriptPubKey[2:22], bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR'])
else:
raise CBitcoinAddressError('not a P2SH scriptPubKey')
def to_scriptPubKey(self):
"""Convert an address to a scriptPubKey"""
assert self.nVersion == bitcoin.params.BASE58_PREFIXES['SCRIPT_ADDR']
return script.CScript([script.OP_HASH160, self, script.OP_EQUAL])
def to_redeemScript(self):
return self.to_scriptPubKey()
class P2PKHBitcoinAddress(CBase58BitcoinAddress):
@classmethod
def from_bytes(cls, data, nVersion=None):
if nVersion is None:
nVersion = bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']
elif nVersion != bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']:
raise ValueError('nVersion incorrect for P2PKH address: got %d; expected %d' % \
(nVersion, bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']))
return super(P2PKHBitcoinAddress, cls).from_bytes(data, nVersion)
@classmethod
def from_pubkey(cls, pubkey, accept_invalid=False):
"""Create a P2PKH bitcoin address from a pubkey
Raises CBitcoinAddressError if pubkey is invalid, unless accept_invalid
is True.
The pubkey must be a bytes instance; CECKey instances are not accepted.
"""
if not isinstance(pubkey, bytes):
raise TypeError('pubkey must be bytes instance; got %r' % pubkey.__class__)
if not accept_invalid:
if not isinstance(pubkey, bitcoin.core.key.CPubKey):
pubkey = bitcoin.core.key.CPubKey(pubkey)
if not pubkey.is_fullyvalid:
raise CBitcoinAddressError('invalid pubkey')
pubkey_hash = bitcoin.core.Hash160(pubkey)
return P2PKHBitcoinAddress.from_bytes(pubkey_hash)
@classmethod
def from_scriptPubKey(cls, scriptPubKey, accept_non_canonical_pushdata=True, accept_bare_checksig=True):
"""Convert a scriptPubKey to a P2PKH address
Raises CBitcoinAddressError if the scriptPubKey isn't of the correct
form.
accept_non_canonical_pushdata - Allow non-canonical pushes (default True)
accept_bare_checksig - Treat bare-checksig as P2PKH scriptPubKeys (default True)
"""
if accept_non_canonical_pushdata:
# Canonicalize script pushes
scriptPubKey = script.CScript(scriptPubKey) # in case it's not a CScript instance yet
try:
scriptPubKey = script.CScript(tuple(scriptPubKey)) # canonicalize
except bitcoin.core.script.CScriptInvalidError:
raise CBitcoinAddressError('not a P2PKH scriptPubKey: script is invalid')
if scriptPubKey.is_witness_v0_keyhash():
return cls.from_bytes(scriptPubKey[2:22], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
elif scriptPubKey.is_witness_v0_nested_keyhash():
return cls.from_bytes(scriptPubKey[3:23], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
elif (len(scriptPubKey) == 25
and scriptPubKey[0] == script.OP_DUP
and scriptPubKey[1] == script.OP_HASH160
and scriptPubKey[2] == 0x14
and scriptPubKey[23] == script.OP_EQUALVERIFY
and scriptPubKey[24] == script.OP_CHECKSIG):
return cls.from_bytes(scriptPubKey[3:23], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
elif accept_bare_checksig:
pubkey = None
# We can operate on the raw bytes directly because we've
# canonicalized everything above.
if (len(scriptPubKey) == 35 # compressed
and scriptPubKey[0] == 0x21
and scriptPubKey[34] == script.OP_CHECKSIG):
pubkey = scriptPubKey[1:34]
elif (len(scriptPubKey) == 67 # uncompressed
and scriptPubKey[0] == 0x41
and scriptPubKey[66] == script.OP_CHECKSIG):
pubkey = scriptPubKey[1:65]
if pubkey is not None:
return cls.from_pubkey(pubkey, accept_invalid=True)
raise CBitcoinAddressError('not a P2PKH scriptPubKey')
def to_scriptPubKey(self, nested=False):
"""Convert an address to a scriptPubKey"""
assert self.nVersion == bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR']
return script.CScript([script.OP_DUP, script.OP_HASH160, self, script.OP_EQUALVERIFY, script.OP_CHECKSIG])
def to_redeemScript(self):
return self.to_scriptPubKey()
class P2WSHBitcoinAddress(CBech32BitcoinAddress):
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a P2WSH address
Raises CBitcoinAddressError if the scriptPubKey isn't of the correct
form.
"""
if scriptPubKey.is_witness_v0_scripthash():
return cls.from_bytes(0, scriptPubKey[2:34])
else:
raise CBitcoinAddressError('not a P2WSH scriptPubKey')
def to_scriptPubKey(self):
"""Convert an address to a scriptPubKey"""
assert self.witver == 0
return script.CScript([0, self])
def to_redeemScript(self):
raise NotImplementedError("Not enough data in p2wsh address to reconstruct redeem script")
class P2WPKHBitcoinAddress(CBech32BitcoinAddress):
@classmethod
def from_scriptPubKey(cls, scriptPubKey):
"""Convert a scriptPubKey to a P2WPKH address
Raises CBitcoinAddressError if the scriptPubKey isn't of the correct
form.
"""
if scriptPubKey.is_witness_v0_keyhash():
return cls.from_bytes(0, scriptPubKey[2:22])
else:
raise CBitcoinAddressError('not a P2WPKH scriptPubKey')
def to_scriptPubKey(self):
"""Convert an address to a scriptPubKey"""
assert self.witver == 0
return script.CScript([0, self])
def to_redeemScript(self):
return script.CScript([script.OP_DUP, script.OP_HASH160, self, script.OP_EQUALVERIFY, script.OP_CHECKSIG])
class CKey(object):
"""An encapsulated private key
Attributes:
pub - The corresponding CPubKey for this private key
is_compressed - True if compressed
"""
def __init__(self, secret, compressed=True):
self._cec_key = bitcoin.core.key.CECKey()
self._cec_key.set_secretbytes(secret)
self._cec_key.set_compressed(compressed)
self.pub = bitcoin.core.key.CPubKey(self._cec_key.get_pubkey(), self._cec_key)
@property
def is_compressed(self):
return self.pub.is_compressed
def sign(self, hash):
return self._cec_key.sign(hash)
def sign_compact(self, hash):
return self._cec_key.sign_compact(hash)
class CBitcoinSecretError(bitcoin.base58.Base58Error):
pass
class CBitcoinSecret(bitcoin.base58.CBase58Data, CKey):
"""A base58-encoded secret key"""
@classmethod
def from_secret_bytes(cls, secret, compressed=True):
"""Create a secret key from a 32-byte secret"""
self = cls.from_bytes(secret + (b'\x01' if compressed else b''),
bitcoin.params.BASE58_PREFIXES['SECRET_KEY'])
self.__init__(None)
return self
def __init__(self, s):
if self.nVersion != bitcoin.params.BASE58_PREFIXES['SECRET_KEY']:
raise CBitcoinSecretError('Not a base58-encoded secret key: got nVersion=%d; expected nVersion=%d' % \
(self.nVersion, bitcoin.params.BASE58_PREFIXES['SECRET_KEY']))
CKey.__init__(self, self[0:32], len(self) > 32 and self[32] == 1)
__all__ = (
'CBitcoinAddressError',
'CBitcoinAddress',
'CBase58BitcoinAddress',
'CBech32BitcoinAddress',
'P2SHBitcoinAddress',
'P2PKHBitcoinAddress',
'P2WSHBitcoinAddress',
'P2WPKHBitcoinAddress',
'CKey',
'CBitcoinSecretError',
'CBitcoinSecret',
)
|