123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196 |
- #!/usr/bin/env python
- #
- # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
- # Copyright (C)2013-2017 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/>.
- """
- txsign: Sign a transaction generated by 'mmgen-txcreate'
- """
- from mmgen.common import *
- from mmgen.seed import *
- from mmgen.tx import *
- from mmgen.addr import *
- pnm = g.proj_name
- txsign_notes = """
- Transactions may contain both {pnm} or non-{pnm} input addresses.
- To sign non-{pnm} inputs, a bitcoind wallet dump or flat key list is used
- as the key source ('--keys-from-file' option).
- To sign {pnm} inputs, key data is generated from a seed as with the
- {pnl}-addrgen and {pnl}-keygen commands. Alternatively, a key-address file
- may be used (--mmgen-keys-from-file option).
- Multiple wallets or other seed files can be listed on the command line in
- any order. If the seeds required to sign the transaction's inputs are not
- found in these files (or in the default wallet), the user will be prompted
- for seed data interactively.
- To prevent an attacker from crafting transactions with bogus {pnm}-to-Bitcoin
- address mappings, all outputs to {pnm} addresses are verified with a seed
- source. Therefore, seed files or a key-address file for all {pnm} outputs
- must also be supplied on the command line if the data can't be found in the
- default wallet.
- Seed source files must have the canonical extensions listed in the 'FileExt'
- column below:
- {f}
- """.format(f='\n '.join(SeedSource.format_fmt_codes().splitlines()),
- pnm=pnm,pnl=pnm.lower())
- wmsg = {
- 'mapping_error': """
- {pnm} -> {c} address mappings differ!
- {{:<23}} {{}} -> {{}}
- {{:<23}} {{}} -> {{}}
- """.strip().format(pnm=pnm,c=g.coin),
- 'missing_keys_error': """
- ERROR: a key file must be supplied for the following non-{pnm} address{{}}:\n {{}}
- """.format(pnm=pnm).strip()
- }
- saved_seeds = {}
- def get_seed_for_seed_id(sid,infiles,saved_seeds):
- if sid in saved_seeds:
- return saved_seeds[sid]
- while True:
- if infiles:
- ss = SeedSource(infiles.pop(0),ignore_in_fmt=True)
- elif opt.in_fmt:
- qmsg('Need seed data for Seed ID %s' % sid)
- ss = SeedSource()
- msg('User input produced Seed ID %s' % ss.seed.sid)
- else:
- die(2,'ERROR: No seed source found for Seed ID: %s' % sid)
- saved_seeds[ss.seed.sid] = ss.seed
- if ss.seed.sid == sid: return ss.seed
- def generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds):
- mmids = [e.mmid for e in need_keys]
- sids = set(i.sid for i in mmids)
- vmsg('Need seed%s: %s' % (suf(sids,'s'),' '.join(sids)))
- d = MMGenList()
- from mmgen.addr import KeyAddrList
- for sid in sids:
- # Returns only if seed is found
- seed = get_seed_for_seed_id(sid,infiles,saved_seeds)
- for t in MMGenAddrType.mmtypes:
- idx_list = [i.idx for i in mmids if i.sid == sid and i.mmtype == t]
- if idx_list:
- addr_idxs = AddrIdxList(idx_list=idx_list)
- d.append(KeyAddrList(seed=seed,addr_idxs=addr_idxs,do_chksum=False,mmtype=MMGenAddrType(t)))
- return d
- def add_keys(tx,src,infiles=None,saved_seeds=None,keyaddr_list=None):
- need_keys = [e for e in getattr(tx,src) if e.mmid and not e.have_wif]
- if not need_keys: return []
- desc,m1 = ('key-address file','From key-address file:') if keyaddr_list else \
- ('seed(s)','Generated from seed:')
- qmsg('Checking {} -> {} address mappings for {} (from {})'.format(pnm,g.coin,src,desc))
- d = MMGenList([keyaddr_list]) if keyaddr_list else \
- generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds)
- new_keys = []
- for e in need_keys:
- for kal in d:
- for f in kal.data:
- mmid = '{}:{}'.format(kal.al_id,f.idx)
- if mmid == e.mmid:
- if f.addr == e.addr:
- e.have_wif = True
- if src == 'inputs':
- new_keys.append(f)
- else:
- die(3,wmsg['mapping_error'].format(m1,mmid,f.addr,'tx file:',e.mmid,e.addr))
- if new_keys:
- vmsg('Added %s wif key%s from %s' % (len(new_keys),suf(new_keys,'s'),desc))
- return new_keys
- def _pop_and_return(args,cmplist): # strips found args
- return list(reversed([args.pop(args.index(a)) for a in reversed(args) if get_extension(a) in cmplist]))
- def get_tx_files(opt,args):
- ret = _pop_and_return(args,[MMGenTX.raw_ext])
- if not ret: die(1,'You must specify a raw transaction file!')
- return ret
- def get_seed_files(opt,args):
- # favor unencrypted seed sources first, as they don't require passwords
- u,e = SeedSourceUnenc,SeedSourceEnc
- ret = _pop_and_return(args,u.get_extensions())
- from mmgen.filename import find_file_in_dir,find_files_in_dir
- if g.bob or g.alice:
- import regtest as rt
- wf = rt.mmwallet(('alice','bob')[g.bob])
- else:
- wf = find_file_in_dir(Wallet,g.data_dir) # Make this the first encrypted ss in the list
- if wf: ret.append(wf)
- ret += _pop_and_return(args,e.get_extensions())
- if not (ret or opt.mmgen_keys_from_file or opt.keys_from_file): # or opt.use_wallet_dat
- die(1,'You must specify a seed or key source!')
- return ret
- def get_keyaddrlist(opt):
- if opt.mmgen_keys_from_file:
- return KeyAddrList(opt.mmgen_keys_from_file)
- return None
- def get_keylist(opt):
- if opt.keys_from_file:
- l = get_lines_from_file(opt.keys_from_file,'key-address data',trim_comments=True)
- kal = KeyAddrList(keylist=[m.split()[0] for m in l]) # accept bitcoind wallet dumps
- kal.generate_addrs_from_keys()
- return kal
- return None
- def txsign(opt,c,tx,seed_files,kl,kal,tx_num_str=''):
- keys = MMGenList() # list of AddrListEntry objects
- non_mm_addrs = tx.get_non_mmaddrs('inputs')
- if non_mm_addrs:
- tmp = KeyAddrList(addrlist=non_mm_addrs,do_chksum=False)
- tmp.add_wifs(kl)
- m = tmp.list_missing('sec')
- if m: die(2,wmsg['missing_keys_error'].format(suf(m,'es'),'\n '.join(m)))
- keys += tmp.data
- if opt.mmgen_keys_from_file:
- keys += add_keys(tx,'inputs',keyaddr_list=kal)
- add_keys(tx,'outputs',keyaddr_list=kal)
- keys += add_keys(tx,'inputs',seed_files,saved_seeds)
- add_keys(tx,'outputs',seed_files,saved_seeds)
- # this attr must not be written to file
- tx.delete_attrs('inputs','have_wif')
- tx.delete_attrs('outputs','have_wif')
- extra_sids = set(saved_seeds) - tx.get_input_sids() - tx.get_output_sids()
- if extra_sids:
- msg('Unused Seed ID{}: {}'.format(suf(extra_sids,'s'),' '.join(extra_sids)))
- if tx.sign(c,tx_num_str,keys):
- return tx
- else:
- die(3,red('Transaction {}could not be signed.'.format(tx_num_str)))
|