ctl.py 9.9 KB

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