-
Notifications
You must be signed in to change notification settings - Fork 493
/
bip32.py
147 lines (114 loc) · 5.08 KB
/
bip32.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
import hashlib
import hmac
import logging
import struct
from ..encoding.bytes32 import from_bytes_32, to_bytes_32
from ..encoding.sec import public_pair_to_sec
logger = logging.getLogger(__name__)
_SUBKEY_VALIDATION_LOG_ERR_FMT = """
BUY A LOTTO TICKET RIGHT NOW! (And consider giving up your wallet to
science!)
You have stumbled across an astronomically unlikely scenario. Your HD
wallet contains an invalid subkey. Having access to this information would
be incredibly valuable to the Bitcoin development community.
If you are inclined to help, please make sure to back up this wallet (or
any outputted information) onto a USB drive and e-mail "Richard Kiss"
<him@richardkiss.com> or "Matt Bogosian" <mtb19@columbia.edu> for
instructions on how best to donate it without losing your bitcoins.
WARNING: DO NOT SEND ANY WALLET INFORMATION UNLESS YOU WANT TO LOSE ALL
THE BITCOINS IT CONTAINS.
""".strip()
class DerivationError(ValueError):
pass
def subkey_secret_exponent_chain_code_pair(
generator, secret_exponent, chain_code_bytes, i, is_hardened, public_pair=None):
"""
Yield info for a child node for this node.
generator:
the ecdsa generator
secret_exponent:
base secret exponent
chain_code:
base chain code
i:
the index for this node.
is_hardened:
use "hardened key derivation". The public version of this node cannot calculate this child.
public_pair:
the public_pair for the given secret exponent. If you leave it None, it's calculated for you
(but then it's slower)
Returns a pair (new_secret_exponent, new_chain_code)
"""
ORDER = generator.order()
i_as_bytes = struct.pack(">L", i)
if is_hardened:
data = b'\0' + to_bytes_32(secret_exponent) + i_as_bytes
else:
if public_pair is None:
public_pair = secret_exponent * generator
sec = public_pair_to_sec(public_pair, compressed=True)
data = sec + i_as_bytes
I64 = hmac.HMAC(key=chain_code_bytes, msg=data, digestmod=hashlib.sha512).digest()
I_left_as_exponent = from_bytes_32(I64[:32]) % ORDER
new_secret_exponent = (I_left_as_exponent + secret_exponent) % ORDER
if new_secret_exponent == 0:
logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT)
raise DerivationError('k_{} == 0'.format(i))
new_chain_code = I64[32:]
return new_secret_exponent, new_chain_code
def subkey_public_pair_chain_code_pair(generator, public_pair, chain_code_bytes, i):
"""
Yield info for a child node for this node.
generator:
the ecdsa generator
public_pair:
base public pair
chain_code:
base chain code
i:
the index for this node.
Returns a pair (new_public_pair, new_chain_code)
"""
INFINITY = generator.infinity()
ORDER = generator.order()
i_as_bytes = struct.pack(">l", i)
sec = public_pair_to_sec(public_pair, compressed=True)
data = sec + i_as_bytes
I64 = hmac.HMAC(key=chain_code_bytes, msg=data, digestmod=hashlib.sha512).digest()
I_left_as_exponent = from_bytes_32(I64[:32]) % ORDER
the_point = I_left_as_exponent * generator + generator.Point(*public_pair)
if the_point == INFINITY:
logger.critical(_SUBKEY_VALIDATION_LOG_ERR_FMT)
raise DerivationError('K_{} == {}'.format(i, the_point))
new_chain_code = I64[32:]
return the_point, new_chain_code
"""
A BIP0032-style hierarchical wallet.
Implement a BIP0032-style hierarchical wallet which can create public
or private wallet keys. Each key can create many child nodes. Each node
has a wallet key and a corresponding private & public key, which can
be used to generate Bitcoin addresses or WIF private keys.
At any stage, the private information can be stripped away, after which
descendants can only produce public keys.
Private keys can also generate "hardened" children, which cannot be
generated by the corresponding public keys. This is useful for generating
"change" addresses, for example, which there is no need to share with people
you give public keys to.
The MIT License (MIT)
Copyright (c) 2013 by Richard Kiss
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""