Debian Codegraph @

bip32gen

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #!/usr/bin/env python
2 #
3 # Copyright 2014 Corgan Labs
4 # See LICENSE.txt for distribution terms
5 #
6
7 import os, sys, argparse, re
8 from bip32utils import *
9
10 # __main__ entrypoint at bottom
11
12 def ReadInput(fname, count, is_hex):
13 "Read input from either stdin or file, optionally hex decoded"
14 f = sys.stdin if fname == '-' else open(fname, 'rb')
15
16 with f:
17 if count is not None:
18 n = count*2 if is_hex else count
19 data = f.read(n)
20 else:
21 data = f.read()
22
23 if is_hex:
24 data = data.strip().decode('hex')
25 return data
26
27
28 def WriteOutput(fname, prefix, data, is_hex):
29 "Write output to either stdout or file, optionally hex encoded"
30 if is_hex:
31 data = data.encode('hex')
32 f= sys.stdout if fname == '-' else open(fname, 'w')
33 f.write(prefix+data+'\n')
34
35
36 def ParseKeyspec(args, input_data, keyspec, cache):
37 """
38 Create a key from key specification with common args, storing
39 intermediate keys in a cache for reuse.
40
41 Assumes keyspec format already validated with regex.
42
43 There are three sources of input for key generation:
44
45 * Supplying entropy from stdin or file, from which
46 the master key and seed will be generated per BIP0032.
47 This is one option for keyspecs starting with 'm/...' or
48 'M/...'. Keyspecs starting with 'M' result in public-
49 only keys. From this master key, they keyspec is
50 recursively parsed to create child keys using the indices
51 found in the keyspec.
52
53 * Supplying an extended private key, which is imported back
54 into a normal key. From this, normal or hardened child keys
55 are recursively derived using the private derivation algorithm
56 and index numbers in the keyspec. The returned key is capable
57 of generating further normal or hardened child keys.
58
59 * Supplying an extended public key, which is imported back into
60 a public-only key. From this, public-only keys are recursively
61 derived using the public derivation algorithm and index numbers
62 in the keyspec. The returned key does not have a private key half
63 and is only further capable of generating publicly derived child
64 keys.
65 """
66 key = None
67 acc = ''
68
69 # Generate initial key, either from entropy, xprv, or xpub
70 if args.input_type == 'entropy':
71 acc = keyspec.split('/')[0]
72 try:
73 key = cache[acc]
74 except KeyError:
75 public = (acc == 'M')
76 key = BIP32Key.fromEntropy(entropy=input_data['entropy'], public=public, testnet=args.testnet)
77 cache[acc] = key
78 elif args.input_type == 'xprv':
79 try:
80 key = cache['xprv']
81 except KeyError:
82 key = BIP32Key.fromExtendedKey(input_data['xprv'])
83 cache['xprv'] = key
84 else:
85 try:
86 key = cache['xpub']
87 except KeyError:
88 key = BIP32Key.fromExtendedKey(input_data['xpub'])
89 cache['xpub'] = key
90
91 # Parse nodes, build up intermediate keys
92 for node in keyspec.split('/'):
93 if node in ['m', 'M']:
94 key = cache[node]
95 else:
96 # Descendent or relative node
97 if acc == '':
98 acc = node
99 else:
100 acc = acc + '/' + node
101
102 try:
103 key = cache[acc]
104 except KeyError:
105 if key is None:
106 key = cache[args.input_type]
107 # Now generate child keys
108 i = int(node.split('h')[0])
109 if 'h' in node:
110 i = i + BIP32_HARDEN
111 key = key.ChildKey(i)
112 cache[acc] = key
113 return key
114
115
116 # Input sources
117
118 def ReadEntropy(args):
119 "Reads optionally hex-encoded data from source"
120 entropy = ReadInput(args.from_file, args.amount/8, args.input_hex)
121 if len(entropy) < args.amount/8:
122 raise Exception("Insufficient entropy provided")
123 if args.verbose:
124 src = 'stdin' if args.from_file == '-' else args.from_file
125 print("Creating master key and seed using %i bits of entropy read from %s" % (args.amount, src))
126 print("entropy: %s" % entropy.encode('hex'))
127 return entropy
128
129
130 valid_output_types = ['addr','privkey','wif','pubkey','xprv','xpub','chain']
131
132 def GetArgs():
133 "Parse command line and validate inputs"
134 parser = argparse.ArgumentParser(description='Create hierarchical deterministic wallet addresses')
135 parser.add_argument('-x', '--input-hex', action='store_true', default=False,
136 help='input supplied as hex-encoded ascii')
137 parser.add_argument('-X', '--output-hex', action='store_true', default=False,
138 help='output generated (where applicable) as hex-encoded ascii')
139 parser.add_argument('-i', '--input-type', choices=['entropy','xprv','xpub'], required=True, action='store',
140 help='source material to generate key')
141 parser.add_argument('-n', '--amount', type=int, default=128, action='store',
142 help='amount of entropy to to read (bits), None for all of input')
143 parser.add_argument('-f', '--from-file', action='store', default='-',
144 help="filespec of input data, '-' for stdin")
145 parser.add_argument('-F', '--to-file', action='store', default='-',
146 help="filespec of output data, '-' for stdout")
147 parser.add_argument('-o', '--output-type', action='store', required=True,
148 help='output types, comma separated, from %s' % '|'.join(valid_output_types))
149 parser.add_argument('-v', '--verbose', action='store_true', default=False,
150 help='verbose output, not for machine parsing')
151 parser.add_argument('-d', '--debug', action='store_true', default=False,
152 help='enable debugging output')
153 parser.add_argument('chain', nargs='+',
154 help='list of hierarchical key specifiers')
155 parser.add_argument('-t', '--testnet', action='store_true', default=False,
156 help='use testnet format')
157
158 args = parser.parse_args()
159
160 # Validate -f, --from-file is readable
161 ff = args.from_file
162 if ff != '-' and os.access(ff, os.R_OK) is False:
163 raise ValueError("unable to read from %s, aborting" % ff)
164
165 # Validate -F, --to-file parent dir is writeable
166 tf = args.to_file
167 if tf != '-':
168 pd = os.path.dirname(os.path.abspath(tf))
169 if os.access(pd, os.W_OK) is False:
170 raise ValueError("do not have permissions to create file in %s, aborting\n" % pd)
171
172 # Validate -o, --output-type
173 for o in args.output_type.split(','):
174 if o not in valid_output_types:
175 valid_output_display = '['+'|'.join(valid_output_types)+']'
176 raise ValueError("output type \'%s\' is not one of %s\n" % (o, valid_output_display))
177
178 # Validate keyspecs for syntax
179 for keyspec in args.chain:
180 if not re.match("^([mM]|[0-9]+h?)(/[0-9]+h?)*$", keyspec):
181 raise ValueError("chain %s is not valid\n" % keyspec)
182 # If input is from entropy, keyspec must be absolute
183 elif args.input_type == 'entropy' and keyspec[0] not in 'mM':
184 raise ValueError("When generating from entropy, keyspec must start with 'm' or 'M'")
185 # Importing extended private or public keys need relative keyspecs
186 elif args.input_type in ['xpub','xprv'] and keyspec[0] in 'mM':
187 raise ValueError("When generating from xprv or xpub, keyspec must start with 0..9")
188
189 return args
190
191
192 def ErrorExit(e):
193 "Hard bailout printing exception"
194 sys.stderr.write(sys.argv[0]+": "+e.message+'\n')
195 sys.exit(1)
196
197
198 if __name__ == "__main__":
199 try:
200 args = GetArgs()
201 except Exception as e:
202 ErrorExit(e)
203
204 # Get common input data
205 input_data = {}
206 try:
207 if args.input_type == 'entropy':
208 input_data['entropy'] = ReadEntropy(args)
209 elif args.input_type == 'xprv':
210 if args.verbose:
211 print("Importing starting key from extended private key")
212 input_data['xprv'] = ReadInput(args.from_file, None, False).strip()
213 elif args.input_type == 'xpub':
214 if args.verbose:
215 print("Importing starting key from extended public key")
216 input_data['xpub'] = ReadInput(args.from_file, None, False).strip()
217 except Exception as e:
218 ErrorExit(e)
219
220 # Iterate through keyspecs, create, then output
221 cache = {}
222 otypes = args.output_type.split(',')
223
224 for keyspec in args.chain:
225 if args.verbose:
226 print("Keyspec: %s" % keyspec)
227 key = ParseKeyspec(args, input_data, keyspec, cache)
228
229 # Output fields in command-line supplied order
230 for otype in otypes:
231 prefix = '' if not args.verbose else otype+':'+' '*(8-len(otype))
232 if otype == 'addr':
233 WriteOutput(args.to_file, prefix, key.Address(), False)
234 elif otype == 'privkey':
235 WriteOutput(args.to_file, prefix, key.PrivateKey(), args.output_hex)
236 elif otype == 'wif':
237 WriteOutput(args.to_file, prefix, key.WalletImportFormat(), False)
238 elif otype == 'pubkey':
239 WriteOutput(args.to_file, prefix, key.PublicKey(), args.output_hex)
240 elif otype == 'xprv':
241 WriteOutput(args.to_file, prefix, key.ExtendedKey(private=True, encoded=True), False)
242 elif otype == 'xpub':
243 WriteOutput(args.to_file, prefix, key.ExtendedKey(private=False, encoded=True), False)
244 elif otype == 'chain':
245 WriteOutput(args.to_file, prefix, key.ChainCode(), args.output_hex)
246 if args.verbose:
247 WriteOutput(args.to_file, '', '', False)