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