sign.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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, fn=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(src, io_list, infiles=None, saved_seeds=None, *, keyaddr_list=None):
  72. need_keys = [e for e in io_list if e.mmid and not e.have_wif]
  73. if not need_keys:
  74. return []
  75. proto = need_keys[0].proto
  76. if keyaddr_list:
  77. desc = 'key-address file'
  78. src_desc = 'From key-address file:'
  79. d = MMGenList([keyaddr_list])
  80. else:
  81. desc = 'seed(s)'
  82. src_desc = 'Generated from seed:'
  83. d = generate_kals_for_mmgen_addrs(need_keys, infiles, saved_seeds, proto)
  84. cfg._util.qmsg(f'Checking {gc.proj_name} -> {proto.coin} address mappings for {src} (from {desc})')
  85. def gen_keys():
  86. for e in need_keys:
  87. for kal in d:
  88. for f in kal.data:
  89. if mmid := f'{kal.al_id}:{f.idx}' == e.mmid:
  90. if f.addr == e.addr:
  91. e.have_wif = True
  92. if src == 'inputs':
  93. yield f
  94. else:
  95. die(3, fmt(f"""
  96. {gc.proj_name} -> {proto.coin} address mappings differ!
  97. {src_desc:<23} {mmid} -> {f.addr}
  98. {'tx file:':<23} {e.mmid} -> {e.addr}
  99. """).strip())
  100. if new_keys := list(gen_keys()):
  101. cfg._util.vmsg(f'Added {len(new_keys)} wif key{suf(new_keys)} from {desc}')
  102. return new_keys
  103. def _pop_matching_fns(args, cmplist): # strips found args
  104. return list(reversed([args.pop(args.index(a)) for a in reversed(args) if get_extension(a) in cmplist]))
  105. def get_tx_files(cfg, args):
  106. from .unsigned import Unsigned, AutomountUnsigned
  107. ret = _pop_matching_fns(args, [(AutomountUnsigned if cfg.autosign else Unsigned).ext])
  108. if not ret:
  109. die(1, 'You must specify a raw transaction file!')
  110. return ret
  111. def get_seed_files(cfg, args, *, ignore_dfl_wallet=False, empty_ok=False):
  112. # favor unencrypted seed sources first, as they don't require passwords
  113. ret = _pop_matching_fns(args, get_wallet_extensions('unenc'))
  114. from ..filename import find_file_in_dir
  115. if not ignore_dfl_wallet: # Make this the first encrypted ss in the list
  116. if wf := find_file_in_dir(get_wallet_cls('mmgen'), cfg.data_dir):
  117. ret.append(wf)
  118. ret += _pop_matching_fns(args, get_wallet_extensions('enc'))
  119. if not (ret or empty_ok or cfg.mmgen_keys_from_file or cfg.keys_from_file): # or cfg.use_wallet_dat
  120. die(1, 'You must specify a seed or key source!')
  121. return ret
  122. def get_keyaddrlist(cfg, proto):
  123. if cfg.mmgen_keys_from_file:
  124. return KeyAddrList(cfg, proto, infile=cfg.mmgen_keys_from_file)
  125. return None
  126. def get_keylist(cfg):
  127. if cfg.keys_from_file:
  128. from ..fileutil import get_lines_from_file
  129. return get_lines_from_file(cfg, cfg.keys_from_file, desc='key-address data', trim_comments=True)
  130. return None
  131. async def txsign(cfg_parm, tx, seed_files, kl, kal, *, tx_num_str='', passwd_file=None):
  132. keys = MMGenList() # list of AddrListEntry objects
  133. non_mmaddrs = tx.get_non_mmaddrs('inputs')
  134. global cfg, global_passwd_file
  135. cfg = cfg_parm
  136. global_passwd_file = passwd_file
  137. if non_mmaddrs:
  138. tx.check_non_mmgen_inputs(caller='txsign', non_mmaddrs=non_mmaddrs)
  139. tmp = KeyAddrList(
  140. cfg = cfg,
  141. proto = tx.proto,
  142. addrlist = non_mmaddrs,
  143. skip_chksum = True)
  144. if kl:
  145. tmp.add_wifs(kl)
  146. missing = tmp.list_missing('sec')
  147. if missing:
  148. sep = '\n '
  149. die(2, 'ERROR: a key file must be supplied for the following non-{} address{}:{}'.format(
  150. gc.proj_name,
  151. suf(missing, 'es'),
  152. sep + sep.join(missing)))
  153. keys += tmp.data
  154. memo_output = tx.check_swap_memo() # do this for non-swap transactions too!
  155. if cfg.mmgen_keys_from_file:
  156. keys += add_keys('inputs', tx.inputs, keyaddr_list=kal)
  157. add_keys('outputs', tx.outputs, keyaddr_list=kal)
  158. if memo_output:
  159. add_keys('swap destination address', [memo_output], keyaddr_list=kal)
  160. keys += add_keys('inputs', tx.inputs, seed_files, saved_seeds)
  161. add_keys('outputs', tx.outputs, seed_files, saved_seeds)
  162. if memo_output:
  163. add_keys('swap destination address', [memo_output], seed_files, saved_seeds)
  164. # this (boolean) attr isn't needed in transaction file
  165. tx.delete_attrs('inputs', 'have_wif')
  166. tx.delete_attrs('outputs', 'have_wif')
  167. extra_sids = remove_dups(
  168. (s for s in saved_seeds if s not in tx.get_sids('inputs') + tx.get_sids('outputs')),
  169. quiet = True)
  170. if extra_sids:
  171. msg(f"Unused Seed ID{suf(extra_sids)}: {' '.join(extra_sids)}")
  172. return await tx.sign(tx_num_str, keys) # returns signed TX object or False