New 'mmgen-walletconv' utility converts to and from all available MMGen wallet
formats, thus obsoleting much of the functionality in '-walletgen' and '-walletchk'. This is the first script to utilize the new OO wallet code in 'seed.py'. New tests in the 'test.py' suite. new file: mmgen-walletconv new file: mmgen/main_walletconv.py modified: mmgen/seed.py modified: test/test.py
This commit is contained in:
parent
1c1659add0
commit
03b1b4b00e
41 changed files with 1728 additions and 1090 deletions
25
mmgen-walletconv
Executable file
25
mmgen-walletconv
Executable file
|
|
@ -0,0 +1,25 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""
|
||||
mmgen-walletconv: Convert an MMGen deterministic wallet from one format
|
||||
to another
|
||||
"""
|
||||
|
||||
from mmgen.main import launch
|
||||
launch("walletconv")
|
||||
|
|
@ -224,6 +224,13 @@ class AddrInfoList(MMGenObject):
|
|||
if sid in self.data:
|
||||
return self.data[sid]
|
||||
|
||||
def mmaddr2btcaddr(self,mmaddr):
|
||||
btcaddr = ""
|
||||
sid,idx = mmaddr.split(":")
|
||||
if sid in self.seed_ids():
|
||||
btcaddr = self.addrinfo(sid).btcaddr(int(idx))
|
||||
return btcaddr
|
||||
|
||||
def add_wallet_data(self,c):
|
||||
vmsg_r("Getting account data from wallet...")
|
||||
data,accts,i = {},c.listaccounts(minconf=0,includeWatchonly=True),0
|
||||
|
|
@ -291,10 +298,12 @@ class AddrInfo(MMGenObject):
|
|||
self.seed_id = seed_id
|
||||
self.addrdata = addrdata
|
||||
self.num_addrs = len(addrdata)
|
||||
if self.source in ("wallet","txsign") or \
|
||||
(self.source == "addrgen" and opt.gen_what == "k"):
|
||||
if self.source in ("wallet","txsign"):
|
||||
self.checksum = None
|
||||
self.idxs_fmt = None
|
||||
elif self.source == "addrgen" and opt.gen_what == "k":
|
||||
self.checksum = None
|
||||
self.fmt_addr_idxs()
|
||||
else: # self.source in addrfile, addrgen
|
||||
self.make_addrdata_chksum()
|
||||
self.fmt_addr_idxs()
|
||||
|
|
@ -383,10 +392,11 @@ class AddrInfo(MMGenObject):
|
|||
out = []
|
||||
from mmgen.addr import addrmsgs
|
||||
out.append(addrmsgs['addrfile_header'] + "\n")
|
||||
w = "Key-address" if status[1] else "Address"
|
||||
out.append("# {} data checksum for {}[{}]: {}".format(
|
||||
w, self.seed_id, self.idxs_fmt, self.checksum))
|
||||
out.append("# Record this value to a secure location\n")
|
||||
if self.checksum:
|
||||
w = "Key-address" if status[1] else "Address"
|
||||
out.append("# {} data checksum for {}[{}]: {}".format(
|
||||
w, self.seed_id, self.idxs_fmt, self.checksum))
|
||||
out.append("# Record this value to a secure location\n")
|
||||
out.append("%s {" % self.seed_id)
|
||||
|
||||
# Body
|
||||
|
|
@ -409,7 +419,7 @@ class AddrInfo(MMGenObject):
|
|||
|
||||
out.append("}")
|
||||
|
||||
return "\n".join([l.rstrip() for l in out])
|
||||
return "\n".join([l.rstrip() for l in out]) + "\n"
|
||||
|
||||
|
||||
def fmt_addr_idxs(self):
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@
|
|||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""
|
||||
crypto.py: Cryptographic and related routines for the 'mmgen-tool' utility
|
||||
crypto.py: Cryptographic and related routines for the MMGen suite
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
|
@ -58,7 +58,7 @@ to exit and re-run the program with the '--old-incog-fmt' option.
|
|||
}
|
||||
|
||||
def encrypt_seed(seed, key):
|
||||
return encrypt_data(seed, key, iv=1, what="seed")
|
||||
return encrypt_data(seed, key, iv=1, desc="seed")
|
||||
|
||||
|
||||
def decrypt_seed(enc_seed, key, seed_id, key_id):
|
||||
|
|
@ -66,21 +66,21 @@ def decrypt_seed(enc_seed, key, seed_id, key_id):
|
|||
vmsg_r("Checking key...")
|
||||
chk1 = make_chksum_8(key)
|
||||
if key_id:
|
||||
if not compare_chksums(key_id,"key id",chk1,"computed",die=False):
|
||||
if not compare_chksums(key_id,"key ID",chk1,"computed"):
|
||||
msg("Incorrect passphrase")
|
||||
return False
|
||||
|
||||
dec_seed = decrypt_data(enc_seed, key, iv=1, what="seed")
|
||||
dec_seed = decrypt_data(enc_seed, key, iv=1, desc="seed")
|
||||
|
||||
chk2 = make_chksum_8(dec_seed)
|
||||
|
||||
if seed_id:
|
||||
if compare_chksums(seed_id,"seed id",chk2,"decrypted seed",die=False):
|
||||
if compare_chksums(seed_id,"seed ID",chk2,"decrypted seed"):
|
||||
qmsg("Passphrase is OK")
|
||||
else:
|
||||
if not opt.debug:
|
||||
msg_r("Checking key ID...")
|
||||
if compare_chksums(key_id,"key id",chk1,"computed",die=False):
|
||||
if compare_chksums(key_id,"key ID",chk1,"computed"):
|
||||
msg("Key ID is correct but decryption of seed failed")
|
||||
else:
|
||||
msg("Incorrect passphrase")
|
||||
|
|
@ -90,29 +90,25 @@ def decrypt_seed(enc_seed, key, seed_id, key_id):
|
|||
# else:
|
||||
# qmsg("Generated IDs (Seed/Key): %s/%s" % (chk2,chk1))
|
||||
|
||||
if opt.debug: Msg("Decrypted seed: %s" % hexlify(dec_seed))
|
||||
dmsg("Decrypted seed: %s" % hexlify(dec_seed))
|
||||
|
||||
vmsg("OK")
|
||||
return dec_seed
|
||||
|
||||
|
||||
def encrypt_data(data, key, iv=1, what="data", verify=True):
|
||||
"""
|
||||
Encrypt arbitrary data using AES256 in counter mode
|
||||
"""
|
||||
def encrypt_data(data, key, iv=1, desc="data", verify=True):
|
||||
|
||||
# 192-bit seed is 24 bytes -> not multiple of 16. Must use MODE_CTR
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util import Counter
|
||||
|
||||
vmsg("Encrypting %s" % what)
|
||||
vmsg("Encrypting %s" % desc)
|
||||
|
||||
c = AES.new(key, AES.MODE_CTR,
|
||||
counter=Counter.new(g.aesctr_iv_len*8,initial_value=iv))
|
||||
enc_data = c.encrypt(data)
|
||||
|
||||
if verify:
|
||||
vmsg_r("Performing a test decryption of the %s..." % what)
|
||||
vmsg_r("Performing a test decryption of the %s..." % desc)
|
||||
|
||||
c = AES.new(key, AES.MODE_CTR,
|
||||
counter=Counter.new(g.aesctr_iv_len*8,initial_value=iv))
|
||||
|
|
@ -120,15 +116,15 @@ def encrypt_data(data, key, iv=1, what="data", verify=True):
|
|||
|
||||
if dec_data == data: vmsg("done")
|
||||
else:
|
||||
msg("ERROR.\nDecrypted %s doesn't match original %s" % (what,what))
|
||||
msg("ERROR.\nDecrypted %s doesn't match original %s" % (desc,desc))
|
||||
sys.exit(2)
|
||||
|
||||
return enc_data
|
||||
|
||||
|
||||
def decrypt_data(enc_data, key, iv=1, what="data"):
|
||||
def decrypt_data(enc_data, key, iv=1, desc="data"):
|
||||
|
||||
vmsg_r("Decrypting %s with key..." % what)
|
||||
vmsg_r("Decrypting %s with key..." % desc)
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util import Counter
|
||||
|
|
@ -151,18 +147,18 @@ def scrypt_hash_passphrase(passwd, salt, hash_preset, buflen=32):
|
|||
|
||||
|
||||
def make_key(passwd,salt,hash_preset,
|
||||
what="encryption key",from_what="passphrase",verbose=False):
|
||||
desc="encryption key",from_what="passphrase",verbose=False):
|
||||
|
||||
if from_what: what += " from "
|
||||
if from_what: desc += " from "
|
||||
if opt.verbose or verbose:
|
||||
msg_r("Generating %s%s..." % (what,from_what))
|
||||
msg_r("Generating %s%s..." % (desc,from_what))
|
||||
key = scrypt_hash_passphrase(passwd, salt, hash_preset)
|
||||
if opt.verbose or verbose: msg("done")
|
||||
if opt.debug: Msg("Key: %s" % hexlify(key))
|
||||
dmsg("Key: %s" % hexlify(key))
|
||||
return key
|
||||
|
||||
|
||||
def get_random_data_from_user(uchars):
|
||||
def _get_random_data_from_user(uchars):
|
||||
|
||||
if opt.quiet: msg("Enter %s random symbols" % uchars)
|
||||
else: msg(crmsg['usr_rand_notice'] % uchars)
|
||||
|
|
@ -189,8 +185,7 @@ def get_random_data_from_user(uchars):
|
|||
|
||||
fmt_time_data = ["{:.22f}".format(i) for i in time_data]
|
||||
|
||||
if opt.debug:
|
||||
msg("\nUser input:\n%s\nKeystroke time intervals:\n%s\n" %
|
||||
dmsg("\nUser input:\n%s\nKeystroke time intervals:\n%s\n" %
|
||||
(key_data,"\n".join(fmt_time_data)))
|
||||
|
||||
prompt = "User random data successfully acquired. Press ENTER to continue"
|
||||
|
|
@ -202,23 +197,23 @@ def get_random_data_from_user(uchars):
|
|||
def get_random(length):
|
||||
from Crypto import Random
|
||||
os_rand = Random.new().read(length)
|
||||
if g.use_urandchars:
|
||||
if g.use_urandchars and opt.usr_randchars:
|
||||
from_what = "OS random data"
|
||||
if not g.user_entropy:
|
||||
g.user_entropy = \
|
||||
sha256(get_random_data_from_user(opt.usr_randchars)).digest()
|
||||
sha256(_get_random_data_from_user(opt.usr_randchars)).digest()
|
||||
from_what += " plus user-supplied entropy"
|
||||
else:
|
||||
from_what += " plus saved user-supplied entropy"
|
||||
key = make_key(g.user_entropy, "", '2', from_what=from_what, verbose=True)
|
||||
return encrypt_data(os_rand,key,what="random data",verify=False)
|
||||
return encrypt_data(os_rand,key,desc="random data",verify=False)
|
||||
else:
|
||||
return os_rand
|
||||
|
||||
|
||||
def get_seed_from_wallet(
|
||||
infile,
|
||||
prompt_info="{pnm} wallet".format(pnm=g.proj_name),
|
||||
desc="{pnm} wallet".format(pnm=g.proj_name),
|
||||
silent=False
|
||||
):
|
||||
|
||||
|
|
@ -228,7 +223,7 @@ def get_seed_from_wallet(
|
|||
if opt.debug: display_control_data(*wdata)
|
||||
|
||||
padd = " "+infile if opt.quiet else ""
|
||||
passwd = get_mmgen_passphrase(prompt_info+padd)
|
||||
passwd = get_mmgen_passphrase(desc+padd)
|
||||
|
||||
key = make_key(passwd, salt, hash_preset)
|
||||
|
||||
|
|
@ -270,17 +265,17 @@ def confirm_old_format():
|
|||
|
||||
def get_seed_from_incog_wallet(
|
||||
infile,
|
||||
prompt_info="{pnm} incognito wallet".format(pnm=g.proj_name),
|
||||
desc="{pnm} incognito wallet".format(pnm=g.proj_name),
|
||||
silent=False,
|
||||
hex_input=False
|
||||
):
|
||||
|
||||
what = "incognito wallet data"
|
||||
desc = "incognito wallet data"
|
||||
|
||||
if opt.from_incog_hidden:
|
||||
d = get_hidden_incog_data()
|
||||
else:
|
||||
d = get_data_from_file(infile,what)
|
||||
d = get_data_from_file(infile,desc)
|
||||
if hex_input:
|
||||
try:
|
||||
d = unhexlify("".join(d.split()).strip())
|
||||
|
|
@ -310,10 +305,13 @@ def get_seed_from_incog_wallet(
|
|||
else 'incog_iv_id'])
|
||||
|
||||
while True:
|
||||
passwd = get_mmgen_passphrase(prompt_info+" "+incog_id)
|
||||
passwd = get_mmgen_passphrase(desc+" "+incog_id)
|
||||
|
||||
qmsg("Configured hash presets: %s" % " ".join(sorted(g.hash_presets)))
|
||||
hp = get_hash_preset_from_user(what="incog wallet")
|
||||
if 'hash_preset' in opt.set_by_user:
|
||||
hp = opt.hash_preset
|
||||
else:
|
||||
hp = get_hash_preset_from_user(desc="incog wallet")
|
||||
|
||||
# IV is used BOTH to initialize counter and to salt password!
|
||||
key = make_key(passwd, iv, hp, "wrapper key")
|
||||
|
|
@ -399,7 +397,7 @@ def _get_seed(infile,silent=False,seed_id=""):
|
|||
msg("Invalid %s file '%s'" % (source,infile))
|
||||
sys.exit(2)
|
||||
|
||||
if opt.debug: Msg("Seed: %s" % hexlify(seed))
|
||||
dmsg("Seed: %s" % hexlify(seed))
|
||||
|
||||
return seed
|
||||
|
||||
|
|
@ -415,9 +413,9 @@ def get_seed_retry(infile,seed_id=""):
|
|||
|
||||
def _get_seed_from_brain_passphrase(words,silent=False):
|
||||
bp = " ".join(words)
|
||||
if opt.debug: Msg("Sanitized brain passphrase: %s" % bp)
|
||||
dmsg("Sanitized brain passphrase: %s" % bp)
|
||||
seed_len,hash_preset = get_from_brain_opt_params()
|
||||
if opt.debug: Msg("Brainwallet l = %s, p = %s" % (seed_len,hash_preset))
|
||||
dmsg("Brainwallet l = %s, p = %s" % (seed_len,hash_preset))
|
||||
vmsg_r("Hashing brainwallet data. Please wait...")
|
||||
# Use buflen arg of scrypt.hash() to get seed of desired length
|
||||
seed = scrypt_hash_passphrase(bp, "", hash_preset, buflen=seed_len/8)
|
||||
|
|
@ -432,31 +430,31 @@ def _get_seed_from_brain_passphrase(words,silent=False):
|
|||
# Vars for mmgen_*crypt functions only
|
||||
salt_len,sha256_len,nonce_len = 32,32,32
|
||||
|
||||
def mmgen_encrypt(data,what="data",hash_preset=''):
|
||||
def mmgen_encrypt(data,desc="data",hash_preset=''):
|
||||
salt,iv,nonce = get_random(salt_len),\
|
||||
get_random(g.aesctr_iv_len), \
|
||||
get_random(nonce_len)
|
||||
hp = hash_preset or get_hash_preset_from_user('3',what)
|
||||
hp = hash_preset or get_hash_preset_from_user('3',desc)
|
||||
m = "default" if hp == '3' else "user-requested"
|
||||
vmsg("Encrypting %s" % what)
|
||||
vmsg("Encrypting %s" % desc)
|
||||
qmsg("Using %s hash preset of '%s'" % (m,hp))
|
||||
passwd = get_new_passphrase(what, {})
|
||||
passwd = get_new_passphrase(desc, {})
|
||||
key = make_key(passwd, salt, hp)
|
||||
enc_d = encrypt_data(sha256(nonce+data).digest() + nonce + data, key,
|
||||
int(hexlify(iv),16), what=what)
|
||||
int(hexlify(iv),16), desc=desc)
|
||||
return salt+iv+enc_d
|
||||
|
||||
|
||||
def mmgen_decrypt(data,what="data",hash_preset=""):
|
||||
def mmgen_decrypt(data,desc="data",hash_preset=""):
|
||||
dstart = salt_len + g.aesctr_iv_len
|
||||
salt,iv,enc_d = data[:salt_len],data[salt_len:dstart],data[dstart:]
|
||||
vmsg("Preparing to decrypt %s" % what)
|
||||
hp = hash_preset or get_hash_preset_from_user('3',what)
|
||||
vmsg("Preparing to decrypt %s" % desc)
|
||||
hp = hash_preset or get_hash_preset_from_user('3',desc)
|
||||
m = "default" if hp == '3' else "user-requested"
|
||||
qmsg("Using %s hash preset of '%s'" % (m,hp))
|
||||
passwd = get_mmgen_passphrase(what)
|
||||
passwd = get_mmgen_passphrase(desc)
|
||||
key = make_key(passwd, salt, hp)
|
||||
dec_d = decrypt_data(enc_d, key, int(hexlify(iv),16), what)
|
||||
dec_d = decrypt_data(enc_d, key, int(hexlify(iv),16), desc)
|
||||
if dec_d[:sha256_len] == sha256(dec_d[sha256_len:]).digest():
|
||||
vmsg("OK")
|
||||
return dec_d[sha256_len+nonce_len:]
|
||||
|
|
@ -464,8 +462,8 @@ def mmgen_decrypt(data,what="data",hash_preset=""):
|
|||
msg("Incorrect passphrase or hash preset")
|
||||
return False
|
||||
|
||||
def mmgen_decrypt_retry(d,what="data"):
|
||||
def mmgen_decrypt_retry(d,desc="data"):
|
||||
while True:
|
||||
d_dec = mmgen_decrypt(d,what)
|
||||
d_dec = mmgen_decrypt(d,desc)
|
||||
if d_dec: return d_dec
|
||||
msg("Trying again...")
|
||||
|
|
|
|||
|
|
@ -20,66 +20,25 @@
|
|||
filename.py: Filename class and methods for the MMGen suite
|
||||
"""
|
||||
import sys,os
|
||||
import mmgen.opt as opt
|
||||
from mmgen.obj import *
|
||||
import mmgen.globalvars as g
|
||||
from mmgen.util import msg,fmt_code_to_sstype
|
||||
from mmgen.util import die,get_extension,check_infile
|
||||
|
||||
class Filename(MMGenObject):
|
||||
|
||||
exts = {
|
||||
'seed': {
|
||||
"mmdat": "Wallet",
|
||||
"mmseed": "SeedFile",
|
||||
"mmwords": "Mnemonic",
|
||||
"mmbrain": "Brainwallet",
|
||||
"mmincog": "IncogWallet",
|
||||
"mmincox": "IncogWalletHex",
|
||||
},
|
||||
'tx': {
|
||||
"raw": "RawTX",
|
||||
"sig": "SigTX",
|
||||
},
|
||||
'addr': {
|
||||
"addrs": "AddrInfo",
|
||||
"keys": "KeyInfo",
|
||||
"akeys": "KeyAddrInfo",
|
||||
"akeys.mmenc": "KeyAddrInfoEnc",
|
||||
},
|
||||
'other': {
|
||||
"chk": "AddrInfoChecksum",
|
||||
"mmenc": "MMEncInfo",
|
||||
},
|
||||
}
|
||||
|
||||
ftypes = {
|
||||
'seed': {
|
||||
"hincog": "IncogWalletHidden",
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(self,fn,ftype=""):
|
||||
def __init__(self,fn,ftype=None):
|
||||
self.name = fn
|
||||
self.dirname = os.path.dirname(fn)
|
||||
self.basename = os.path.basename(fn)
|
||||
self.ext = None
|
||||
self.ftype = ftype
|
||||
|
||||
def mf1(k): return k == ftype
|
||||
def mf2(k): return '.'+k == fn[-len('.'+k):]
|
||||
# This should be done before license msg instead
|
||||
# check_infile(fn)
|
||||
|
||||
# find file info for ftype or extension
|
||||
e,attr,have_match = (self.ftypes,"ftype",mf1) if ftype else \
|
||||
(self.exts,"ext",mf2)
|
||||
|
||||
for k in e:
|
||||
for j in e[k]:
|
||||
if have_match(j):
|
||||
setattr(self,attr,j)
|
||||
self.fclass = k
|
||||
self.sstype = e[k][j]
|
||||
|
||||
if not hasattr(self,attr):
|
||||
die(2,"Unrecognized %s for file '%s'" % (attr,fn))
|
||||
if not ftype:
|
||||
self.ext = get_extension(fn)
|
||||
if not (self.ext):
|
||||
die(2,"Unrecognized extension '.%s' for file '%s'" % (self.ext,fn))
|
||||
|
||||
# TODO: Check for Windows
|
||||
import stat
|
||||
|
|
|
|||
|
|
@ -53,7 +53,8 @@ version = '0.8.0'
|
|||
|
||||
required_opts = [
|
||||
"quiet","verbose","debug","outdir","echo_passphrase","passwd_file",
|
||||
"usr_randchars","stdout","show_hash_presets"
|
||||
"usr_randchars","stdout","show_hash_presets","label",
|
||||
"keep_passphrase","keep_hash_preset"
|
||||
]
|
||||
min_screen_width = 80
|
||||
|
||||
|
|
@ -119,16 +120,3 @@ addr_label_symbols = wallet_label_symbols = printable_nonl
|
|||
max_addr_label_len = 32
|
||||
max_wallet_label_len = 48
|
||||
max_tx_comment_len = 72 # Comment is b58 encoded, so can permit all UTF-8
|
||||
|
||||
wallet_fmt_codes = (
|
||||
( "Wallet", "wallet", "w" ),
|
||||
( "SeedFile", "mmseed","seed", "s" ),
|
||||
( "Mnemonic", "mmwords","words","mnemonic","mnem","m" ),
|
||||
( "Brainwallet", "mmbrain","brainwallet","brain","bw","b" ),
|
||||
( "IncogWallet", "mmincog","incog","i" ),
|
||||
( "IncogWalletHex", "mmincox","incog_hex","ix" ),
|
||||
( "IncogWalletHidden", "incog_hidden","ih" ),
|
||||
)
|
||||
#addr_label_punc = ".","_",",","-"," ","(",")"
|
||||
#addr_label_symbols = tuple(ascii_letters + digits) + addr_label_punc
|
||||
#wallet_label_punc = addr_label_punc
|
||||
|
|
|
|||
|
|
@ -19,18 +19,16 @@
|
|||
"""
|
||||
license.py: Text of GPLv3
|
||||
"""
|
||||
|
||||
import mmgen.globalvars as g
|
||||
|
||||
gpl = {
|
||||
'warning': """
|
||||
warning = """
|
||||
{pnm} Copyright (C) {g.Cdates} by {g.author} {g.email}. This
|
||||
program comes with ABSOLUTELY NO WARRANTY. This is free software, and
|
||||
you are welcome to redistribute it under certain conditions.
|
||||
""".format(g=g,pnm=g.proj_name),
|
||||
'prompt': """
|
||||
Press 'w' for conditions and warranty info, or 'c' to continue:
|
||||
""",
|
||||
'conditions': """
|
||||
""".format(g=g,pnm=g.proj_name)
|
||||
|
||||
conditions = """
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
|
@ -581,4 +579,3 @@ an absolute waiver of all civil liability in connection with the
|
|||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
"""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ def launch(what):
|
|||
def launch_txsend(): import mmgen.main_txsend
|
||||
def launch_txsign(): import mmgen.main_txsign
|
||||
def launch_walletchk(): import mmgen.main_walletchk
|
||||
def launch_walletconv(): import mmgen.main_walletconv
|
||||
def launch_walletgen(): import mmgen.main_walletgen
|
||||
|
||||
try: import termios
|
||||
|
|
|
|||
|
|
@ -161,8 +161,8 @@ if opt.stdout or not sys.stdout.isatty():
|
|||
if enc_ext and sys.stdout.isatty():
|
||||
msg("Cannot write encrypted data to screen. Exiting")
|
||||
sys.exit(2)
|
||||
write_to_stdout(addrdata_str,what,
|
||||
(what=="keys"and not opt.quiet and sys.stdout.isatty()))
|
||||
write_to_stdout(addrdata_str,what,ask_terminal=(what=="keys"
|
||||
and not opt.quiet and sys.stdout.isatty()))
|
||||
else:
|
||||
outfile = "%s.%s%s" % (outfile_base, (
|
||||
g.keyaddrfile_ext if "ka" in opt.gen_what else (
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ if len(cmd_args) == 1:
|
|||
ai = AddrInfo(infile,has_keys=opt.keyaddr_file)
|
||||
else:
|
||||
msg("""
|
||||
"You must specify an mmgen address file (or a list of non-{pnm} addresses
|
||||
You must specify an {pnm} address file (or a list of non-{pnm} addresses
|
||||
with the '--addrlist' option)
|
||||
""".strip().format(pnm=g.proj_name))
|
||||
sys.exit(1)
|
||||
|
|
|
|||
|
|
@ -67,8 +67,8 @@ seed_id,key_id = metadata[:2]
|
|||
|
||||
# Repeat on incorrect pw entry
|
||||
while True:
|
||||
p = "{pnm} wallet".format(pnm=g.proj_name)
|
||||
passwd = get_mmgen_passphrase(p,not opt.keep_old_passphrase)
|
||||
desc = "{pnm} wallet".format(pnm=g.proj_name)
|
||||
passwd = get_mmgen_passphrase(desc,not opt.keep_old_passphrase)
|
||||
key = make_key(passwd, salt, hash_preset)
|
||||
seed = decrypt_seed(enc_seed, key, seed_id, key_id)
|
||||
if seed: break
|
||||
|
|
|
|||
|
|
@ -180,8 +180,8 @@ class AES(object):
|
|||
def rotate(self, word):
|
||||
""" Rijndael's key schedule rotate operation.
|
||||
|
||||
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
|
||||
Word is an char list of size 4 (32 bits overall).
|
||||
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
|
||||
Word is an char list of size 4 (32 bits overall).
|
||||
"""
|
||||
return word[1:] + word[:1]
|
||||
|
||||
|
|
@ -230,10 +230,10 @@ class AES(object):
|
|||
def expandKey(self, key, size, expandedKeySize):
|
||||
"""Rijndael's key expansion.
|
||||
|
||||
Expands an 128,192,256 key into an 176,208,240 bytes key
|
||||
Expands an 128,192,256 key into an 176,208,240 bytes key
|
||||
|
||||
expandedKey is a char list of large enough size,
|
||||
key is the non-expanded key.
|
||||
expandedKey is a char list of large enough size,
|
||||
key is the non-expanded key.
|
||||
"""
|
||||
# current expanded keySize, in bytes
|
||||
currentSize = 0
|
||||
|
|
@ -276,8 +276,8 @@ class AES(object):
|
|||
|
||||
def createRoundKey(self, expandedKey, roundKeyPointer):
|
||||
"""Create a round key.
|
||||
Creates a round key from the given expanded key and the
|
||||
position within the expanded key.
|
||||
Creates a round key from the given expanded key and the
|
||||
position within the expanded key.
|
||||
"""
|
||||
roundKey = [0] * 16
|
||||
for i in range(4):
|
||||
|
|
@ -1183,8 +1183,8 @@ def parse_BlockLocator(vds):
|
|||
return d
|
||||
|
||||
def deserialize_BlockLocator(d):
|
||||
result = "Block Locator top: "+d['hashes'][0][::-1].encode('hex_codec')
|
||||
return result
|
||||
result = "Block Locator top: "+d['hashes'][0][::-1].encode('hex_codec')
|
||||
return result
|
||||
|
||||
def parse_setting(setting, vds):
|
||||
if setting[0] == "f": # flag (boolean) settings
|
||||
|
|
@ -1404,11 +1404,11 @@ def parse_wallet(db, item_callback):
|
|||
|
||||
def update_wallet(db, type, data):
|
||||
"""Write a single item to the wallet.
|
||||
db must be open with writable=True.
|
||||
type and data are the type code and data dictionary as parse_wallet would
|
||||
give to item_callback.
|
||||
data's __key__, __value__ and __type__ are ignored; only the primary data
|
||||
fields are used.
|
||||
db must be open with writable=True.
|
||||
type and data are the type code and data dictionary as parse_wallet would
|
||||
give to item_callback.
|
||||
data's __key__, __value__ and __type__ are ignored; only the primary data
|
||||
fields are used.
|
||||
"""
|
||||
d = data
|
||||
kds = BCDataStream()
|
||||
|
|
@ -1656,8 +1656,8 @@ elif opt.keysforaddrs:
|
|||
msg("Warning: not all requested keys found")
|
||||
|
||||
len_arg = "%s" % len(wallet_addrs) \
|
||||
if len(data) == len(wallet_addrs) or ext == "json" \
|
||||
else "%s:%s" % (len(data),len(wallet_addrs))
|
||||
if len(data) == len(wallet_addrs) or ext == "json" \
|
||||
else "%s:%s" % (len(data),len(wallet_addrs))
|
||||
|
||||
from mmgen.util import make_chksum_8,write_to_file,write_to_stdout
|
||||
wallet_id = make_chksum_8(str(sorted(wallet_addrs)))
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ from decimal import Decimal
|
|||
|
||||
import mmgen.globalvars as g
|
||||
import mmgen.opt as opt
|
||||
from mmgen.util import dmsg
|
||||
from mmgen.tx import *
|
||||
|
||||
pnm = g.proj_name
|
||||
|
|
@ -196,9 +197,9 @@ Display options: show [D]ays, [g]roup, show [m]mgen addr, r[e]draw screen
|
|||
i.addr = "%s%s %s" % (
|
||||
i.address[:btaddr_w-len(dots)],
|
||||
dots, (
|
||||
("{:<{w}} ".format(i.mmid,w=mmid_w) if i.mmid else "")
|
||||
+ i.comment)[:acct_w]
|
||||
)
|
||||
("{:<{w}} ".format(i.mmid,w=mmid_w) if i.mmid else "")
|
||||
+ i.comment)[:acct_w]
|
||||
)
|
||||
else:
|
||||
i.addr = i.address
|
||||
|
||||
|
|
@ -294,16 +295,13 @@ def mmaddr2btcaddr_unspent(unspent,mmaddr):
|
|||
|
||||
|
||||
def mmaddr2btcaddr(c,mmaddr,ail_w,ail_f):
|
||||
# assume mmaddr has already been checked
|
||||
sid,idx = mmaddr.split(":")
|
||||
btcaddr = ""
|
||||
|
||||
if sid in ail_w.seed_ids():
|
||||
btcaddr = ail_w.addrinfo(sid).btcaddr(int(idx))
|
||||
# assume mmaddr has already been checked
|
||||
btcaddr = ail_w.mmaddr2btcaddr(mmaddr)
|
||||
|
||||
if not btcaddr:
|
||||
if ail_f and sid in ail_f.seed_ids():
|
||||
btcaddr = ail_f.addrinfo(sid).btcaddr(int(idx))
|
||||
if ail_f:
|
||||
btcaddr = ail_f.mmaddr2btcaddr(mmaddr)
|
||||
if btcaddr:
|
||||
msg(wmsg['addr_in_addrfile_only'].format(mmgenaddr=mmaddr))
|
||||
if not keypress_confirm("Continue anyway?"):
|
||||
|
|
@ -449,9 +447,7 @@ if change > 0: tx_out[change_addr] = float(change)
|
|||
|
||||
tx_in = [{"txid":i.txid, "vout":i.vout} for i in sel_unspent]
|
||||
|
||||
if opt.debug:
|
||||
Msg("tx_in: " + repr(tx_in))
|
||||
Msg("tx_out: " + repr(tx_out))
|
||||
dmsg("tx_in: %s\ntx_out: %s" % (repr(tx_in),repr(tx_out)))
|
||||
|
||||
if opt.comment_file:
|
||||
if keypress_confirm("Edit comment?",False):
|
||||
|
|
|
|||
|
|
@ -68,12 +68,12 @@ if keypress_confirm("Edit transaction comment?"):
|
|||
write_to_file(outfile,data,w,False,True,True)
|
||||
|
||||
warn = "Once this transaction is sent, there's no taking it back!"
|
||||
what = "broadcast this transaction to the network"
|
||||
action = "broadcast this transaction to the network"
|
||||
expect = "YES, I REALLY WANT TO DO THIS"
|
||||
|
||||
if opt.quiet: warn,expect = "","YES"
|
||||
|
||||
confirm_or_exit(warn, what, expect)
|
||||
confirm_or_exit(warn, action, expect)
|
||||
|
||||
msg("Sending transaction")
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ import sys
|
|||
import mmgen.globalvars as g
|
||||
import mmgen.opt as opt
|
||||
from mmgen.tx import *
|
||||
from mmgen.util import do_license_msg
|
||||
from mmgen.util import do_license_msg,dmsg
|
||||
|
||||
pnm = g.proj_name
|
||||
pnl = pnm.lower()
|
||||
|
|
@ -150,7 +150,7 @@ def sign_transaction(c,tx_hex,tx_num_str,sig_data,keys=None):
|
|||
|
||||
if keys:
|
||||
qmsg("Passing %s key%s to bitcoind" % (len(keys),suf(keys,"k")))
|
||||
if opt.debug: Msg("Keys:\n %s" % "\n ".join(keys))
|
||||
dmsg("Keys:\n %s" % "\n ".join(keys))
|
||||
|
||||
msg_r("Signing transaction{}...".format(tx_num_str))
|
||||
from mmgen.rpc import exceptions
|
||||
|
|
@ -192,11 +192,11 @@ def sign_tx_with_bitcoind_wallet(c,tx_hex,tx_num_str,sig_data,keys):
|
|||
return sig_tx
|
||||
|
||||
|
||||
def check_maps_from_seeds(maplist,what,infiles,saved_seeds,return_keys=False):
|
||||
def check_maps_from_seeds(maplist,desc,infiles,saved_seeds,return_keys=False):
|
||||
|
||||
if not maplist: return []
|
||||
qmsg("Checking {pnm} -> BTC address mappings for {w}s (from seed(s))".format(
|
||||
pnm=pnm,w=what))
|
||||
pnm=pnm,w=desc))
|
||||
d = get_keys_for_mmgen_addrs(maplist.keys(),infiles,saved_seeds)
|
||||
# 0=mmaddr 1=addr 2=wif
|
||||
m = dict([(e[0],e[1]) for e in d])
|
||||
|
|
@ -253,9 +253,9 @@ def parse_keylist(from_file):
|
|||
|
||||
|
||||
# Check inputs and outputs maps against key-address file, deleting entries:
|
||||
def check_maps_from_kafile(imap,what,kadata,return_keys=False):
|
||||
def check_maps_from_kafile(imap,desc,kadata,return_keys=False):
|
||||
if not kadata: return []
|
||||
qmsg("Checking {pnm} -> BTC address mappings for {w}s (from key-address file)".format(pnm=pnm,w=what))
|
||||
qmsg("Checking {pnm} -> BTC address mappings for {w}s (from key-address file)".format(pnm=pnm,w=desc))
|
||||
ret = []
|
||||
for k in imap.keys():
|
||||
if k in kadata.keys():
|
||||
|
|
@ -266,9 +266,9 @@ def check_maps_from_kafile(imap,what,kadata,return_keys=False):
|
|||
kl,il = "key-address file:","tx file:"
|
||||
msg(wmsg['mm2btc_mapping_error']%(kl,k,kadata[k][0],il,k,imap[k]))
|
||||
sys.exit(2)
|
||||
if ret: vmsg("Removed %s address%s from %ss map" % (len(ret),suf(ret,"a"),what))
|
||||
if ret: vmsg("Removed %s address%s from %ss map" % (len(ret),suf(ret,"a"),desc))
|
||||
if return_keys:
|
||||
vmsg("Added %s wif key%s from %ss map" % (len(ret),suf(ret,"k"),what))
|
||||
vmsg("Added %s wif key%s from %ss map" % (len(ret),suf(ret,"k"),desc))
|
||||
return ret
|
||||
|
||||
|
||||
|
|
@ -288,7 +288,7 @@ infiles = opt.opts.init(opts_data,add_opts=["b16"])
|
|||
for l in (
|
||||
('tx_id', 'info'),
|
||||
('tx_id', 'terse_info'),
|
||||
): opt.opts.warn_incompatible_opts(l)
|
||||
): opt.opts.die_on_incompatible_opts(l)
|
||||
|
||||
if opt.from_incog_hex or opt.from_incog_hidden: opt.from_incog = True
|
||||
|
||||
|
|
|
|||
|
|
@ -95,8 +95,7 @@ def export_to_hidden_incog(incog_enc):
|
|||
outfile,offset = opt.export_incog_hidden.split(",") #Already sanity-checked
|
||||
if opt.outdir: outfile = make_full_path(opt.outdir,outfile)
|
||||
|
||||
if opt.debug:
|
||||
Msg("Incog data len %s, offset %s" % (len(incog_enc),offset))
|
||||
dmsg("Incog data len %s, offset %s" % (len(incog_enc),offset))
|
||||
check_data_fits_file_at_offset(outfile,int(offset),len(incog_enc),"write")
|
||||
|
||||
if not opt.quiet: confirm_or_exit("","alter file '%s'" % outfile)
|
||||
|
|
@ -162,7 +161,7 @@ if opt.export_mnemonic:
|
|||
|
||||
elif opt.export_seed:
|
||||
from mmgen.bitcoin import b58encode_pad
|
||||
data = split_into_columns(4,b58encode_pad(seed))
|
||||
data = split_into_cols(4,b58encode_pad(seed))
|
||||
chk = make_chksum_6(b58encode_pad(seed))
|
||||
fn = "%s.%s" % (make_chksum_8(seed).upper(), g.seed_ext)
|
||||
write_to_file_or_stdout(fn, "%s %s\n" % (chk,data), "seed data")
|
||||
|
|
|
|||
89
mmgen/main_walletconv.py
Executable file
89
mmgen/main_walletconv.py
Executable file
|
|
@ -0,0 +1,89 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""
|
||||
mmgen-walletconv: Convert an MMGen deterministic wallet from one format
|
||||
to another
|
||||
"""
|
||||
|
||||
import sys
|
||||
import mmgen.globalvars as g
|
||||
import mmgen.opt as opt
|
||||
from mmgen.util import die,msg,green,do_license_msg,check_infile
|
||||
from mmgen.seed import SeedSource
|
||||
|
||||
opts_data = {
|
||||
'sets_disabled': (
|
||||
('hidden_incog_input_params', bool, 'in_fmt', 'hi'),
|
||||
('hidden_incog_output_params', bool, 'out_fmt', 'hi')
|
||||
),
|
||||
'desc': "Convert an {pnm} wallet from one format to another".format(
|
||||
pnm=g.proj_name),
|
||||
'usage':"[opts] [infile]",
|
||||
'options': """
|
||||
-h, --help Print this help message.
|
||||
-d, --outdir= d Output files to directory 'd' instead of working dir.
|
||||
-i, --in-fmt= f Convert from wallet format 'f' (see FMT CODES below).
|
||||
-o, --out-fmt= f Convert to wallet format 'f' (see FMT CODES below).
|
||||
-H, --hidden-incog-input-params=f,o Use filename 'f' and offset 'o' (comma
|
||||
separated) for hidden incognito input.
|
||||
-J, --hidden-incog-output-params=f,o Same above, but for output. If file
|
||||
'f' doesn't exist, it will be created and filled with
|
||||
random data.
|
||||
-O, --old-incog-fmt Specify old-format incognito input.
|
||||
-k, --keep-passphrase Reuse input wallet passphrase for output wallet.
|
||||
-K, --keep-hash-preset Reuse input wallet hash preset for output wallet.
|
||||
-l, --seed-len= l Specify wallet seed length of 'l' bits. This option
|
||||
is required only for brainwallet and incognito inputs
|
||||
with non-standard (< {g.seed_len}-bit) seed lengths.
|
||||
-p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
|
||||
for password hashing (default: '{g.hash_preset}').
|
||||
-q, --quiet Produce quieter output; suppress some warnings.
|
||||
-r, --usr-randchars=n Get 'n' characters of additional randomness from user
|
||||
(min={g.min_urandchars}, max={g.max_urandchars}, default={g.usr_randchars}).
|
||||
-S, --stdout Write wallet data to stdout instead of file.
|
||||
-v, --verbose Produce more verbose output.
|
||||
|
||||
FMT CODES:
|
||||
{f}
|
||||
""".format(g=g,f="\n ".join(SeedSource.format_fmt_codes().split("\n")))
|
||||
}
|
||||
|
||||
cmd_args = opt.opts.init(opts_data)
|
||||
|
||||
if len(cmd_args) == 0 \
|
||||
and not opt.hidden_incog_input_params \
|
||||
and not opt.in_fmt:
|
||||
die(1,"An input file or input format must be specified")
|
||||
|
||||
if len(cmd_args) > 1 or (len(cmd_args) == 1 and opt.hidden_incog_input_params):
|
||||
die(1,"Only one input file may be specified")
|
||||
|
||||
if len(cmd_args) == 1:
|
||||
check_infile(cmd_args[0])
|
||||
|
||||
do_license_msg()
|
||||
|
||||
msg(green("Processing input wallet"))
|
||||
|
||||
ss_in = SeedSource(*cmd_args)
|
||||
|
||||
msg(green("Processing output wallet"))
|
||||
|
||||
ss_out = SeedSource(ss=ss_in)
|
||||
ss_out.write_to_file()
|
||||
14
mmgen/obj.py
14
mmgen/obj.py
|
|
@ -20,7 +20,7 @@
|
|||
obj.py: The MMGenObject class and methods
|
||||
"""
|
||||
import mmgen.globalvars as g
|
||||
from mmgen.util import msgrepr_exit,msgrepr
|
||||
from mmgen.util import mdie,mmsg
|
||||
|
||||
lvl = 0
|
||||
|
||||
|
|
@ -72,18 +72,18 @@ class MMGenObject(object):
|
|||
col_w = max(len(k) for k in keys)
|
||||
fs = "{}%-{}s: %s".format(indent,col_w)
|
||||
|
||||
methods = [k for k in keys if repr(getattr(self,k))[:14] == '<bound method ']
|
||||
methods = [k for k in keys if repr(getattr(self,k))[:14] == '<bound method ']
|
||||
|
||||
def f(k): return repr(getattr(self,k))[:14] == '<bound method '
|
||||
methods = filter(f,keys)
|
||||
def f(k): return repr(getattr(self,k))[:7] == '<mmgen.'
|
||||
objects = filter(f,keys)
|
||||
def f(k): return repr(getattr(self,k))[:14] == '<bound method '
|
||||
methods = filter(f,keys)
|
||||
def f(k): return repr(getattr(self,k))[:7] == '<mmgen.'
|
||||
objects = filter(f,keys)
|
||||
other = list(set(keys) - set(methods) - set(objects))
|
||||
|
||||
for k in sorted(methods) + sorted(other) + sorted(objects):
|
||||
val = getattr(self,k)
|
||||
if str(type(val))[:13] == "<class 'mmgen": # recurse into sub-objects
|
||||
out.append("\n%s%s (%s):" % (indent,k,repr(type(val))))
|
||||
out.append("\n%s%s (%s):" % (indent,k,type(val)))
|
||||
lvl += 1
|
||||
out.append(str(getattr(self,k))+"\n")
|
||||
lvl -= 1
|
||||
|
|
|
|||
145
mmgen/opts.py
145
mmgen/opts.py
|
|
@ -24,7 +24,7 @@ import sys
|
|||
import mmgen.globalvars as g
|
||||
import mmgen.share.Opts
|
||||
import opt
|
||||
from mmgen.util import msg,msgrepr_exit,msgrepr,Msg,fmt_type
|
||||
from mmgen.util import msg,msg_r,mdie,mmsg,Msg,die
|
||||
|
||||
def usage():
|
||||
Msg("USAGE: %s %s" % (g.prog_name, usage_txt))
|
||||
|
|
@ -32,17 +32,15 @@ def usage():
|
|||
|
||||
def print_version_info():
|
||||
Msg("""
|
||||
{progname_uc} version {g.version}
|
||||
{pgnm_uc} version {g.version}
|
||||
Part of the {pnm} suite, a Bitcoin cold-storage solution for the com-
|
||||
mand line. Copyright (C) {g.Cdates} {g.author} {g.email}
|
||||
""".format(pnm=g.proj_name,g=g,progname_uc=g.prog_name.upper()).strip())
|
||||
""".format(pnm=g.proj_name, g=g, pgnm_uc=g.prog_name.upper()).strip())
|
||||
|
||||
def warn_incompatible_opts(incompat_list):
|
||||
def die_on_incompatible_opts(incompat_list):
|
||||
bad = [k for k in opt.__dict__ if opt.__dict__[k] and k in incompat_list]
|
||||
if len(bad) > 1:
|
||||
msg("Mutually exclusive options: %s" % " ".join(
|
||||
["--"+b.replace("_","-") for b in bad]))
|
||||
sys.exit(1)
|
||||
die(1,"Conflicting options: %s" % ", ".join([fmt_opt(b) for b in bad]))
|
||||
|
||||
def _typeconvert_from_dfl(key):
|
||||
|
||||
|
|
@ -51,7 +49,6 @@ def _typeconvert_from_dfl(key):
|
|||
gval = g.__dict__[key]
|
||||
uval = opt.__dict__[key]
|
||||
gtype = type(gval)
|
||||
utype = type(uval)
|
||||
|
||||
try:
|
||||
opt.__dict__[key] = gtype(opt.__dict__[key])
|
||||
|
|
@ -62,16 +59,18 @@ def _typeconvert_from_dfl(key):
|
|||
'float': 'a float',
|
||||
'bool': 'a boolean value',
|
||||
}
|
||||
m = [d[k] for k in d if __builtins__[k] == gtype]
|
||||
fs = "'%s': invalid parameter for '--%s' option (not %s)"
|
||||
msg(fs % (opt.__dict__[key],opt.replace("_","-"),m))
|
||||
sys.exit(1)
|
||||
die(1, "'%s': invalid parameter for '--%s' option (not %s)" % (
|
||||
opt.__dict__[key],
|
||||
key.replace("_","-"),
|
||||
d[gtype.__name__]
|
||||
))
|
||||
|
||||
if g.debug:
|
||||
Msg("Opt overriden by user:\n %-18s: %s" % (
|
||||
key, ("%s -> %s" % (gval,uval))
|
||||
))
|
||||
|
||||
def fmt_opt(o): return "--" + o.replace("_","-")
|
||||
|
||||
def _show_hash_presets():
|
||||
fs = " {:<7} {:<6} {:<3} {}"
|
||||
|
|
@ -116,21 +115,25 @@ def init(opts_data,add_opts=[]):
|
|||
for o in [s.rstrip("=") for s in long_opts] + g.required_opts + add_opts:
|
||||
opt.__dict__[o] = uopts[o] if o in uopts else None
|
||||
|
||||
# check user-set opts without modifying them
|
||||
if not check_opts(uopts): sys.exit(1)
|
||||
|
||||
# A special case - do this here, before opt gets set from g.dfl_vars
|
||||
if opt.usr_randchars: g.use_urandchars = True
|
||||
|
||||
# If user opt is set, convert its type based on value in mmgen.globalvars
|
||||
# If unset, set it to default value in mmgen.globalvars (g):
|
||||
opt.__dict__['set_by_user'] = []
|
||||
for k in g.dfl_vars:
|
||||
if k in opt.__dict__ and opt.__dict__[k] != None:
|
||||
_typeconvert_from_dfl(k)
|
||||
else: opt.__dict__[k] = g.__dict__[k]
|
||||
opt.set_by_user.append(k)
|
||||
else:
|
||||
opt.__dict__[k] = g.__dict__[k]
|
||||
|
||||
# Check user-set opts without modifying them
|
||||
if not check_opts(uopts): sys.exit(1)
|
||||
|
||||
if opt.show_hash_presets:
|
||||
_show_hash_presets(); sys.exit(0)
|
||||
|
||||
if opt.debug: opt.verbose = True
|
||||
|
||||
if g.debug:
|
||||
|
|
@ -138,7 +141,7 @@ def init(opts_data,add_opts=[]):
|
|||
for k in opt.__dict__:
|
||||
v = opt.__dict__[k]
|
||||
if v != None and k != "opts":
|
||||
Msg(" %-18s: %-6s [%s]" % (k,v,fmt_type(v)))
|
||||
Msg(" %-18s: %-6s [%s]" % (k,v,type(v).__name__))
|
||||
Msg("### END OPTS.PY ###\n")
|
||||
|
||||
for l in (
|
||||
|
|
@ -146,7 +149,7 @@ def init(opts_data,add_opts=[]):
|
|||
('export_incog','export_incog_hex','export_incog_hidden','export_mnemonic',
|
||||
'export_seed'),
|
||||
('quiet','verbose')
|
||||
): warn_incompatible_opts(l)
|
||||
): die_on_incompatible_opts(l)
|
||||
|
||||
return args
|
||||
|
||||
|
|
@ -160,50 +163,61 @@ def show_all_opts():
|
|||
|
||||
def check_opts(usr_opts): # Returns false if any check fails
|
||||
|
||||
def opt_splits(val,sep,n,what):
|
||||
def opt_splits(val,sep,n,desc):
|
||||
sepword = "comma" if sep == "," else (
|
||||
"colon" if sep == ":" else ("'"+sep+"'"))
|
||||
try: l = val.split(sep)
|
||||
except:
|
||||
msg("'%s': invalid %s (not %s-separated list)" % (val,what,sepword))
|
||||
msg("'%s': invalid %s (not %s-separated list)" % (val,desc,sepword))
|
||||
return False
|
||||
|
||||
if len(l) == n: return True
|
||||
else:
|
||||
msg("'%s': invalid %s (%s %s-separated items required)" %
|
||||
(val,what,n,sepword))
|
||||
(val,desc,n,sepword))
|
||||
return False
|
||||
|
||||
def opt_compares(val,op,target,what):
|
||||
def opt_compares(val,op,target,desc):
|
||||
if not eval("%s %s %s" % (val, op, target)):
|
||||
msg("%s: invalid %s (not %s %s)" % (val,what,op,target))
|
||||
msg("%s: invalid %s (not %s %s)" % (val,desc,op,target))
|
||||
return False
|
||||
return True
|
||||
|
||||
def opt_is_int(val,what):
|
||||
def opt_is_int(val,desc):
|
||||
try: int(val)
|
||||
except:
|
||||
msg("'%s': invalid %s (not an integer)" % (val,what))
|
||||
msg("'%s': invalid %s (not an integer)" % (val,desc))
|
||||
return False
|
||||
return True
|
||||
|
||||
def opt_is_in_list(val,lst,what):
|
||||
def opt_is_in_list(val,lst,desc):
|
||||
if val not in lst:
|
||||
q,sep = ("'","','") if type(lst[0]) == str else ("",",")
|
||||
msg("{q}{}{q}: invalid {}\nValid options: {q}{}{q}".format(
|
||||
val,what,sep.join([str(i) for i in sorted(lst)]),q=q))
|
||||
msg("{q}{v}{q}: invalid {w}\nValid choices: {q}{o}{q}".format(
|
||||
v=val,w=desc,q=q,
|
||||
o=sep.join([str(i) for i in sorted(lst)])
|
||||
))
|
||||
return False
|
||||
return True
|
||||
|
||||
def opt_unrecognized(key,val,desc):
|
||||
msg("'%s': unrecognized %s for option '%s'"
|
||||
% (val,desc,fmt_opt(key)))
|
||||
return False
|
||||
|
||||
def opt_display(key,val='',beg="For selected",end=":\n"):
|
||||
s = "%s=%s" % (fmt_opt(key),val) if val else fmt_opt(key)
|
||||
msg_r("%s option '%s'%s" % (beg,s,end))
|
||||
|
||||
global opt
|
||||
for key,val in [(k,getattr(opt,k)) for k in usr_opts]:
|
||||
|
||||
what = "parameter for '--%s' option" % key.replace("_","-")
|
||||
desc = "parameter for '%s' option" % fmt_opt(key)
|
||||
|
||||
# Check for file existence and readability
|
||||
from mmgen.util import check_infile
|
||||
if key in ('keys_from_file','mmgen_keys_from_file',
|
||||
'passwd_file','keysforaddrs','comment_file'):
|
||||
from mmgen.util import check_infile
|
||||
check_infile(val) # exits on error
|
||||
continue
|
||||
|
||||
|
|
@ -220,40 +234,83 @@ def check_opts(usr_opts): # Returns false if any check fails
|
|||
w = "character in label"
|
||||
for ch in list(val):
|
||||
if not opt_is_in_list(ch,g.wallet_label_symbols,w): return False
|
||||
# NEW
|
||||
elif key in ('in_fmt','out_fmt'):
|
||||
from mmgen.seed import SeedSource,IncogWallet,Brainwallet,IncogWalletHidden
|
||||
sstype = SeedSource.fmt_code_to_sstype(val)
|
||||
if not sstype:
|
||||
return opt_unrecognized(key,val,"format code")
|
||||
if key == 'out_fmt':
|
||||
p = 'hidden_incog_output_params'
|
||||
if sstype == IncogWalletHidden and not getattr(opt,p):
|
||||
die(1,"Hidden incog format output requested. You must supply"
|
||||
+ " a file and offset with the '%s' option" % fmt_opt(p))
|
||||
if issubclass(sstype,IncogWallet) and opt.old_incog_fmt:
|
||||
opt_display(key,val,beg="Selected",end=" ")
|
||||
opt_display('old_incog_fmt',beg="conflicts with",end=":\n")
|
||||
die(1,"Export to old incog wallet format unsupported")
|
||||
elif issubclass(sstype,Brainwallet):
|
||||
die(1,"Output to brainwallet format unsupported")
|
||||
elif key in ('hidden_incog_input_params','hidden_incog_output_params'):
|
||||
if key == 'hidden_incog_input_params':
|
||||
check_infile(val.split(",")[0])
|
||||
key2 = 'in_fmt'
|
||||
else:
|
||||
key2 = 'out_fmt'
|
||||
if hasattr(opt,key2):
|
||||
val2 = getattr(opt,key2)
|
||||
from mmgen.seed import IncogWalletHidden
|
||||
if val2 and val2 not in IncogWalletHidden.fmt_codes:
|
||||
die(1,
|
||||
"Option conflict:\n %s, with\n %s=%s" % (
|
||||
fmt_opt(key),fmt_opt(key2),val2
|
||||
))
|
||||
|
||||
# begin OLD, deprecated
|
||||
elif key == 'hidden_incog_params':
|
||||
from mmgen.util import check_outfile
|
||||
if not opt_splits(val,",",2,desc): return False
|
||||
outfile,offset = val.split(",")
|
||||
check_outfile(outfile)
|
||||
w = "offset " + desc
|
||||
if not opt_is_int(offset,w): return False
|
||||
if not opt_compares(offset,">=",0,desc): return False
|
||||
elif key == 'export_incog_hidden' or key == 'from_incog_hidden':
|
||||
if key == 'from_incog_hidden':
|
||||
if not opt_splits(val,",",3,what): return False
|
||||
if not opt_splits(val,",",3,desc): return False
|
||||
infile,offset,seed_len = val.split(",")
|
||||
from mmgen.util import check_infile
|
||||
check_infile(infile)
|
||||
w = "seed length " + what
|
||||
w = "seed length " + desc
|
||||
if not opt_is_int(seed_len,w): return False
|
||||
if not opt_is_in_list(int(seed_len),g.seed_lens,w): return False
|
||||
else:
|
||||
from mmgen.util import check_outfile
|
||||
if not opt_splits(val,",",2,what): return False
|
||||
if not opt_splits(val,",",2,desc): return False
|
||||
outfile,offset = val.split(",")
|
||||
check_outfile(outfile)
|
||||
w = "offset " + what
|
||||
w = "offset " + desc
|
||||
if not opt_is_int(offset,w): return False
|
||||
if not opt_compares(offset,">=",0,what): return False
|
||||
if not opt_compares(offset,">=",0,desc): return False
|
||||
elif key == 'from_brain':
|
||||
if not opt_splits(val,",",2,what): return False
|
||||
if not opt_splits(val,",",2,desc): return False
|
||||
l,p = val.split(",")
|
||||
w = "seed length " + what
|
||||
w = "seed length " + desc
|
||||
if not opt_is_int(l,w): return False
|
||||
if not opt_is_in_list(int(l),g.seed_lens,w): return False
|
||||
w = "hash preset " + what
|
||||
w = "hash preset " + desc
|
||||
if not opt_is_in_list(p,g.hash_presets.keys(),w): return False
|
||||
# end OLD
|
||||
elif key == 'seed_len':
|
||||
if not opt_is_int(val,what): return False
|
||||
if not opt_is_in_list(int(val),g.seed_lens,what): return False
|
||||
if not opt_is_int(val,desc): return False
|
||||
if not opt_is_in_list(int(val),g.seed_lens,desc): return False
|
||||
elif key == 'hash_preset':
|
||||
if not opt_is_in_list(val,g.hash_presets.keys(),what): return False
|
||||
if not opt_is_in_list(val,g.hash_presets.keys(),desc): return False
|
||||
elif key == 'usr_randchars':
|
||||
if not opt_is_int(val,what): return False
|
||||
if not opt_compares(val,">=",g.min_urandchars,what): return False
|
||||
if not opt_compares(val,"<=",g.max_urandchars,what): return False
|
||||
if val == 0: continue
|
||||
if not opt_is_int(val,desc): return False
|
||||
if not opt_compares(val,">=",g.min_urandchars,desc): return False
|
||||
if not opt_compares(val,"<=",g.max_urandchars,desc): return False
|
||||
else:
|
||||
if g.debug: Msg("check_opts(): No test for opt '%s'" % key)
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ bitcoin-python - Easy-to-use Bitcoin API client
|
|||
|
||||
|
||||
def connect_to_local(filename=None):
|
||||
"""
|
||||
"""
|
||||
Connect to default bitcoin instance owned by this user, on this machine.
|
||||
|
||||
Returns a :class:`~mmgen.rpc.connection.BitcoinConnection` object.
|
||||
|
|
@ -31,24 +31,23 @@ def connect_to_local(filename=None):
|
|||
Arguments:
|
||||
|
||||
- `filename`: Path to a configuration file in a non-standard location (optional)
|
||||
"""
|
||||
from mmgen.rpc.connection import BitcoinConnection
|
||||
from mmgen.rpc.config import read_default_config
|
||||
"""
|
||||
from mmgen.rpc.connection import BitcoinConnection
|
||||
from mmgen.rpc.config import read_default_config
|
||||
|
||||
cfg = read_default_config(filename)
|
||||
port = int(cfg.get('rpcport', '18332' if cfg.get('testnet') else '8332'))
|
||||
rcpuser = cfg.get('rpcuser', '')
|
||||
cfg = read_default_config(filename)
|
||||
port = int(cfg.get('rpcport', '18332' if cfg.get('testnet') else '8332'))
|
||||
rcpuser = cfg.get('rpcuser', '')
|
||||
|
||||
return BitcoinConnection(rcpuser, cfg['rpcpassword'], 'localhost', port)
|
||||
return BitcoinConnection(rcpuser, cfg['rpcpassword'], 'localhost', port)
|
||||
|
||||
|
||||
def connect_to_remote(user, password, host='localhost', port=8332,
|
||||
use_https=False):
|
||||
"""
|
||||
def connect_to_remote(user,password,host='localhost',port=8332,use_https=False):
|
||||
"""
|
||||
Connect to remote or alternative local bitcoin client instance.
|
||||
|
||||
Returns a :class:`~mmgen.rpc.connection.BitcoinConnection` object.
|
||||
"""
|
||||
from mmgen.rpc.connection import BitcoinConnection
|
||||
"""
|
||||
from mmgen.rpc.connection import BitcoinConnection
|
||||
|
||||
return BitcoinConnection(user, password, host, port, use_https)
|
||||
return BitcoinConnection(user, password, host, port, use_https)
|
||||
|
|
|
|||
|
|
@ -23,53 +23,53 @@ Utilities for reading bitcoin configuration files.
|
|||
|
||||
|
||||
def read_config_file(filename):
|
||||
"""
|
||||
"""
|
||||
Read a simple ``'='``-delimited config file.
|
||||
Raises :const:`IOError` if unable to open file, or :const:`ValueError`
|
||||
if an parse error occurs.
|
||||
"""
|
||||
f = open(filename)
|
||||
try:
|
||||
cfg = {}
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
try:
|
||||
(key, value) = line.split('=', 1)
|
||||
cfg[key] = value
|
||||
except ValueError:
|
||||
pass # Happens when line has no '=', ignore
|
||||
finally:
|
||||
f.close()
|
||||
return cfg
|
||||
"""
|
||||
f = open(filename)
|
||||
try:
|
||||
cfg = {}
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
try:
|
||||
(key, value) = line.split('=', 1)
|
||||
cfg[key] = value
|
||||
except ValueError:
|
||||
pass # Happens when line has no '=', ignore
|
||||
finally:
|
||||
f.close()
|
||||
return cfg
|
||||
|
||||
|
||||
def read_default_config(filename=None):
|
||||
"""
|
||||
"""
|
||||
Read bitcoin default configuration from the current user's home directory.
|
||||
|
||||
Arguments:
|
||||
|
||||
- `filename`: Path to a configuration file in a non-standard location (optional)
|
||||
"""
|
||||
if filename is None:
|
||||
import os
|
||||
import platform
|
||||
home = os.getenv("HOME")
|
||||
if not home:
|
||||
raise IOError("Home directory not defined, don't know where to look for config file")
|
||||
"""
|
||||
if filename is None:
|
||||
import os
|
||||
import platform
|
||||
home = os.getenv("HOME")
|
||||
if not home:
|
||||
raise IOError("Home directory not defined, don't know where to look for config file")
|
||||
|
||||
if platform.system() == "Darwin":
|
||||
location = 'Library/Application Support/Bitcoin/bitcoin.conf'
|
||||
else:
|
||||
location = '.bitcoin/bitcoin.conf'
|
||||
filename = os.path.join(home, location)
|
||||
if platform.system() == "Darwin":
|
||||
location = 'Library/Application Support/Bitcoin/bitcoin.conf'
|
||||
else:
|
||||
location = '.bitcoin/bitcoin.conf'
|
||||
filename = os.path.join(home, location)
|
||||
|
||||
elif filename.startswith("~"):
|
||||
import os
|
||||
filename = os.path.expanduser(filename)
|
||||
elif filename.startswith("~"):
|
||||
import os
|
||||
filename = os.path.expanduser(filename)
|
||||
|
||||
try:
|
||||
return read_config_file(filename)
|
||||
except (IOError, ValueError):
|
||||
pass # Cannot read config file, ignore
|
||||
try:
|
||||
return read_config_file(filename)
|
||||
except (IOError, ValueError):
|
||||
pass # Cannot read config file, ignore
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue