MMGen version 0.8.3
New features/improvements: * New native Bitcoin RPC library. * Support for cookie-based RPC authentication (new in Bitcoin Core v0.12.0). * Batch mode available when listing and importing addresses. * mmgen-tool listaddresses: 'addrs' argument allows you to specify an address or range of addresses. NOTE: if MMGen is already installed on your system, you must remove your existing installation by hand before installing this new version. On Linux, this means deleting everything under the directory '/usr/local/lib/python2.7/dist-packages/mmgen/'. Also, if you did a 'git pull' instead of a fresh clone, you must delete the 'build' directory in the repository root before installing. The 'mmgen-pywallet' utility has been removed. It's no longer needed, as the 'bitcoin-cli dumpwallet' command (available since Core v0.9.0) provides equivalent functionality. The Windows port isn't being actively maintained at the moment. Use at your own risk, and report any problems on the Bitcointalk forum.
This commit is contained in:
parent
5b80bd2cd5
commit
956eeab186
55 changed files with 2471 additions and 5509 deletions
|
|
@ -12,17 +12,16 @@ Install the pexpect Python module:
|
|||
|
||||
$ sudo pip install pexpect
|
||||
|
||||
Note: pexpect v4.0.1 (the latest version as of this writing) is
|
||||
BROKEN and will cause errors when running the test suite!
|
||||
If this is the version you just installed on your system (examine the
|
||||
output of 'pip freeze' to find out), then you must downgrade. Note
|
||||
that newer versions may be broken as well. Version 3.1 is known to work
|
||||
and can be found [here][03]. First, uninstall the broken pexpect:
|
||||
>> Note: pexpect v4.0.1 (the latest version as of this writing) is BROKEN and
|
||||
>> will cause errors when running the test suite! If this is the version you
|
||||
>> just installed on your system (examine the output of 'pip freeze' to find
|
||||
>> out), then you must downgrade. Note that newer versions may be broken as
|
||||
>> well. Version 3.1 is known to work. If this is the version on your system,
|
||||
>> then you may skip the next step. Otherwise, download the [v3.1 tarball][03],
|
||||
>> unpack it, cd to the archive root and run:
|
||||
|
||||
$ sudo pip uninstall pexpect
|
||||
|
||||
Then download and unpack the v3.1 tarball, cd to the archive root and
|
||||
run 'sudo python setup.py install' to install it.
|
||||
$ sudo pip uninstall pexpect
|
||||
$ sudo python setup.py install
|
||||
|
||||
Install MMGen:
|
||||
|
||||
|
|
|
|||
|
|
@ -229,55 +229,66 @@ confirmations, your transaction will be saved:
|
|||
Note that the transaction has a unique ID, and the non-change spend amount of
|
||||
6.6 BTC is included in the filename.
|
||||
|
||||
#### <a name=06>Create a keylist file (online computer):</a>
|
||||
|
||||
To sign your transaction, you'll need the Bitcoin private key corresponding to
|
||||
its input address, '1F93Znz....'
|
||||
|
||||
If the key in question is in a bitcoind wallet ('wallet.dat'), you'll want to
|
||||
extract the key (along with all the other keys in the wallet) to a keylist
|
||||
file. This is done using the 'bitcoin-cli dumpwallet' command with bitcoind
|
||||
running.
|
||||
|
||||
$ bitcoin-cli dumpwallet my_secret.keys
|
||||
|
||||
This will write the keylist file 'my_secret.keys' (or whatever filename you've
|
||||
chosen) to your home directory (or maybe to your Bitcoin data directory, results
|
||||
may vary). If you want it written to another location, provide an absolute
|
||||
path.
|
||||
|
||||
Note that the keylist file lists your private keys in *unencrypted* form, even
|
||||
if your 'wallet.dat' was encrypted. Therefore, it should be backed up to a safe
|
||||
location—to a USB stick, say, or to your offline computer. After you've backed
|
||||
it up, securely delete all copies of it on your online computer.
|
||||
|
||||
You'll use this keylist file to sign all transactions that spend from addresses
|
||||
in your bitcoind wallet.
|
||||
|
||||
If the key/address pair in question came from another source, you may create
|
||||
your own file 'my_secret.keys' (or whatever) in a plain text editor and just
|
||||
list the key in this file. In the case of multiple keys, just list them all,
|
||||
one key per line. In our example, the file will have one line containing a
|
||||
single private key corresponding to the address '1F93Znz....'
|
||||
|
||||
#### <a name=06>Sign a transaction (offline computer):</a>
|
||||
|
||||
Now copy the raw transaction you've just created to a USB stick and transfer it
|
||||
to your offline computer for signing. For this you'll need the key corresponding
|
||||
to the transaction's input address, 1F93Znz.... If the key in question is in a
|
||||
bitcoind 'wallet.dat', copy 'wallet.dat' to your offline machine as well and use
|
||||
the included command 'mmgen-pywallet' (a modified version of the well-known
|
||||
pywallet utility) to extract the required key from it.
|
||||
Now transfer the the raw transaction file and just-created keylist file to your
|
||||
offline computer and run:
|
||||
|
||||
$ mmgen-pywallet -k wallet.dat
|
||||
...
|
||||
Private keys written to file 'wd_EDBC983A[102].keys'
|
||||
|
||||
You've in fact extracted a list of all of the wallet's 102 keys here, but that's
|
||||
not a problem, since the unused keys will be ignored (if you wish, you can
|
||||
extract only the one key you need using the '--keys-for-addrs' option). Now go
|
||||
ahead and sign the transaction using this key list:
|
||||
|
||||
$ mmgen-txsign -k wd_EDBC983A[102].keys tx_FEDCBA[6.6].raw
|
||||
$ mmgen-txsign -k my_secret.keys tx_FEDCBA[6.6].raw
|
||||
...
|
||||
Signed transaction written to file 'tx_FEDCBA[6.6].sig'
|
||||
|
||||
Note that 'mmgen-pywallet's output is just a flat list of keys. So if you have
|
||||
several Bitcoin wallets with balances, you can just concatenate these lists into
|
||||
a single file which you can use to sign all future transactions with
|
||||
'wallet.dat' inputs:
|
||||
The signed transaction is written to a new file whose name differs from the raw
|
||||
transaction file only by its '.sig' extension.
|
||||
|
||||
$ mmgen-pywallet -k wallet1.dat
|
||||
$ mmgen-pywallet -k wallet2.dat
|
||||
$ mmgen-pywallet -k wallet3.dat
|
||||
$ cat wd_*.keys > all_keys
|
||||
|
||||
Once you've migrated your funds to MMGen, such key files will no longer be
|
||||
NOTE: once you've migrated your funds to MMGen, the keylist file will no longer be
|
||||
needed. Instead, you'll sign transactions by listing an MMGen seed source
|
||||
(wallet, mnemonic or seed file) on the command line after the transaction,
|
||||
and the required keys will be generated on the fly, as in this example:
|
||||
(wallet, mnemonic or seed file) on the command line after the transaction, and
|
||||
the required keys will be generated on the fly, as in the following example:
|
||||
|
||||
$ mmgen-txsign tx_ABCDE[1.2345].raw 1234567A-BCDEF123[256,3].mmdat
|
||||
$ mmgen-txsign tx_ABCDE[1].raw my_mmgen_wallet.mmdat
|
||||
|
||||
Transactions may contain a mixture of MMGen and non-MMGen inputs, as well as
|
||||
inputs with more than one MMGen Seed ID. Just list a seed source for each
|
||||
NOTE: transactions may contain a mixture of MMGen and non-MMGen inputs, as well
|
||||
as inputs with more than one MMGen Seed ID. Just list a seed source for each
|
||||
MMGen input on the command line after the transaction, as in this example:
|
||||
|
||||
$ mmgen-txsign -k key_list my_tx.raw a.mmdat b.mmwords c.mmseed
|
||||
$ mmgen-txsign -k my_secret.keys my_tx.raw a.mmdat b.mmwords c.mmseed
|
||||
|
||||
#### <a name=07>Send a transaction (online computer):</a>
|
||||
|
||||
Now you're ready for the final step: broadcasting the transaction to the
|
||||
network. Copy just-created signed transaction file to your online computer,
|
||||
network. Copy the just-created signed transaction file to your online computer,
|
||||
start bitcoind and issue the command:
|
||||
|
||||
$ mmgen-txsend tx_FEDCBA[6.6].sig
|
||||
|
|
@ -301,7 +312,7 @@ Your total MMGen balance will also now be visible:
|
|||
89ABCDEF: 0 BTC 0 BTC 9.99995 BTC
|
||||
TOTAL: 0 BTC 0 BTC 9.99995 BTC
|
||||
|
||||
To verify that your transaction's received its first, second, third and so forth
|
||||
To verify that your transaction's received its first, second, third, and so on,
|
||||
confirmation, increase the 'minconf' value to 1, 2, 3 and so forth.
|
||||
|
||||
Congratulations! You've performed your first MMGen transaction and placed your
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
#!/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-pywallet: Dump contents of a bitcoind wallet to file
|
||||
"""
|
||||
|
||||
from mmgen.main import launch
|
||||
launch("pywallet")
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
|
|||
158
mmgen/addr.py
158
mmgen/addr.py
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
@ -20,17 +20,13 @@
|
|||
addr.py: Address generation/display routines for the MMGen suite
|
||||
"""
|
||||
|
||||
import sys
|
||||
from hashlib import sha256, sha512
|
||||
from hashlib import new as hashlib_new
|
||||
from hashlib import sha256, sha512, new as hashlib_new
|
||||
from binascii import hexlify, unhexlify
|
||||
|
||||
from mmgen.common import *
|
||||
from mmgen.bitcoin import numtowif
|
||||
from mmgen.util import *
|
||||
from mmgen.tx import *
|
||||
from mmgen.obj import *
|
||||
import mmgen.globalvars as g
|
||||
import mmgen.opt as opt
|
||||
|
||||
pnm = g.proj_name
|
||||
|
||||
|
|
@ -54,7 +50,7 @@ addrmsgs = {
|
|||
Executable '{kconv}' unavailable. Falling back on (slow) internal ECDSA library.
|
||||
Please install '{kconv}' from the {vgen} package on your system for much
|
||||
faster address generation.
|
||||
""".format(kconv=g.keyconv_exec, vgen="vanitygen")
|
||||
""".format(kconv=g.keyconv_exec, vgen='vanitygen')
|
||||
}
|
||||
|
||||
def test_for_keyconv(silent=False):
|
||||
|
|
@ -69,19 +65,19 @@ def test_for_keyconv(silent=False):
|
|||
return True
|
||||
|
||||
|
||||
def generate_addrs(seed, addrnums, source="addrgen"):
|
||||
def generate_addrs(seed, addrnums, source='addrgen'):
|
||||
|
||||
from util import make_chksum_8
|
||||
seed_id = make_chksum_8(seed) # Must do this before seed gets clobbered
|
||||
|
||||
if 'a' in opt.gen_what:
|
||||
if opt.no_keyconv or test_for_keyconv() == False:
|
||||
msg("Using (slow) internal ECDSA library for address generation")
|
||||
msg('Using (slow) internal ECDSA library for address generation')
|
||||
from mmgen.bitcoin import privnum2addr
|
||||
keyconv = False
|
||||
else:
|
||||
from subprocess import check_output
|
||||
keyconv = "keyconv"
|
||||
keyconv = 'keyconv'
|
||||
|
||||
addrnums = sorted(set(addrnums)) # don't trust the calling function
|
||||
t_addrs,num,pos,out = len(addrnums),0,0,[]
|
||||
|
|
@ -102,7 +98,7 @@ def generate_addrs(seed, addrnums, source="addrgen"):
|
|||
|
||||
pos += 1
|
||||
|
||||
qmsg_r("\rGenerating %s #%s (%s of %s)" % (w[0],num,pos,t_addrs))
|
||||
qmsg_r('\rGenerating %s #%s (%s of %s)' % (w[0],num,pos,t_addrs))
|
||||
|
||||
e = AddrInfoEntry()
|
||||
e.idx = num
|
||||
|
|
@ -123,7 +119,7 @@ def generate_addrs(seed, addrnums, source="addrgen"):
|
|||
out.append(e)
|
||||
|
||||
m = w[0] if t_addrs == 1 else w[0]+w[1]
|
||||
qmsg("\r%s: %s %s generated%s" % (seed_id,t_addrs,m," "*15))
|
||||
qmsg('\r%s: %s %s generated%s' % (seed_id,t_addrs,m,' '*15))
|
||||
a = AddrInfo(has_keys='k' in opt.gen_what, source=source)
|
||||
a.initialize(seed_id,out)
|
||||
return a
|
||||
|
|
@ -131,7 +127,7 @@ def generate_addrs(seed, addrnums, source="addrgen"):
|
|||
def _parse_addrfile_body(lines,has_keys=False,check=False):
|
||||
|
||||
if has_keys and len(lines) % 2:
|
||||
return "Key-address file has odd number of lines"
|
||||
return 'Key-address file has odd number of lines'
|
||||
|
||||
ret = []
|
||||
while lines:
|
||||
|
|
@ -145,7 +141,7 @@ def _parse_addrfile_body(lines,has_keys=False,check=False):
|
|||
return "'%s': invalid Bitcoin address" % d[1]
|
||||
|
||||
if len(d) == 3: check_addr_label(d[2])
|
||||
else: d.append("")
|
||||
else: d.append('')
|
||||
|
||||
a.idx,a.addr,a.comment = int(d[0]),unicode(d[1]),unicode(d[2])
|
||||
|
||||
|
|
@ -153,7 +149,7 @@ def _parse_addrfile_body(lines,has_keys=False,check=False):
|
|||
l = lines.pop(0)
|
||||
d = l.split(None,2)
|
||||
|
||||
if d[0] != "wif:":
|
||||
if d[0] != 'wif:':
|
||||
return "Invalid key line in file: '%s'" % l
|
||||
if not is_wif(d[1]):
|
||||
return "'%s': invalid Bitcoin key" % d[1]
|
||||
|
|
@ -162,14 +158,14 @@ def _parse_addrfile_body(lines,has_keys=False,check=False):
|
|||
|
||||
ret.append(a)
|
||||
|
||||
if has_keys and keypress_confirm("Check key-to-address validity?"):
|
||||
if has_keys and keypress_confirm('Check key-to-address validity?'):
|
||||
wif2addr_f = get_wif2addr_f()
|
||||
llen = len(ret)
|
||||
for n,e in enumerate(ret):
|
||||
msg_r("\rVerifying keys %s/%s" % (n+1,llen))
|
||||
msg_r('\rVerifying keys %s/%s' % (n+1,llen))
|
||||
if e.addr != wif2addr_f(e.wif):
|
||||
return "Key doesn't match address!\n %s\n %s" % (e.wif,e.addr)
|
||||
msg(" - done")
|
||||
msg(' - done')
|
||||
|
||||
return ret
|
||||
|
||||
|
|
@ -177,7 +173,7 @@ def _parse_addrfile_body(lines,has_keys=False,check=False):
|
|||
def _parse_addrfile(fn,buf=[],has_keys=False,exit_on_error=True):
|
||||
|
||||
if buf: lines = remove_comments(buf.splitlines()) # DOS-safe
|
||||
else: lines = get_lines_from_file(fn,"address data",trim_comments=True)
|
||||
else: lines = get_lines_from_file(fn,'address data',trim_comments=True)
|
||||
|
||||
try:
|
||||
sid,obrace = lines[0].split()
|
||||
|
|
@ -196,17 +192,14 @@ def _parse_addrfile(fn,buf=[],has_keys=False,exit_on_error=True):
|
|||
if type(ret) == list: return sid,ret
|
||||
else: errmsg = ret
|
||||
|
||||
if exit_on_error:
|
||||
msg(errmsg)
|
||||
sys.exit(3)
|
||||
else:
|
||||
return False
|
||||
if exit_on_error: die(3,errmsg)
|
||||
else: return False
|
||||
|
||||
|
||||
def _parse_keyaddr_file(fn):
|
||||
from mmgen.crypto import mmgen_decrypt_file_maybe
|
||||
d = mmgen_decrypt_file_maybe(fn,"key-address file")
|
||||
return _parse_addrfile("",buf=d,has_keys=True,exit_on_error=False)
|
||||
d = mmgen_decrypt_file_maybe(fn,'key-address file')
|
||||
return _parse_addrfile('',buf=d,has_keys=True,exit_on_error=False)
|
||||
|
||||
|
||||
class AddrInfoList(MMGenObject):
|
||||
|
|
@ -225,31 +218,31 @@ class AddrInfoList(MMGenObject):
|
|||
return self.data[sid]
|
||||
|
||||
def mmaddr2btcaddr(self,mmaddr):
|
||||
btcaddr = ""
|
||||
sid,idx = mmaddr.split(":")
|
||||
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
|
||||
vmsg_r('Getting account data from wallet...')
|
||||
accts = c.listaccounts(0,True)
|
||||
data,i = {},0
|
||||
for acct in accts:
|
||||
ma,comment = parse_mmgen_label(acct)
|
||||
if ma:
|
||||
i += 1
|
||||
addrlist = c.getaddressesbyaccount(acct)
|
||||
if len(addrlist) != 1:
|
||||
msg(wmsg['too_many_acct_addresses'] % acct)
|
||||
sys.exit(2)
|
||||
seed_id,idx = ma.split(":")
|
||||
die(2,wmsg['too_many_acct_addresses'] % acct)
|
||||
seed_id,idx = ma.split(':')
|
||||
if seed_id not in data:
|
||||
data[seed_id] = []
|
||||
a = AddrInfoEntry()
|
||||
a.idx,a.addr,a.comment = \
|
||||
int(idx),unicode(addrlist[0]),unicode(comment)
|
||||
data[seed_id].append(a)
|
||||
vmsg("{n} {pnm} addresses found, {m} accounts total".format(
|
||||
vmsg('{n} {pnm} addresses found, {m} accounts total'.format(
|
||||
n=i,pnm=pnm,m=len(accts)))
|
||||
for sid in data:
|
||||
self.add(AddrInfo(sid=sid,adata=data[sid]))
|
||||
|
|
@ -259,8 +252,7 @@ class AddrInfoList(MMGenObject):
|
|||
self.data[addrinfo.seed_id] = addrinfo
|
||||
return True
|
||||
else:
|
||||
msg("Error: object %s is not of type AddrInfo" % repr(addrinfo))
|
||||
sys.exit(1)
|
||||
die(1,'Error: object %s is not of type AddrInfo' % repr(addrinfo))
|
||||
|
||||
def make_reverse_dict(self,btcaddrs):
|
||||
d = {}
|
||||
|
|
@ -274,53 +266,57 @@ class AddrInfoEntry(MMGenObject):
|
|||
|
||||
class AddrInfo(MMGenObject):
|
||||
|
||||
def __init__(self,addrfile="",has_keys=False,sid="",adata=[], source=""):
|
||||
def __init__(self,addrfile='',has_keys=False,sid='',adata=[],source='',caller=''):
|
||||
self.has_keys = has_keys
|
||||
self.caller = caller
|
||||
do_chksum = True
|
||||
if addrfile:
|
||||
f = _parse_keyaddr_file if has_keys else _parse_addrfile
|
||||
f = (_parse_addrfile,_parse_keyaddr_file)[bool(has_keys)]
|
||||
sid,adata = f(addrfile)
|
||||
self.source = "addrfile"
|
||||
self.source = 'addrfile'
|
||||
elif sid and adata: # data from wallet
|
||||
self.source = "wallet"
|
||||
self.source = 'wallet'
|
||||
elif sid or adata:
|
||||
die(3,"Must specify address file, or seed_id + adata")
|
||||
die(3,'Must specify address file, or seed_id + adata')
|
||||
else:
|
||||
self.source = source if source else "unknown"
|
||||
self.source = source if source else 'unknown'
|
||||
return
|
||||
|
||||
self.initialize(sid,adata)
|
||||
|
||||
def initialize(self,seed_id,addrdata):
|
||||
if seed_id in self.__dict__:
|
||||
msg("Seed ID already set for object %s" % self)
|
||||
msg('Seed ID already set for object %s' % self)
|
||||
return False
|
||||
self.seed_id = seed_id
|
||||
self.addrdata = addrdata
|
||||
self.num_addrs = len(addrdata)
|
||||
if self.source in ("wallet","txsign"):
|
||||
if self.source in ('wallet','txsign'):
|
||||
self.checksum = None
|
||||
self.idxs_fmt = None
|
||||
elif self.source == "addrgen" and opt.gen_what == "k":
|
||||
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()
|
||||
w = "key-address" if self.has_keys else "address"
|
||||
qmsg("Checksum for %s data %s[%s]: %s" %
|
||||
(w,self.seed_id,self.idxs_fmt,self.checksum))
|
||||
if self.source == "addrgen":
|
||||
qmsg(
|
||||
"Record this checksum: it will be used to verify the address file in the future")
|
||||
elif self.source == "addrfile":
|
||||
qmsg("Check this value against your records")
|
||||
if self.caller == 'tool':
|
||||
Msg(self.checksum)
|
||||
else:
|
||||
self.fmt_addr_idxs()
|
||||
w = ('address','key-address')[bool(self.has_keys)]
|
||||
qmsg('Checksum for %s data %s[%s]: %s' %
|
||||
(w,self.seed_id,self.idxs_fmt,self.checksum))
|
||||
if self.source == 'addrgen':
|
||||
qmsg(
|
||||
'Record this checksum: it will be used to verify the address file in the future')
|
||||
elif self.source == 'addrfile':
|
||||
qmsg('Check this value against your records')
|
||||
|
||||
def idxs(self):
|
||||
return [e.idx for e in self.addrdata]
|
||||
|
||||
def addrs(self):
|
||||
return ["%s:%s"%(self.seed_id,e.idx) for e in self.addrdata]
|
||||
return ['%s:%s'%(self.seed_id,e.idx) for e in self.addrdata]
|
||||
|
||||
def addrpairs(self):
|
||||
return [(e.idx,e.addr) for e in self.addrdata]
|
||||
|
|
@ -355,15 +351,15 @@ class AddrInfo(MMGenObject):
|
|||
d,b = {},btcaddrs
|
||||
for e in self.addrdata:
|
||||
try:
|
||||
d[b[b.index(e.addr)]] = ("%s:%s"%(self.seed_id,e.idx),e.comment)
|
||||
d[b[b.index(e.addr)]] = ('%s:%s'%(self.seed_id,e.idx),e.comment)
|
||||
except: pass
|
||||
return d
|
||||
|
||||
|
||||
def make_addrdata_chksum(self):
|
||||
lines=[" ".join([str(e.idx),e.addr]+([e.wif] if self.has_keys else []))
|
||||
lines=[' '.join([str(e.idx),e.addr]+([e.wif] if self.has_keys else []))
|
||||
for e in self.addrdata]
|
||||
self.checksum = make_chksum_N(" ".join(lines), nchars=24, sep=True)
|
||||
self.checksum = make_chksum_N(' '.join(lines), nchars=24, sep=True)
|
||||
|
||||
|
||||
def fmt_data(self,enable_comments=False):
|
||||
|
|
@ -377,53 +373,51 @@ class AddrInfo(MMGenObject):
|
|||
|
||||
for i,s in enumerate(status):
|
||||
if s != 0 and s != self.num_addrs:
|
||||
msg("%s missing %s in addr data"% (self.num_addrs-s,attrs[i]))
|
||||
sys.exit(3)
|
||||
die(3,'%s missing %s in addr data'% (self.num_addrs-s,attrs[i]))
|
||||
|
||||
if status[0] == status[1] == 0:
|
||||
msg("Addr data contains neither addresses nor keys")
|
||||
sys.exit(3)
|
||||
die(3,'Addr data contains neither addresses nor keys')
|
||||
|
||||
# Header
|
||||
out = []
|
||||
from mmgen.addr import addrmsgs
|
||||
k = ('addrfile_header','keyfile_header')[int(status[0]==0)]
|
||||
out.append(addrmsgs[k]+"\n")
|
||||
k = ('addrfile_header','keyfile_header')[status[0]==0]
|
||||
out.append(addrmsgs[k]+'\n')
|
||||
if self.checksum:
|
||||
w = ("Key-address","Address")[int(status[1]==0)]
|
||||
out.append("# {} data checksum for {}[{}]: {}".format(
|
||||
w = ('Key-address','Address')[status[1]==0]
|
||||
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)
|
||||
out.append('# Record this value to a secure location.\n')
|
||||
out.append('%s {' % self.seed_id)
|
||||
|
||||
# Body
|
||||
fs = " {:<%s} {:<34}{}" % len(str(self.addrdata[-1].idx))
|
||||
fs = ' {:<%s} {:<34}{}' % len(str(self.addrdata[-1].idx))
|
||||
for e in self.addrdata:
|
||||
c = ""
|
||||
c = ''
|
||||
if enable_comments:
|
||||
try: c = " "+e.comment
|
||||
try: c = ' '+e.comment
|
||||
except: pass
|
||||
if status[0]: # First line with idx
|
||||
out.append(fs.format(e.idx, e.addr,c))
|
||||
else:
|
||||
out.append(fs.format(e.idx, "wif: "+e.wif,c))
|
||||
out.append(fs.format(e.idx, 'wif: '+e.wif,c))
|
||||
|
||||
if status[1]: # Subsequent lines
|
||||
if status[2]:
|
||||
out.append(fs.format("", "hex: "+e.sec,c))
|
||||
out.append(fs.format('', 'hex: '+e.sec,c))
|
||||
if status[0]:
|
||||
out.append(fs.format("", "wif: "+e.wif,c))
|
||||
out.append(fs.format('', 'wif: '+e.wif,c))
|
||||
|
||||
out.append("}")
|
||||
out.append('}')
|
||||
|
||||
return "\n".join([l.rstrip() for l in out]) + "\n"
|
||||
return '\n'.join([l.rstrip() for l in out]) + '\n'
|
||||
|
||||
|
||||
def fmt_addr_idxs(self):
|
||||
|
||||
try: int(self.addrdata[0].idx)
|
||||
except:
|
||||
self.idxs_fmt = "(no idxs)"
|
||||
self.idxs_fmt = '(no idxs)'
|
||||
return
|
||||
|
||||
addr_idxs = [e.idx for e in self.addrdata]
|
||||
|
|
@ -432,10 +426,10 @@ class AddrInfo(MMGenObject):
|
|||
|
||||
for i in addr_idxs[1:]:
|
||||
if i == prev + 1:
|
||||
if i == addr_idxs[-1]: ret += "-", i
|
||||
if i == addr_idxs[-1]: ret += '-', i
|
||||
else:
|
||||
if prev != ret[-1]: ret += "-", prev
|
||||
ret += ",", i
|
||||
if prev != ret[-1]: ret += '-', prev
|
||||
ret += ',', i
|
||||
prev = i
|
||||
|
||||
self.idxs_fmt = "".join([str(i) for i in ret])
|
||||
self.idxs_fmt = ''.join([str(i) for i in ret])
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# MMGen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
@ -37,7 +37,7 @@ _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
|
|||
curve_secp256k1 = ecdsa.ellipticcurve.CurveFp( _p, _a, _b )
|
||||
generator_secp256k1 = ecdsa.ellipticcurve.Point( curve_secp256k1, _Gx, _Gy, _r )
|
||||
oid_secp256k1 = (1,3,132,0,10)
|
||||
secp256k1 = ecdsa.curves.Curve("secp256k1", curve_secp256k1, generator_secp256k1, oid_secp256k1)
|
||||
secp256k1 = ecdsa.curves.Curve('secp256k1', curve_secp256k1, generator_secp256k1, oid_secp256k1)
|
||||
|
||||
b58a='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
||||
|
||||
|
|
@ -49,8 +49,8 @@ b58a='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
|
|||
#
|
||||
# Test: 5JbQQTs3cnoYN9vDYaGY6nhQ1DggVsY4FJNBUfEfpSQqrEp3srk
|
||||
#
|
||||
# The "zero address":
|
||||
# 1111111111111111111114oLvT2 (use step2 = ("0" * 40) to generate)
|
||||
# The 'zero address':
|
||||
# 1111111111111111111114oLvT2 (use step2 = ('0' * 40) to generate)
|
||||
#
|
||||
|
||||
def pubhex2hexaddr(pubhex):
|
||||
|
|
@ -63,8 +63,8 @@ def hexaddr2addr(hexaddr, vers_num='00'):
|
|||
step1 = sha256(unhexlify(hexaddr2)).digest()
|
||||
step2 = sha256(step1).hexdigest()
|
||||
pubkey = hexaddr2 + step2[:8]
|
||||
lzeroes = (len(hexaddr2) - len(hexaddr2.lstrip("0"))) / 2
|
||||
return ("1" * lzeroes) + _numtob58(int(pubkey,16))
|
||||
lzeroes = (len(hexaddr2) - len(hexaddr2.lstrip('0'))) / 2
|
||||
return ('1' * lzeroes) + _numtob58(int(pubkey,16))
|
||||
|
||||
def verify_addr(addr,verbose=False,return_hex=False):
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ def verify_addr(addr,verbose=False,return_hex=False):
|
|||
if addr[0] != ldigit: continue
|
||||
num = _b58tonum(addr)
|
||||
if num == False: break
|
||||
addr_hex = "{:050x}".format(num)
|
||||
addr_hex = '{:050x}'.format(num)
|
||||
if addr_hex[:2] != vers_num: continue
|
||||
step1 = sha256(unhexlify(addr_hex[:42])).digest()
|
||||
step2 = sha256(step1).hexdigest()
|
||||
|
|
@ -101,7 +101,7 @@ def _b58tonum(b58num):
|
|||
return sum([b58a.index(n) * (58**i) for i,n in enumerate(list(b58num[::-1]))])
|
||||
|
||||
def numtowif(numpriv):
|
||||
step1 = '80' + "{:064x}".format(numpriv)
|
||||
step1 = '80' + '{:064x}'.format(numpriv)
|
||||
step2 = sha256(unhexlify(step1)).digest()
|
||||
step3 = sha256(step2).hexdigest()
|
||||
key = step1 + step3[:8]
|
||||
|
|
@ -113,17 +113,17 @@ def numtowif(numpriv):
|
|||
# (well, not exactly: they yield numeric but not bytewise equivalence)
|
||||
|
||||
def b58encode(s):
|
||||
if s == "": return ""
|
||||
if s == '': return ''
|
||||
num = int(hexlify(s),16)
|
||||
return _numtob58(num)
|
||||
|
||||
def b58decode(b58num):
|
||||
if b58num == "": return ""
|
||||
if b58num == '': return ''
|
||||
# Zap all spaces:
|
||||
num = _b58tonum(b58num.translate(None,' \t\n\r'))
|
||||
if num == False: return False
|
||||
out = "{:x}".format(num)
|
||||
return unhexlify("0"*(len(out)%2) + out)
|
||||
out = '{:x}'.format(num)
|
||||
return unhexlify('0'*(len(out)%2) + out)
|
||||
|
||||
# These yield bytewise equivalence in our special cases:
|
||||
|
||||
|
|
@ -134,36 +134,36 @@ def _b58_pad(s,a,b,pad,f,w):
|
|||
try:
|
||||
outlen = b[a.index(len(s))]
|
||||
except:
|
||||
Msg("_b58_pad() accepts only %s %s bytes long "\
|
||||
"(input was %s bytes)" % (w,",".join([str(i) for i in a]),len(s)))
|
||||
Msg('_b58_pad() accepts only %s %s bytes long '\
|
||||
'(input was %s bytes)' % (w,','.join([str(i) for i in a]),len(s)))
|
||||
return False
|
||||
|
||||
out = f(s)
|
||||
if out == False: return False
|
||||
return "%s%s" % (pad * (outlen - len(out)), out)
|
||||
return '%s%s' % (pad * (outlen - len(out)), out)
|
||||
|
||||
def b58encode_pad(s):
|
||||
return _b58_pad(s,
|
||||
a=bin_lens,b=b58_lens,pad="1",f=b58encode,w="binary strings")
|
||||
a=bin_lens,b=b58_lens,pad='1',f=b58encode,w='binary strings')
|
||||
|
||||
def b58decode_pad(s):
|
||||
return _b58_pad(s,
|
||||
a=b58_lens,b=bin_lens,pad='\0',f=b58decode,w="base 58 numbers")
|
||||
a=b58_lens,b=bin_lens,pad='\0',f=b58decode,w='base 58 numbers')
|
||||
|
||||
# Compressed address support:
|
||||
|
||||
def wiftohex(wifpriv,compressed=False):
|
||||
idx = 68 if compressed else 66
|
||||
idx = (66,68)[bool(compressed)]
|
||||
num = _b58tonum(wifpriv)
|
||||
if num == False: return False
|
||||
key = "{:x}".format(num)
|
||||
key = '{:x}'.format(num)
|
||||
if compressed and key[66:68] != '01': return False
|
||||
round1 = sha256(unhexlify(key[:idx])).digest()
|
||||
round2 = sha256(round1).hexdigest()
|
||||
return key[2:66] if (key[:2] == '80' and key[idx:] == round2[:8]) else False
|
||||
|
||||
def hextowif(hexpriv,compressed=False):
|
||||
step1 = '80' + hexpriv + ('01' if compressed else '')
|
||||
step1 = '80' + hexpriv + ('','01')[bool(compressed)]
|
||||
step2 = sha256(unhexlify(step1)).digest()
|
||||
step3 = sha256(step2).hexdigest()
|
||||
key = step1 + step3[:8]
|
||||
|
|
@ -173,7 +173,7 @@ def privnum2pubhex(numpriv,compressed=False):
|
|||
pko = ecdsa.SigningKey.from_secret_exponent(numpriv,secp256k1)
|
||||
pubkey = hexlify(pko.get_verifying_key().to_string())
|
||||
if compressed:
|
||||
p = '02' if pubkey[-1] in "02468ace" else '03'
|
||||
p = ('03','02')[pubkey[-1] in '02468ace']
|
||||
return p+pubkey[:64]
|
||||
else:
|
||||
return '04'+pubkey
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
@ -17,6 +17,11 @@
|
|||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
"""
|
||||
opt.py: a namespace for the global opt variables
|
||||
common.py: Common imports for all MMGen scripts
|
||||
"""
|
||||
import opts
|
||||
|
||||
import sys
|
||||
import mmgen.globalvars as g
|
||||
import mmgen.opts as opts
|
||||
from mmgen.opts import opt
|
||||
from mmgen.util import *
|
||||
122
mmgen/crypto.py
122
mmgen/crypto.py
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
@ -20,13 +20,10 @@
|
|||
crypto.py: Cryptographic and related routines for the MMGen suite
|
||||
"""
|
||||
|
||||
import sys
|
||||
from binascii import hexlify
|
||||
from hashlib import sha256
|
||||
|
||||
import mmgen.globalvars as g
|
||||
import mmgen.opt as opt
|
||||
from mmgen.util import *
|
||||
from mmgen.common import *
|
||||
from mmgen.term import get_char
|
||||
|
||||
crmsg = {
|
||||
|
|
@ -58,73 +55,72 @@ keystrokes will also be used as a source of randomness.
|
|||
}
|
||||
|
||||
def encrypt_seed(seed, key):
|
||||
return encrypt_data(seed, key, iv=1, desc="seed")
|
||||
return encrypt_data(seed, key, iv=1, desc='seed')
|
||||
|
||||
|
||||
def decrypt_seed(enc_seed, key, seed_id, key_id):
|
||||
|
||||
vmsg_r("Checking key...")
|
||||
vmsg_r('Checking key...')
|
||||
chk1 = make_chksum_8(key)
|
||||
if key_id:
|
||||
if not compare_chksums(key_id,"key ID",chk1,"computed"):
|
||||
msg("Incorrect passphrase or hash preset")
|
||||
if not compare_chksums(key_id,'key ID',chk1,'computed'):
|
||||
msg('Incorrect passphrase or hash preset')
|
||||
return False
|
||||
|
||||
dec_seed = decrypt_data(enc_seed, key, iv=1, desc="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"):
|
||||
qmsg("Passphrase is OK")
|
||||
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"):
|
||||
msg("Key ID is correct but decryption of seed failed")
|
||||
msg_r('Checking key ID...')
|
||||
if compare_chksums(key_id,'key ID',chk1,'computed'):
|
||||
msg('Key ID is correct but decryption of seed failed')
|
||||
else:
|
||||
msg("Incorrect passphrase or hash preset")
|
||||
msg('Incorrect passphrase or hash preset')
|
||||
|
||||
vmsg("")
|
||||
vmsg('')
|
||||
return False
|
||||
# else:
|
||||
# qmsg("Generated IDs (Seed/Key): %s/%s" % (chk2,chk1))
|
||||
# qmsg('Generated IDs (Seed/Key): %s/%s' % (chk2,chk1))
|
||||
|
||||
dmsg("Decrypted seed: %s" % hexlify(dec_seed))
|
||||
dmsg('Decrypted seed: %s' % hexlify(dec_seed))
|
||||
|
||||
return dec_seed
|
||||
|
||||
|
||||
def encrypt_data(data, key, iv=1, desc="data", verify=True):
|
||||
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" % desc)
|
||||
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..." % desc)
|
||||
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))
|
||||
dec_data = c.decrypt(enc_data)
|
||||
|
||||
if dec_data == data: vmsg("done")
|
||||
if dec_data == data: vmsg('done')
|
||||
else:
|
||||
msg("ERROR.\nDecrypted %s doesn't match original %s" % (desc,desc))
|
||||
sys.exit(2)
|
||||
die(2,"ERROR.\nDecrypted %s doesn't match original %s" % (desc,desc))
|
||||
|
||||
return enc_data
|
||||
|
||||
|
||||
def decrypt_data(enc_data, key, iv=1, desc="data"):
|
||||
def decrypt_data(enc_data, key, iv=1, desc='data'):
|
||||
|
||||
vmsg_r("Decrypting %s with key..." % desc)
|
||||
vmsg_r('Decrypting %s with key...' % desc)
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util import Counter
|
||||
|
|
@ -147,66 +143,66 @@ def scrypt_hash_passphrase(passwd, salt, hash_preset, buflen=32):
|
|||
|
||||
|
||||
def make_key(passwd,salt,hash_preset,
|
||||
desc="encryption key",from_what="passphrase",verbose=False):
|
||||
desc='encryption key',from_what='passphrase',verbose=False):
|
||||
|
||||
if from_what: desc += " from "
|
||||
if from_what: desc += ' from '
|
||||
if opt.verbose or verbose:
|
||||
msg_r("Generating %s%s..." % (desc,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")
|
||||
dmsg("Key: %s" % hexlify(key))
|
||||
if opt.verbose or verbose: msg('done')
|
||||
dmsg('Key: %s' % hexlify(key))
|
||||
return key
|
||||
|
||||
|
||||
def _get_random_data_from_user(uchars):
|
||||
|
||||
if opt.quiet: msg("Enter %s random symbols" % uchars)
|
||||
if opt.quiet: msg('Enter %s random symbols' % uchars)
|
||||
else: msg(crmsg['usr_rand_notice'] % uchars)
|
||||
|
||||
prompt = "You may begin typing. %s symbols left: "
|
||||
prompt = 'You may begin typing. %s symbols left: '
|
||||
msg_r(prompt % uchars)
|
||||
|
||||
import time
|
||||
# time.clock() always returns zero, so we'll use time.time()
|
||||
saved_time = time.time()
|
||||
|
||||
key_data,time_data,pp = "",[],True
|
||||
key_data,time_data,pp = '',[],True
|
||||
|
||||
for i in range(uchars):
|
||||
key_data += get_char(immed_chars="ALL",prehold_protect=pp)
|
||||
key_data += get_char(immed_chars='ALL',prehold_protect=pp)
|
||||
pp = False
|
||||
msg_r("\r" + prompt % (uchars - i - 1))
|
||||
msg_r('\r' + prompt % (uchars - i - 1))
|
||||
now = time.time()
|
||||
time_data.append(now - saved_time)
|
||||
saved_time = now
|
||||
|
||||
if opt.quiet: msg_r("\r")
|
||||
else: msg_r("\rThank you. That's enough.%s\n\n" % (" "*18))
|
||||
if opt.quiet: msg_r('\r')
|
||||
else: msg_r("\rThank you. That's enough.%s\n\n" % (' '*18))
|
||||
|
||||
fmt_time_data = ["{:.22f}".format(i) for i in time_data]
|
||||
fmt_time_data = ['{:.22f}'.format(i) for i in time_data]
|
||||
|
||||
dmsg("\nUser input:\n%s\nKeystroke time intervals:\n%s\n" %
|
||||
(key_data,"\n".join(fmt_time_data)))
|
||||
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"
|
||||
prompt_and_get_char(prompt,"",enter_ok=True)
|
||||
prompt = 'User random data successfully acquired. Press ENTER to continue'
|
||||
prompt_and_get_char(prompt,'',enter_ok=True)
|
||||
|
||||
return key_data+"".join(fmt_time_data)
|
||||
return key_data+''.join(fmt_time_data)
|
||||
|
||||
|
||||
def get_random(length):
|
||||
from Crypto import Random
|
||||
os_rand = Random.new().read(length)
|
||||
if g.use_urandchars and opt.usr_randchars:
|
||||
from_what = "OS random data"
|
||||
from_what = 'OS random data'
|
||||
if not g.user_entropy:
|
||||
g.user_entropy = \
|
||||
sha256(_get_random_data_from_user(opt.usr_randchars)).digest()
|
||||
from_what += " plus user-supplied entropy"
|
||||
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,desc="random data",verify=False)
|
||||
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,desc='random data',verify=False)
|
||||
else:
|
||||
return os_rand
|
||||
|
||||
|
|
@ -214,13 +210,13 @@ def get_random(length):
|
|||
# Vars for mmgen_*crypt functions only
|
||||
salt_len,sha256_len,nonce_len = 32,32,32
|
||||
|
||||
def mmgen_encrypt(data,desc="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',desc)
|
||||
m = "default" if hp == '3' else "user-requested"
|
||||
vmsg("Encrypting %s" % desc)
|
||||
m = ('user-requested','default')[hp=='3']
|
||||
vmsg('Encrypting %s' % desc)
|
||||
qmsg("Using %s hash preset of '%s'" % (m,hp))
|
||||
passwd = get_new_passphrase(desc, {})
|
||||
key = make_key(passwd, salt, hp)
|
||||
|
|
@ -229,34 +225,34 @@ def mmgen_encrypt(data,desc="data",hash_preset=''):
|
|||
return salt+iv+enc_d
|
||||
|
||||
|
||||
def mmgen_decrypt(data,desc="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" % desc)
|
||||
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"
|
||||
m = ('user-requested','default')[hp=='3']
|
||||
qmsg("Using %s hash preset of '%s'" % (m,hp))
|
||||
passwd = get_mmgen_passphrase(desc)
|
||||
key = make_key(passwd, salt, hp)
|
||||
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")
|
||||
vmsg('OK')
|
||||
return dec_d[sha256_len+nonce_len:]
|
||||
else:
|
||||
msg("Incorrect passphrase or hash preset")
|
||||
msg('Incorrect passphrase or hash preset')
|
||||
return False
|
||||
|
||||
def mmgen_decrypt_file_maybe(fn,desc):
|
||||
d = get_data_from_file(fn,"{} data".format(desc),binary=True)
|
||||
d = get_data_from_file(fn,'{} data'.format(desc),binary=True)
|
||||
have_enc_ext = get_extension(fn) == g.mmenc_ext
|
||||
if have_enc_ext or not is_ascii(d):
|
||||
m = ("Attempting to decrypt","Decrypting")[int(have_enc_ext)]
|
||||
msg("%s %s %s" % (m,desc,fn))
|
||||
m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
|
||||
msg('%s %s %s' % (m,desc,fn))
|
||||
d = mmgen_decrypt_retry(d,desc)
|
||||
return d
|
||||
|
||||
def mmgen_decrypt_retry(d,desc="data"):
|
||||
def mmgen_decrypt_retry(d,desc='data'):
|
||||
while True:
|
||||
d_dec = mmgen_decrypt(d,desc)
|
||||
if d_dec: return d_dec
|
||||
msg("Trying again...")
|
||||
msg('Trying again...')
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
|
||||
# Copyright (C)2013-2015 Philemon <mmgen-py@yandex.com>
|
||||
# Copyright (C)2013-2016 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
|
||||
|
|
@ -41,7 +41,7 @@ class Filename(MMGenObject):
|
|||
die(2,"Unrecognized extension '.%s' for file '%s'" % (self.ext,fn))
|
||||
|
||||
# TODO: Check for Windows
|
||||
mode = (os.O_RDONLY,os.O_RDWR)[int(write)]
|
||||
mode = (os.O_RDONLY,os.O_RDWR)[bool(write)]
|
||||
import stat
|
||||
if stat.S_ISBLK(os.stat(fn).st_mode):
|
||||
try:
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue