sign.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. tx.sign: Sign a transaction generated by 'mmgen-txcreate'
  20. """
  21. from ..common import *
  22. from ..obj import MMGenList
  23. from ..addr import MMGenAddrType
  24. from ..addrlist import AddrIdxList,KeyAddrList
  25. from ..wallet import Wallet,get_wallet_extensions,get_wallet_cls
  26. saved_seeds = {}
  27. def get_seed_for_seed_id(sid,infiles,saved_seeds):
  28. if sid in saved_seeds:
  29. return saved_seeds[sid]
  30. subseeds_checked = False
  31. while True:
  32. if infiles:
  33. seed = Wallet(infiles.pop(0),ignore_in_fmt=True).seed
  34. elif subseeds_checked == False:
  35. seed = saved_seeds[list(saved_seeds)[0]].subseed_by_seed_id(sid,print_msg=True)
  36. subseeds_checked = True
  37. if not seed: continue
  38. elif opt.in_fmt:
  39. qmsg(f'Need seed data for Seed ID {sid}')
  40. seed = Wallet().seed
  41. msg(f'User input produced Seed ID {seed.sid}')
  42. if not seed.sid == sid: # TODO: add test
  43. seed = seed.subseed_by_seed_id(sid,print_msg=True)
  44. if seed:
  45. saved_seeds[seed.sid] = seed
  46. if seed.sid == sid:
  47. return seed
  48. else:
  49. die(2,f'ERROR: No seed source found for Seed ID: {sid}')
  50. def generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds,proto):
  51. mmids = [e.mmid for e in need_keys]
  52. sids = remove_dups((i.sid for i in mmids),quiet=True)
  53. vmsg(f"Need seed{suf(sids)}: {' '.join(sids)}")
  54. def gen_kals():
  55. for sid in sids:
  56. # Returns only if seed is found
  57. seed = get_seed_for_seed_id(sid,infiles,saved_seeds)
  58. for id_str in MMGenAddrType.mmtypes:
  59. idx_list = [i.idx for i in mmids if i.sid == sid and i.mmtype == id_str]
  60. if idx_list:
  61. yield KeyAddrList(
  62. proto = proto,
  63. seed = seed,
  64. addr_idxs = AddrIdxList(idx_list=idx_list),
  65. mmtype = MMGenAddrType(proto,id_str),
  66. skip_chksum = True )
  67. return MMGenList(gen_kals())
  68. def add_keys(tx,src,infiles=None,saved_seeds=None,keyaddr_list=None):
  69. need_keys = [e for e in getattr(tx,src) if e.mmid and not e.have_wif]
  70. if not need_keys:
  71. return []
  72. desc,src_desc = (
  73. ('key-address file','From key-address file:') if keyaddr_list else
  74. ('seed(s)','Generated from seed:') )
  75. qmsg(f'Checking {g.proj_name} -> {tx.proto.coin} address mappings for {src} (from {desc})')
  76. d = (
  77. MMGenList([keyaddr_list]) if keyaddr_list else
  78. generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds,tx.proto) )
  79. new_keys = []
  80. for e in need_keys:
  81. for kal in d:
  82. for f in kal.data:
  83. mmid = f'{kal.al_id}:{f.idx}'
  84. if mmid == e.mmid:
  85. if f.addr == e.addr:
  86. e.have_wif = True
  87. if src == 'inputs':
  88. new_keys.append(f)
  89. else:
  90. die(3,fmt(f"""
  91. {g.proj_name} -> {tx.proto.coin} address mappings differ!
  92. {{src_desc:<23}} {{mmid}} -> {{f.addr}}
  93. {{'tx file:':<23}} {{e.mmid}} -> {{e.addr}}
  94. """).strip())
  95. if new_keys:
  96. vmsg(f'Added {len(new_keys)} wif key{suf(new_keys)} from {desc}')
  97. return new_keys
  98. def _pop_matching_fns(args,cmplist): # strips found args
  99. return list(reversed([args.pop(args.index(a)) for a in reversed(args) if get_extension(a) in cmplist]))
  100. def get_tx_files(opt,args):
  101. from .unsigned import Unsigned
  102. ret = _pop_matching_fns(args,[Unsigned.ext])
  103. if not ret:
  104. die(1,'You must specify a raw transaction file!')
  105. return ret
  106. def get_seed_files(opt,args):
  107. # favor unencrypted seed sources first, as they don't require passwords
  108. ret = _pop_matching_fns( args, get_wallet_extensions('unenc') )
  109. from ..filename import find_file_in_dir
  110. wf = find_file_in_dir(get_wallet_cls('mmgen'),g.data_dir) # Make this the first encrypted ss in the list
  111. if wf:
  112. ret.append(wf)
  113. ret += _pop_matching_fns( args, get_wallet_extensions('enc') )
  114. if not (ret or opt.mmgen_keys_from_file or opt.keys_from_file): # or opt.use_wallet_dat
  115. die(1,'You must specify a seed or key source!')
  116. return ret
  117. def get_keyaddrlist(proto,opt):
  118. if opt.mmgen_keys_from_file:
  119. return KeyAddrList(proto,opt.mmgen_keys_from_file)
  120. return None
  121. def get_keylist(proto,opt):
  122. if opt.keys_from_file:
  123. from ..fileutil import get_lines_from_file
  124. return get_lines_from_file(opt.keys_from_file,'key-address data',trim_comments=True)
  125. return None
  126. async def txsign(tx,seed_files,kl,kal,tx_num_str=''):
  127. keys = MMGenList() # list of AddrListEntry objects
  128. non_mmaddrs = tx.get_non_mmaddrs('inputs')
  129. if non_mmaddrs:
  130. tx.check_non_mmgen_inputs(caller='txsign',non_mmaddrs=non_mmaddrs)
  131. tmp = KeyAddrList(
  132. proto = tx.proto,
  133. addrlist = non_mmaddrs,
  134. skip_chksum = True )
  135. if kl:
  136. tmp.add_wifs(kl)
  137. missing = tmp.list_missing('sec')
  138. if missing:
  139. sep = '\n '
  140. die(2,'ERROR: a key file must be supplied for the following non-{} address{}:{}'.format(
  141. g.proj_name,
  142. suf(missing,'es'),
  143. sep + sep.join(missing) ))
  144. keys += tmp.data
  145. if opt.mmgen_keys_from_file:
  146. keys += add_keys(tx,'inputs',keyaddr_list=kal)
  147. add_keys(tx,'outputs',keyaddr_list=kal)
  148. keys += add_keys(tx,'inputs',seed_files,saved_seeds)
  149. add_keys(tx,'outputs',seed_files,saved_seeds)
  150. # this (boolean) attr isn't needed in transaction file
  151. tx.delete_attrs('inputs','have_wif')
  152. tx.delete_attrs('outputs','have_wif')
  153. extra_sids = remove_dups(
  154. (s for s in saved_seeds if s not in tx.get_sids('inputs') + tx.get_sids('outputs')),
  155. quiet = True )
  156. if extra_sids:
  157. msg(f"Unused Seed ID{suf(extra_sids)}: {' '.join(extra_sids)}")
  158. return await tx.sign(tx_num_str,keys) # returns signed TX object or False