MCPcopy Index your code
hub / github.com/petertodd/python-bitcoinlib / from_scriptPubKey

Method from_scriptPubKey

bitcoin/wallet.py:219–270  ·  view source on GitHub ↗

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

(cls, scriptPubKey, accept_non_canonical_pushdata=True, accept_bare_checksig=True)

Source from the content-addressed store, hash-verified

217
218 @classmethod
219 def from_scriptPubKey(cls, scriptPubKey, accept_non_canonical_pushdata=True, accept_bare_checksig=True):
220 """Convert a scriptPubKey to a P2PKH address
221
222 Raises CBitcoinAddressError if the scriptPubKey isn't of the correct
223 form.
224
225 accept_non_canonical_pushdata - Allow non-canonical pushes (default True)
226
227 accept_bare_checksig - Treat bare-checksig as P2PKH scriptPubKeys (default True)
228 """
229 if accept_non_canonical_pushdata:
230 # Canonicalize script pushes
231 scriptPubKey = script.CScript(scriptPubKey) # in case it's not a CScript instance yet
232
233 try:
234 scriptPubKey = script.CScript(tuple(scriptPubKey)) # canonicalize
235 except bitcoin.core.script.CScriptInvalidError:
236 raise CBitcoinAddressError('not a P2PKH scriptPubKey: script is invalid')
237
238 if scriptPubKey.is_witness_v0_keyhash():
239 return cls.from_bytes(scriptPubKey[2:22], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
240 elif scriptPubKey.is_witness_v0_nested_keyhash():
241 return cls.from_bytes(scriptPubKey[3:23], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
242 elif (len(scriptPubKey) == 25
243 and scriptPubKey[0] == script.OP_DUP
244 and scriptPubKey[1] == script.OP_HASH160
245 and scriptPubKey[2] == 0x14
246 and scriptPubKey[23] == script.OP_EQUALVERIFY
247 and scriptPubKey[24] == script.OP_CHECKSIG):
248 return cls.from_bytes(scriptPubKey[3:23], bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'])
249
250 elif accept_bare_checksig:
251 pubkey = None
252
253 # We can operate on the raw bytes directly because we've
254 # canonicalized everything above.
255 if (len(scriptPubKey) == 35 # compressed
256 and scriptPubKey[0] == 0x21
257 and scriptPubKey[34] == script.OP_CHECKSIG):
258
259 pubkey = scriptPubKey[1:34]
260
261 elif (len(scriptPubKey) == 67 # uncompressed
262 and scriptPubKey[0] == 0x41
263 and scriptPubKey[66] == script.OP_CHECKSIG):
264
265 pubkey = scriptPubKey[1:65]
266
267 if pubkey is not None:
268 return cls.from_pubkey(pubkey, accept_invalid=True)
269
270 raise CBitcoinAddressError('not a P2PKH scriptPubKey')
271
272 def to_scriptPubKey(self, nested=False):
273 """Convert an address to a scriptPubKey"""

Callers

nothing calls this directly

Calls 5

is_witness_v0_keyhashMethod · 0.95
from_pubkeyMethod · 0.80
from_bytesMethod · 0.45

Tested by

no test coverage detected