-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathwallet.py
255 lines (193 loc) · 9.14 KB
/
wallet.py
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
# Copyright (C) 2012-2014 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.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
_bord = ord
if sys.version > '3':
_bord = lambda x: x
import bitcoin
import bitcoin.base58
import bitcoin.core
import bitcoin.core.key
import bitcoin.core.script as script
class CBitcoinAddressError(bitcoin.base58.Base58Error):
"""Raised when an invalid Bitcoin address is encountered"""
class CBitcoinAddress(bitcoin.base58.CBase58Data):
"""A Bitcoin address"""
@classmethod
def from_bytes(cls, data, nVersion):
self = super(CBitcoinAddress, 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 address')
def to_scriptPubKey(self):
"""Convert an address to a scriptPubKey"""
raise NotImplementedError
class P2SHBitcoinAddress(CBitcoinAddress):
@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])
class P2PKHBitcoinAddress(CBitcoinAddress):
@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 (len(scriptPubKey) == 25
and _bord(scriptPubKey[0]) == script.OP_DUP
and _bord(scriptPubKey[1]) == script.OP_HASH160
and _bord(scriptPubKey[2]) == 0x14
and _bord(scriptPubKey[23]) == script.OP_EQUALVERIFY
and _bord(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 _bord(scriptPubKey[0]) == 0x21
and _bord(scriptPubKey[34]) == script.OP_CHECKSIG):
pubkey = scriptPubKey[1:34]
elif (len(scriptPubKey) == 67 # uncompressed
and _bord(scriptPubKey[0]) == 0x41
and _bord(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):
"""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])
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)
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 _bord(self[32]) == 1)
__all__ = (
'CBitcoinAddressError',
'CBitcoinAddress',
'P2SHBitcoinAddress',
'P2PKHBitcoinAddress',
'CKey',
'CBitcoinSecretError',
'CBitcoinSecret',
)