txsign.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. txsign: Sign a transaction generated by 'mmgen-txcreate'
  20. """
  21. from .common import *
  22. from .addr import AddrIdxList,KeyAddrList
  23. from .obj import MMGenAddrType,MMGenList
  24. from .wallet import Wallet,WalletUnenc,WalletEnc,MMGenWallet
  25. from .tx import MMGenTX
  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_and_return(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. ret = _pop_and_return(args,[MMGenTX.Unsigned.ext])
  102. if not ret:
  103. die(1,'You must specify a raw transaction file!')
  104. return ret
  105. def get_seed_files(opt,args):
  106. # favor unencrypted seed sources first, as they don't require passwords
  107. u,e = WalletUnenc,WalletEnc
  108. ret = _pop_and_return(args,u.get_extensions())
  109. from .filename import find_file_in_dir
  110. wf = find_file_in_dir(MMGenWallet,g.data_dir) # Make this the first encrypted ss in the list
  111. if wf: ret.append(wf)
  112. ret += _pop_and_return(args,e.get_extensions())
  113. if not (ret or opt.mmgen_keys_from_file or opt.keys_from_file): # or opt.use_wallet_dat
  114. die(1,'You must specify a seed or key source!')
  115. return ret
  116. def get_keyaddrlist(proto,opt):
  117. if opt.mmgen_keys_from_file:
  118. return KeyAddrList(proto,opt.mmgen_keys_from_file)
  119. return None
  120. def get_keylist(proto,opt):
  121. if opt.keys_from_file:
  122. return get_lines_from_file(opt.keys_from_file,'key-address data',trim_comments=True)
  123. return None
  124. async def txsign(tx,seed_files,kl,kal,tx_num_str=''):
  125. keys = MMGenList() # list of AddrListEntry objects
  126. non_mmaddrs = tx.get_non_mmaddrs('inputs')
  127. if non_mmaddrs:
  128. tx.check_non_mmgen_inputs(caller='txsign',non_mmaddrs=non_mmaddrs)
  129. tmp = KeyAddrList(
  130. proto = tx.proto,
  131. addrlist = non_mmaddrs,
  132. skip_chksum = True )
  133. if kl:
  134. tmp.add_wifs(kl)
  135. missing = tmp.list_missing('sec')
  136. if missing:
  137. sep = '\n '
  138. die(2,'ERROR: a key file must be supplied for the following non-{} address{}:{}'.format(
  139. g.proj_name,
  140. suf(missing,'es'),
  141. sep + sep.join(missing) ))
  142. keys += tmp.data
  143. if opt.mmgen_keys_from_file:
  144. keys += add_keys(tx,'inputs',keyaddr_list=kal)
  145. add_keys(tx,'outputs',keyaddr_list=kal)
  146. keys += add_keys(tx,'inputs',seed_files,saved_seeds)
  147. add_keys(tx,'outputs',seed_files,saved_seeds)
  148. # this (boolean) attr isn't needed in transaction file
  149. tx.delete_attrs('inputs','have_wif')
  150. tx.delete_attrs('outputs','have_wif')
  151. extra_sids = remove_dups(
  152. (s for s in saved_seeds if s not in tx.get_sids('inputs') + tx.get_sids('outputs')),
  153. quiet = True )
  154. if extra_sids:
  155. msg(f"Unused Seed ID{suf(extra_sids)}: {' '.join(extra_sids)}")
  156. return await tx.sign(tx_num_str,keys) # returns signed TX object or False