ctl.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. tw.ctl: Tracking wallet control class for the MMGen suite
  20. """
  21. import json
  22. from collections import namedtuple
  23. from ..globalvars import g
  24. from ..util import msg,msg_r,qmsg,dmsg,suf,die
  25. from ..base_obj import AsyncInit
  26. from ..objmethods import MMGenObject
  27. from ..obj import TwComment,get_obj
  28. from ..addr import CoinAddr,is_mmgen_id,is_coin_addr
  29. from ..rpc import rpc_init
  30. from .shared import TwMMGenID,TwLabel
  31. addr_info = namedtuple('addr_info',['twmmid','coinaddr'])
  32. # decorator for TwCtl
  33. def write_mode(orig_func):
  34. def f(self,*args,**kwargs):
  35. if self.mode != 'w':
  36. die(1,'{} opened in read-only mode: cannot execute method {}()'.format(
  37. type(self).__name__,
  38. locals()['orig_func'].__name__
  39. ))
  40. return orig_func(self,*args,**kwargs)
  41. return f
  42. class TwCtl(MMGenObject,metaclass=AsyncInit):
  43. caps = ('rescan','batch')
  44. data_key = 'addresses'
  45. use_tw_file = False
  46. aggressive_sync = False
  47. importing = False
  48. def __new__(cls,proto,*args,**kwargs):
  49. return MMGenObject.__new__(proto.base_proto_subclass(cls,'tw.ctl'))
  50. async def __init__(self,proto,mode='r',token_addr=None,rpc_ignore_wallet=False):
  51. assert mode in ('r','w','i'), f"{mode!r}: wallet mode must be 'r','w' or 'i'"
  52. if mode == 'i':
  53. self.importing = True
  54. mode = 'w'
  55. # TODO: create on demand - only certain ops require RPC
  56. self.rpc = await rpc_init( proto, ignore_wallet=rpc_ignore_wallet )
  57. self.proto = proto
  58. self.mode = mode
  59. self.desc = self.base_desc = f'{self.proto.name} tracking wallet'
  60. if self.use_tw_file:
  61. self.init_from_wallet_file()
  62. else:
  63. self.init_empty()
  64. if self.data['coin'] != self.proto.coin: # TODO remove?
  65. die( 'WalletFileError',
  66. 'Tracking wallet coin ({}) does not match current coin ({})!'.format(
  67. self.data['coin'],
  68. self.proto.coin ))
  69. self.conv_types(self.data[self.data_key])
  70. self.cur_balances = {} # cache balances to prevent repeated lookups per program invocation
  71. def init_from_wallet_file(self):
  72. import os
  73. tw_dir = (
  74. os.path.join(g.data_dir) if self.proto.coin == 'BTC' else
  75. os.path.join(
  76. g.data_dir_root,
  77. 'altcoins',
  78. self.proto.coin.lower(),
  79. ('' if self.proto.network == 'mainnet' else 'testnet')
  80. ))
  81. self.tw_fn = os.path.join(tw_dir,'tracking-wallet.json')
  82. from ..fileutil import check_or_create_dir,get_data_from_file
  83. check_or_create_dir(tw_dir)
  84. try:
  85. self.orig_data = get_data_from_file(self.tw_fn,quiet=True)
  86. self.data = json.loads(self.orig_data)
  87. except:
  88. try: os.stat(self.tw_fn)
  89. except:
  90. self.orig_data = ''
  91. self.init_empty()
  92. self.force_write()
  93. else:
  94. die( 'WalletFileError', f'File {self.tw_fn!r} exists but does not contain valid json data' )
  95. else:
  96. self.upgrade_wallet_maybe()
  97. # ensure that wallet file is written when user exits via KeyboardInterrupt:
  98. if self.mode == 'w':
  99. import atexit
  100. def del_twctl(twctl):
  101. dmsg(f'Running exit handler del_twctl() for {twctl!r}')
  102. del twctl
  103. atexit.register(del_twctl,self)
  104. def __del__(self):
  105. """
  106. TwCtl instances opened in write or import mode must be explicitly destroyed with ‘del
  107. twuo.twctl’ and the like to ensure the instance is deleted and wallet is written before
  108. global vars are destroyed by the interpreter at shutdown.
  109. Not that this code can only be debugged by examining the program output, as exceptions
  110. are ignored within __del__():
  111. /usr/share/doc/python3.6-doc/html/reference/datamodel.html#object.__del__
  112. Since no exceptions are raised, errors will not be caught by the test suite.
  113. """
  114. if getattr(self,'mode',None) == 'w': # mode attr might not exist in this state
  115. self.write()
  116. elif g.debug:
  117. msg('read-only wallet, doing nothing')
  118. def conv_types(self,ad):
  119. for k,v in ad.items():
  120. if k not in ('params','coin'):
  121. v['mmid'] = TwMMGenID(self.proto,v['mmid'])
  122. v['comment'] = TwComment(v['comment'])
  123. @property
  124. def data_root(self):
  125. return self.data[self.data_key]
  126. @property
  127. def data_root_desc(self):
  128. return self.data_key
  129. def cache_balance(self,addr,bal,session_cache,data_root,force=False):
  130. if force or addr not in session_cache:
  131. session_cache[addr] = str(bal)
  132. if addr in data_root:
  133. data_root[addr]['balance'] = str(bal)
  134. if self.aggressive_sync:
  135. self.write()
  136. def get_cached_balance(self,addr,session_cache,data_root):
  137. if addr in session_cache:
  138. return self.proto.coin_amt(session_cache[addr])
  139. if not g.cached_balances:
  140. return None
  141. if addr in data_root and 'balance' in data_root[addr]:
  142. return self.proto.coin_amt(data_root[addr]['balance'])
  143. async def get_balance(self,addr,force_rpc=False):
  144. ret = None if force_rpc else self.get_cached_balance(addr,self.cur_balances,self.data_root)
  145. if ret == None:
  146. ret = await self.rpc_get_balance(addr)
  147. self.cache_balance(addr,ret,self.cur_balances,self.data_root)
  148. return ret
  149. def force_write(self):
  150. mode_save = self.mode
  151. self.mode = 'w'
  152. self.write()
  153. self.mode = mode_save
  154. @write_mode
  155. def write_changed(self,data,quiet):
  156. from ..fileutil import write_data_to_file
  157. write_data_to_file(
  158. self.tw_fn,
  159. data,
  160. desc = f'{self.base_desc} data',
  161. ask_overwrite = False,
  162. ignore_opt_outdir = True,
  163. quiet = quiet,
  164. check_data = True, # die if wallet has been altered by another program
  165. cmp_data = self.orig_data )
  166. self.orig_data = data
  167. def write(self,quiet=True):
  168. if not self.use_tw_file:
  169. dmsg("'use_tw_file' is False, doing nothing")
  170. return
  171. dmsg(f'write(): checking if {self.desc} data has changed')
  172. wdata = json.dumps(self.data)
  173. if self.orig_data != wdata:
  174. self.write_changed(wdata,quiet=quiet)
  175. elif g.debug:
  176. msg('Data is unchanged\n')
  177. async def resolve_address(self,addrspec):
  178. twmmid,coinaddr = (None,None)
  179. if is_coin_addr(self.proto,addrspec):
  180. coinaddr = get_obj(CoinAddr,proto=self.proto,addr=addrspec)
  181. elif is_mmgen_id(self.proto,addrspec):
  182. twmmid = TwMMGenID(self.proto,addrspec)
  183. else:
  184. msg(f'{addrspec!r}: invalid address for this network')
  185. return None
  186. from .rpc import TwRPC
  187. pairs = await TwRPC(proto=self.proto,rpc=self.rpc,twctl=self).get_addr_label_pairs(twmmid)
  188. if not pairs:
  189. msg(f'MMGen address {twmmid!r} not found in tracking wallet')
  190. return None
  191. pairs_data = dict((label.mmid,addr) for label,addr in pairs)
  192. if twmmid and not coinaddr:
  193. coinaddr = pairs_data[twmmid]
  194. # Allow for the possibility that BTC addr of MMGen addr was entered.
  195. # Do reverse lookup, so that MMGen addr will not be marked as non-MMGen.
  196. if not twmmid:
  197. for mmid,addr in pairs_data.items():
  198. if coinaddr == addr:
  199. twmmid = mmid
  200. break
  201. else:
  202. msg(f'Coin address {addrspec!r} not found in tracking wallet')
  203. return None
  204. return addr_info(twmmid,coinaddr)
  205. # returns on failure
  206. @write_mode
  207. async def set_comment(self,addrspec,comment='',trusted_coinaddr=None,silent=False):
  208. res = (
  209. addr_info(addrspec,trusted_coinaddr) if trusted_coinaddr
  210. else await self.resolve_address(addrspec) )
  211. if not res:
  212. return False
  213. comment = get_obj(TwComment,s=comment)
  214. if comment == False:
  215. return False
  216. lbl = get_obj(
  217. TwLabel,
  218. proto = self.proto,
  219. text = res.twmmid + (' ' + comment if comment else ''))
  220. if lbl == False:
  221. return False
  222. if await self.set_label(res.coinaddr,lbl):
  223. # redundant paranoia step:
  224. from .rpc import TwRPC
  225. pairs = await TwRPC(proto=self.proto,rpc=self.rpc,twctl=self).get_addr_label_pairs(res.twmmid)
  226. assert pairs[0][0].comment == comment, f'{pairs[0][0].comment!r} != {comment!r}'
  227. desc = '{} address {} in tracking wallet'.format(
  228. res.twmmid.type.replace('mmgen','MMGen'),
  229. res.twmmid.addr.hl() )
  230. if comment:
  231. msg('Added label {} to {}'.format(comment.hl(encl="''"),desc))
  232. else:
  233. msg(f'Removed label from {desc}')
  234. return True
  235. else:
  236. if not silent:
  237. msg( 'Label could not be {}'.format('added' if comment else 'removed') )
  238. return False
  239. @write_mode
  240. async def remove_comment(self,mmaddr):
  241. await self.set_comment(mmaddr,'')
  242. async def import_address_common(self,data,batch=False,gather=False):
  243. async def do_import(address,comment,message):
  244. try:
  245. res = await self.import_address( address, comment )
  246. qmsg(message)
  247. return res
  248. except Exception as e:
  249. die(2,f'\nImport of address {address!r} failed: {e.args[0]!r}')
  250. _d = namedtuple( 'formatted_import_data', data[0]._fields + ('mmid_disp',))
  251. pfx = self.proto.base_coin.lower() + ':'
  252. fdata = [ _d(*d, 'non-MMGen' if d.twmmid.startswith(pfx) else d.twmmid ) for d in data ]
  253. fs = '{:%s}: {:%s} {:%s} - OK' % (
  254. len(str(len(fdata))) * 2 + 1,
  255. max(len(d.addr) for d in fdata),
  256. max(len(d.mmid_disp) for d in fdata) + 2
  257. )
  258. nAddrs = len(data)
  259. out = [( # create list, not generator, so we know data is valid before starting import
  260. CoinAddr( self.proto, d.addr ),
  261. TwLabel( self.proto, d.twmmid + (f' {d.comment}' if d.comment else '') ),
  262. fs.format( f'{n}/{nAddrs}', d.addr, f'({d.mmid_disp})' )
  263. ) for n,d in enumerate(fdata,1)]
  264. if batch:
  265. msg_r(f'Batch importing {len(out)} address{suf(data,"es")}...')
  266. ret = await self.batch_import_address((a,b) for a,b,c in out)
  267. msg(f'done\n{len(ret)} addresses imported')
  268. else:
  269. if gather: # this seems to provide little performance benefit
  270. import asyncio
  271. await asyncio.gather(*(do_import(*d) for d in out))
  272. else:
  273. for d in out:
  274. await do_import(*d)
  275. msg('Address import completed OK')