sign.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 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 ..cfg import gc
  22. from ..util import msg,suf,fmt,die,remove_dups,get_extension
  23. from ..obj import MMGenList
  24. from ..addr import MMGenAddrType
  25. from ..addrlist import AddrIdxList,KeyAddrList
  26. from ..wallet import Wallet,get_wallet_extensions,get_wallet_cls
  27. saved_seeds = {}
  28. def get_seed_for_seed_id(sid,infiles,saved_seeds):
  29. if sid in saved_seeds:
  30. return saved_seeds[sid]
  31. subseeds_checked = False
  32. while True:
  33. if infiles:
  34. seed = Wallet(cfg, infiles.pop(0), ignore_in_fmt=True, passwd_file=global_passwd_file).seed
  35. elif subseeds_checked is False:
  36. seed = saved_seeds[list(saved_seeds)[0]].subseed_by_seed_id(sid,print_msg=True)
  37. subseeds_checked = True
  38. if not seed:
  39. continue
  40. elif cfg.in_fmt:
  41. cfg._util.qmsg(f'Need seed data for Seed ID {sid}')
  42. seed = Wallet(cfg, passwd_file=global_passwd_file).seed
  43. msg(f'User input produced Seed ID {seed.sid}')
  44. if not seed.sid == sid: # TODO: add test
  45. seed = seed.subseed_by_seed_id(sid,print_msg=True)
  46. if seed:
  47. saved_seeds[seed.sid] = seed
  48. if seed.sid == sid:
  49. return seed
  50. else:
  51. die(2,f'ERROR: No seed source found for Seed ID: {sid}')
  52. def generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds,proto):
  53. mmids = [e.mmid for e in need_keys]
  54. sids = remove_dups((i.sid for i in mmids),quiet=True)
  55. cfg._util.vmsg(f"Need seed{suf(sids)}: {' '.join(sids)}")
  56. def gen_kals():
  57. for sid in sids:
  58. # Returns only if seed is found
  59. seed = get_seed_for_seed_id(sid,infiles,saved_seeds)
  60. for id_str in MMGenAddrType.mmtypes:
  61. idx_list = [i.idx for i in mmids if i.sid == sid and i.mmtype == id_str]
  62. if idx_list:
  63. yield KeyAddrList(
  64. cfg = cfg,
  65. proto = proto,
  66. seed = seed,
  67. addr_idxs = AddrIdxList(idx_list=idx_list),
  68. mmtype = MMGenAddrType(proto,id_str),
  69. skip_chksum = True )
  70. return MMGenList(gen_kals())
  71. def add_keys(tx,src,infiles=None,saved_seeds=None,keyaddr_list=None):
  72. need_keys = [e for e in getattr(tx,src) if e.mmid and not e.have_wif]
  73. if not need_keys:
  74. return []
  75. desc,src_desc = (
  76. ('key-address file','From key-address file:') if keyaddr_list else
  77. ('seed(s)','Generated from seed:') )
  78. cfg._util.qmsg(f'Checking {gc.proj_name} -> {tx.proto.coin} address mappings for {src} (from {desc})')
  79. d = (
  80. MMGenList([keyaddr_list]) if keyaddr_list else
  81. generate_kals_for_mmgen_addrs(need_keys,infiles,saved_seeds,tx.proto) )
  82. new_keys = []
  83. for e in need_keys:
  84. for kal in d:
  85. for f in kal.data:
  86. mmid = f'{kal.al_id}:{f.idx}'
  87. if mmid == e.mmid:
  88. if f.addr == e.addr:
  89. e.have_wif = True
  90. if src == 'inputs':
  91. new_keys.append(f)
  92. else:
  93. die(3,fmt(f"""
  94. {gc.proj_name} -> {tx.proto.coin} address mappings differ!
  95. {src_desc:<23} {mmid} -> {f.addr}
  96. {'tx file:':<23} {e.mmid} -> {e.addr}
  97. """).strip())
  98. if new_keys:
  99. cfg._util.vmsg(f'Added {len(new_keys)} wif key{suf(new_keys)} from {desc}')
  100. return new_keys
  101. def _pop_matching_fns(args,cmplist): # strips found args
  102. return list(reversed([args.pop(args.index(a)) for a in reversed(args) if get_extension(a) in cmplist]))
  103. def get_tx_files(cfg, args):
  104. from .unsigned import Unsigned, AutomountUnsigned
  105. ret = _pop_matching_fns(args, [(AutomountUnsigned if cfg.autosign else Unsigned).ext])
  106. if not ret:
  107. die(1,'You must specify a raw transaction file!')
  108. return ret
  109. def get_seed_files(cfg,args):
  110. # favor unencrypted seed sources first, as they don't require passwords
  111. ret = _pop_matching_fns( args, get_wallet_extensions('unenc') )
  112. from ..filename import find_file_in_dir
  113. wf = find_file_in_dir(get_wallet_cls('mmgen'),cfg.data_dir) # Make this the first encrypted ss in the list
  114. if wf:
  115. ret.append(wf)
  116. ret += _pop_matching_fns( args, get_wallet_extensions('enc') )
  117. if not (ret or cfg.mmgen_keys_from_file or cfg.keys_from_file): # or cfg.use_wallet_dat
  118. die(1,'You must specify a seed or key source!')
  119. return ret
  120. def get_keyaddrlist(cfg,proto):
  121. if cfg.mmgen_keys_from_file:
  122. return KeyAddrList( cfg, proto, cfg.mmgen_keys_from_file )
  123. return None
  124. def get_keylist(cfg):
  125. if cfg.keys_from_file:
  126. from ..fileutil import get_lines_from_file
  127. return get_lines_from_file( cfg, cfg.keys_from_file, 'key-address data', trim_comments=True )
  128. return None
  129. async def txsign(cfg_parm, tx, seed_files, kl, kal, tx_num_str='', passwd_file=None):
  130. keys = MMGenList() # list of AddrListEntry objects
  131. non_mmaddrs = tx.get_non_mmaddrs('inputs')
  132. global cfg, global_passwd_file
  133. cfg = cfg_parm
  134. global_passwd_file = passwd_file
  135. if non_mmaddrs:
  136. tx.check_non_mmgen_inputs(caller='txsign',non_mmaddrs=non_mmaddrs)
  137. tmp = KeyAddrList(
  138. cfg = cfg,
  139. proto = tx.proto,
  140. addrlist = non_mmaddrs,
  141. skip_chksum = True )
  142. if kl:
  143. tmp.add_wifs(kl)
  144. missing = tmp.list_missing('sec')
  145. if missing:
  146. sep = '\n '
  147. die(2,'ERROR: a key file must be supplied for the following non-{} address{}:{}'.format(
  148. gc.proj_name,
  149. suf(missing,'es'),
  150. sep + sep.join(missing) ))
  151. keys += tmp.data
  152. if cfg.mmgen_keys_from_file:
  153. keys += add_keys(tx,'inputs',keyaddr_list=kal)
  154. add_keys(tx,'outputs',keyaddr_list=kal)
  155. keys += add_keys(tx,'inputs',seed_files,saved_seeds)
  156. add_keys(tx,'outputs',seed_files,saved_seeds)
  157. # this (boolean) attr isn't needed in transaction file
  158. tx.delete_attrs('inputs','have_wif')
  159. tx.delete_attrs('outputs','have_wif')
  160. extra_sids = remove_dups(
  161. (s for s in saved_seeds if s not in tx.get_sids('inputs') + tx.get_sids('outputs')),
  162. quiet = True )
  163. if extra_sids:
  164. msg(f"Unused Seed ID{suf(extra_sids)}: {' '.join(extra_sids)}")
  165. return await tx.sign(tx_num_str,keys) # returns signed TX object or False