twctl.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. twctl: Tracking wallet control class for the MMGen suite
  20. """
  21. from .globalvars import g
  22. from .util import msg,dmsg,write_mode,altcoin_subclass
  23. from .base_obj import AsyncInit
  24. from .objmethods import MMGenObject
  25. from .obj import TwComment,get_obj
  26. from .addr import CoinAddr,is_mmgen_id,is_coin_addr
  27. from .rpc import rpc_init
  28. from .tw import TwMMGenID,TwLabel
  29. class TrackingWallet(MMGenObject,metaclass=AsyncInit):
  30. caps = ('rescan','batch')
  31. data_key = 'addresses'
  32. use_tw_file = False
  33. aggressive_sync = False
  34. importing = False
  35. def __new__(cls,proto,*args,**kwargs):
  36. return MMGenObject.__new__(altcoin_subclass(cls,proto,'twctl'))
  37. async def __init__(self,proto,mode='r',token_addr=None):
  38. assert mode in ('r','w','i'), f"{mode!r}: wallet mode must be 'r','w' or 'i'"
  39. if mode == 'i':
  40. self.importing = True
  41. mode = 'w'
  42. if g.debug:
  43. print_stack_trace(f'TW INIT {mode!r} {self!r}')
  44. self.rpc = await rpc_init(proto) # TODO: create on demand - only certain ops require RPC
  45. self.proto = proto
  46. self.mode = mode
  47. self.desc = self.base_desc = f'{self.proto.name} tracking wallet'
  48. if self.use_tw_file:
  49. self.init_from_wallet_file()
  50. else:
  51. self.init_empty()
  52. if self.data['coin'] != self.proto.coin: # TODO remove?
  53. from .exception import WalletFileError
  54. raise WalletFileError(
  55. 'Tracking wallet coin ({}) does not match current coin ({})!'.format(
  56. self.data['coin'],
  57. self.proto.coin ))
  58. self.conv_types(self.data[self.data_key])
  59. self.cur_balances = {} # cache balances to prevent repeated lookups per program invocation
  60. def init_empty(self):
  61. self.data = { 'coin': self.proto.coin, 'addresses': {} }
  62. def init_from_wallet_file(self):
  63. import os,json
  64. tw_dir = (
  65. os.path.join(g.data_dir) if self.proto.coin == 'BTC' else
  66. os.path.join(
  67. g.data_dir_root,
  68. 'altcoins',
  69. self.proto.coin.lower(),
  70. ('' if self.proto.network == 'mainnet' else 'testnet')
  71. ))
  72. self.tw_fn = os.path.join(tw_dir,'tracking-wallet.json')
  73. from .fileutil import check_or_create_dir,get_data_from_file
  74. check_or_create_dir(tw_dir)
  75. try:
  76. self.orig_data = get_data_from_file(self.tw_fn,quiet=True)
  77. self.data = json.loads(self.orig_data)
  78. except:
  79. try: os.stat(self.tw_fn)
  80. except:
  81. self.orig_data = ''
  82. self.init_empty()
  83. self.force_write()
  84. else:
  85. from .exception import WalletFileError
  86. raise WalletFileError(f'File {self.tw_fn!r} exists but does not contain valid json data')
  87. else:
  88. self.upgrade_wallet_maybe()
  89. # ensure that wallet file is written when user exits via KeyboardInterrupt:
  90. if self.mode == 'w':
  91. import atexit
  92. def del_tw(tw):
  93. dmsg(f'Running exit handler del_tw() for {tw!r}')
  94. del tw
  95. atexit.register(del_tw,self)
  96. def __del__(self):
  97. """
  98. TrackingWallet instances opened in write or import mode must be explicitly destroyed
  99. with 'del twctl', 'del twuo.wallet' and the like to ensure the instance is deleted and
  100. wallet is written before global vars are destroyed by the interpreter at shutdown.
  101. Not that this code can only be debugged by examining the program output, as exceptions
  102. are ignored within __del__():
  103. /usr/share/doc/python3.6-doc/html/reference/datamodel.html#object.__del__
  104. Since no exceptions are raised, errors will not be caught by the test suite.
  105. """
  106. if g.debug:
  107. print_stack_trace(f'TW DEL {self!r}')
  108. if getattr(self,'mode',None) == 'w': # mode attr might not exist in this state
  109. self.write()
  110. elif g.debug:
  111. msg('read-only wallet, doing nothing')
  112. def upgrade_wallet_maybe(self):
  113. pass
  114. def conv_types(self,ad):
  115. for k,v in ad.items():
  116. if k not in ('params','coin'):
  117. v['mmid'] = TwMMGenID(self.proto,v['mmid'])
  118. v['comment'] = TwComment(v['comment'])
  119. @property
  120. def data_root(self):
  121. return self.data[self.data_key]
  122. @property
  123. def data_root_desc(self):
  124. return self.data_key
  125. def cache_balance(self,addr,bal,session_cache,data_root,force=False):
  126. if force or addr not in session_cache:
  127. session_cache[addr] = str(bal)
  128. if addr in data_root:
  129. data_root[addr]['balance'] = str(bal)
  130. if self.aggressive_sync:
  131. self.write()
  132. def get_cached_balance(self,addr,session_cache,data_root):
  133. if addr in session_cache:
  134. return self.proto.coin_amt(session_cache[addr])
  135. if not g.cached_balances:
  136. return None
  137. if addr in data_root and 'balance' in data_root[addr]:
  138. return self.proto.coin_amt(data_root[addr]['balance'])
  139. async def get_balance(self,addr,force_rpc=False):
  140. ret = None if force_rpc else self.get_cached_balance(addr,self.cur_balances,self.data_root)
  141. if ret == None:
  142. ret = await self.rpc_get_balance(addr)
  143. self.cache_balance(addr,ret,self.cur_balances,self.data_root)
  144. return ret
  145. async def rpc_get_balance(self,addr):
  146. raise NotImplementedError('not implemented')
  147. @property
  148. def sorted_list(self):
  149. return sorted(
  150. [ { 'addr':x[0],
  151. 'mmid':x[1]['mmid'],
  152. 'comment':x[1]['comment'] }
  153. for x in self.data_root.items() if x[0] not in ('params','coin') ],
  154. key=lambda x: x['mmid'].sort_key+x['addr'] )
  155. @property
  156. def mmid_ordered_dict(self):
  157. return dict((x['mmid'],{'addr':x['addr'],'comment':x['comment']}) for x in self.sorted_list)
  158. @write_mode
  159. async def import_address(self,addr,label,rescan):
  160. return await self.rpc.call('importaddress',addr,label,rescan,timeout=(False,3600)[rescan])
  161. @write_mode
  162. def batch_import_address(self,arg_list):
  163. return self.rpc.batch_call('importaddress',arg_list)
  164. def force_write(self):
  165. mode_save = self.mode
  166. self.mode = 'w'
  167. self.write()
  168. self.mode = mode_save
  169. @write_mode
  170. def write_changed(self,data):
  171. from .fileutil import write_data_to_file
  172. write_data_to_file(
  173. self.tw_fn,
  174. data,
  175. desc = f'{self.base_desc} data',
  176. ask_overwrite = False,
  177. ignore_opt_outdir = True,
  178. quiet = True,
  179. check_data = True,
  180. cmp_data = self.orig_data )
  181. self.orig_data = data
  182. def write(self): # use 'check_data' to check wallet hasn't been altered by another program
  183. if not self.use_tw_file:
  184. dmsg("'use_tw_file' is False, doing nothing")
  185. return
  186. dmsg(f'write(): checking if {self.desc} data has changed')
  187. import json
  188. wdata = json.dumps(self.data)
  189. if self.orig_data != wdata:
  190. if g.debug:
  191. print_stack_trace(f'TW DATA CHANGED {self!r}')
  192. print_diff(self.orig_data,wdata,from_json=True)
  193. self.write_changed(wdata)
  194. elif g.debug:
  195. msg('Data is unchanged\n')
  196. async def is_in_wallet(self,addr):
  197. from .twaddrs import TwAddrList
  198. return addr in (await TwAddrList(self.proto,[],0,True,True,True,wallet=self)).coinaddr_list()
  199. @write_mode
  200. async def set_label(self,coinaddr,lbl):
  201. # bitcoin-{abc,bchn} 'setlabel' RPC is broken, so use old 'importaddress' method to set label
  202. # broken behavior: new label is set OK, but old label gets attached to another address
  203. if 'label_api' in self.rpc.caps and self.proto.coin != 'BCH':
  204. args = ('setlabel',coinaddr,lbl)
  205. else:
  206. # NOTE: this works because importaddress() removes the old account before
  207. # associating the new account with the address.
  208. # RPC args: addr,label,rescan[=true],p2sh[=none]
  209. args = ('importaddress',coinaddr,lbl,False)
  210. try:
  211. return await self.rpc.call(*args)
  212. except Exception as e:
  213. rmsg(e.args[0])
  214. return False
  215. # returns on failure
  216. @write_mode
  217. async def add_label(self,arg1,label='',addr=None,silent=False,on_fail='return'):
  218. assert on_fail in ('return','raise'), 'add_label_chk1'
  219. mmaddr,coinaddr = None,None
  220. if is_coin_addr(self.proto,addr or arg1):
  221. coinaddr = get_obj(CoinAddr,proto=self.proto,addr=addr or arg1)
  222. if is_mmgen_id(self.proto,arg1):
  223. mmaddr = TwMMGenID(self.proto,arg1)
  224. if mmaddr and not coinaddr:
  225. from .addrdata import TwAddrData
  226. coinaddr = (await TwAddrData(self.proto)).mmaddr2coinaddr(mmaddr)
  227. try:
  228. if not is_mmgen_id(self.proto,arg1):
  229. assert coinaddr, f'Invalid coin address for this chain: {arg1}'
  230. assert coinaddr, f'{g.proj_name} address {mmaddr!r} not found in tracking wallet'
  231. assert await self.is_in_wallet(coinaddr), f'Address {coinaddr!r} not found in tracking wallet'
  232. except Exception as e:
  233. msg(str(e))
  234. return False
  235. # Allow for the possibility that BTC addr of MMGen addr was entered.
  236. # Do reverse lookup, so that MMGen addr will not be marked as non-MMGen.
  237. if not mmaddr:
  238. from .addrdata import TwAddrData
  239. mmaddr = (await TwAddrData(proto=self.proto)).coinaddr2mmaddr(coinaddr)
  240. if not mmaddr:
  241. mmaddr = f'{self.proto.base_coin.lower()}:{coinaddr}'
  242. mmaddr = TwMMGenID(self.proto,mmaddr)
  243. cmt = TwComment(label) if on_fail=='raise' else get_obj(TwComment,s=label)
  244. if cmt in (False,None):
  245. return False
  246. lbl_txt = mmaddr + (' ' + cmt if cmt else '')
  247. lbl = (
  248. TwLabel(self.proto,lbl_txt) if on_fail == 'raise' else
  249. get_obj(TwLabel,proto=self.proto,text=lbl_txt) )
  250. if await self.set_label(coinaddr,lbl) == False:
  251. if not silent:
  252. msg( 'Label could not be {}'.format('added' if label else 'removed') )
  253. return False
  254. else:
  255. desc = '{} address {} in tracking wallet'.format(
  256. mmaddr.type.replace('mmg','MMG'),
  257. mmaddr.replace(self.proto.base_coin.lower()+':','') )
  258. if label:
  259. msg(f'Added label {label!r} to {desc}')
  260. else:
  261. msg(f'Removed label from {desc}')
  262. return True
  263. @write_mode
  264. async def remove_label(self,mmaddr):
  265. await self.add_label(mmaddr,'')
  266. @write_mode
  267. async def remove_address(self,addr):
  268. raise NotImplementedError(f'address removal not implemented for coin {self.proto.coin}')