addresses.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen
  9. # https://gitlab.com/mmgen/mmgen
  10. """
  11. tw.addresses: Tracking wallet listaddresses class for the MMGen suite
  12. """
  13. from ..util import suf
  14. from ..objmethods import MMGenObject
  15. from ..obj import MMGenListItem,ImmutableAttr,ListItemAttr,TwComment,NonNegativeInt
  16. from ..addr import CoinAddr,MMGenID
  17. from ..color import red,green
  18. from .view import TwView
  19. from .shared import TwMMGenID
  20. class TwAddresses(TwView):
  21. hdr_lbl = 'tracking wallet addresses'
  22. desc = 'address list'
  23. item_desc = 'address'
  24. sort_key = 'twmmid'
  25. update_widths_on_age_toggle = True
  26. print_output_types = ('detail',)
  27. filters = ('showempty','showused','all_labels')
  28. showcoinaddrs = True
  29. showempty = True
  30. showused = 1 # tristate: 0:no, 1:yes, 2:all
  31. all_labels = False
  32. no_data_errmsg = 'No addresses in tracking wallet!'
  33. mod_subpath = 'tw.addresses'
  34. class display_type(TwView.display_type):
  35. class squeezed(TwView.display_type.squeezed):
  36. cols = ('num','mmid','used','addr','comment','amt','date')
  37. class detail(TwView.display_type.detail):
  38. cols = ('num','mmid','used','addr','comment','amt','block','date_time')
  39. class TwAddress(MMGenListItem):
  40. valid_attrs = {'twmmid','addr','al_id','confs','comment','amt','recvd','date','skip'}
  41. invalid_attrs = {'proto'}
  42. twmmid = ImmutableAttr(TwMMGenID,include_proto=True) # contains confs,txid(unused),date(unused),al_id
  43. addr = ImmutableAttr(CoinAddr,include_proto=True)
  44. al_id = ImmutableAttr(str) # set to '_' for non-MMGen addresses
  45. confs = ImmutableAttr(int,typeconv=False)
  46. comment = ListItemAttr(TwComment,reassign_ok=True)
  47. amt = ImmutableAttr(None)
  48. recvd = ImmutableAttr(None)
  49. date = ListItemAttr(int,typeconv=False,reassign_ok=True)
  50. skip = ListItemAttr(str,typeconv=False,reassign_ok=True)
  51. def __init__(self,proto,**kwargs):
  52. self.__dict__['proto'] = proto
  53. MMGenListItem.__init__(self,**kwargs)
  54. class conv_funcs:
  55. def amt(self,value):
  56. return self.proto.coin_amt(value)
  57. def recvd(self,value):
  58. return self.proto.coin_amt(value)
  59. @property
  60. def coinaddr_list(self):
  61. return [d.addr for d in self.data]
  62. async def __init__(self,proto,minconf=1,mmgen_addrs='',get_data=False):
  63. await super().__init__(proto)
  64. self.minconf = NonNegativeInt(minconf)
  65. if mmgen_addrs:
  66. a = mmgen_addrs.rsplit(':',1)
  67. if len(a) != 2:
  68. from ..util import die
  69. die(1,
  70. f'{mmgen_addrs}: invalid address list argument ' +
  71. '(must be in form <seed ID>:[<type>:]<idx list>)' )
  72. from ..addrlist import AddrIdxList
  73. self.usr_addr_list = [MMGenID(self.proto,f'{a[0]}:{i}') for i in AddrIdxList(a[1])]
  74. else:
  75. self.usr_addr_list = []
  76. if get_data:
  77. await self.get_data()
  78. @property
  79. def no_rpcdata_errmsg(self):
  80. return 'No addresses {}found!'.format(
  81. f'with {self.minconf} confirmations ' if self.minconf else '')
  82. async def gen_data(self,rpc_data,lbl_id):
  83. return (
  84. self.TwAddress(
  85. self.proto,
  86. twmmid = twmmid,
  87. addr = data['addr'],
  88. al_id = getattr(twmmid.obj,'al_id','_'),
  89. confs = data['confs'],
  90. comment = data['lbl'].comment,
  91. amt = data['amt'],
  92. recvd = data['recvd'],
  93. date = 0,
  94. skip = '' )
  95. for twmmid,data in rpc_data.items()
  96. )
  97. def filter_data(self):
  98. if self.usr_addr_list:
  99. return (d for d in self.data if d.twmmid.obj in self.usr_addr_list)
  100. else:
  101. return (d for d in self.data if
  102. (self.all_labels and d.comment) or
  103. (self.showused == 2 and d.recvd) or
  104. (not (d.recvd and not self.showused) and (d.amt or self.showempty))
  105. )
  106. def get_column_widths(self,data,wide=False):
  107. return self.compute_column_widths(
  108. widths = { # fixed cols
  109. 'num': max(2,len(str(len(data)))+1),
  110. 'mmid': max(len(d.twmmid.disp) for d in data),
  111. 'used': 4,
  112. 'amt': self.amt_widths['amt'],
  113. 'date': self.age_w if self.has_age else 0,
  114. 'block': self.age_col_params['block'][0] if wide and self.has_age else 0,
  115. 'date_time': self.age_col_params['date_time'][0] if wide and self.has_age else 0,
  116. 'spc': 7, # 6 spaces between cols + 1 leading space in fs
  117. },
  118. maxws = { # expandable cols
  119. 'addr': max(len(d.addr) for d in data) if self.showcoinaddrs else 0,
  120. 'comment': max(d.comment.screen_width for d in data),
  121. },
  122. minws = {
  123. 'addr': 12 if self.showcoinaddrs else 0,
  124. 'comment': len('Comment'),
  125. },
  126. maxws_nice = {'addr': 18},
  127. wide = wide,
  128. )
  129. def subheader(self,color):
  130. if self.minconf:
  131. return f'Displaying balances with at least {self.minconf} confirmation{suf(self.minconf)}\n'
  132. else:
  133. return ''
  134. def gen_squeezed_display(self,data,cw,hdr_fs,fs,color):
  135. yield hdr_fs.format(
  136. n = '',
  137. m = 'MMGenID',
  138. u = 'Used',
  139. a = 'Address',
  140. c = 'Comment',
  141. A = 'Balance',
  142. d = self.age_hdr )
  143. yes,no = (red('Yes '),green('No ')) if color else ('Yes ','No ')
  144. id_save = data[0].al_id
  145. for n,d in enumerate(data,1):
  146. if id_save != d.al_id:
  147. id_save = d.al_id
  148. yield ''
  149. yield fs.format(
  150. n = str(n) + ')',
  151. m = d.twmmid.fmt( width=cw.mmid, color=color ),
  152. u = yes if d.recvd else no,
  153. a = d.addr.fmt( color=color, width=cw.addr ),
  154. c = d.comment.fmt( width=cw.comment, color=color, nullrepl='-' ),
  155. A = d.amt.fmt( color=color, iwidth=cw.iwidth, prec=self.disp_prec ),
  156. d = self.age_disp( d, self.age_fmt )
  157. )
  158. def gen_detail_display(self,data,cw,hdr_fs,fs,color):
  159. yield hdr_fs.format(
  160. n = '',
  161. m = 'MMGenID',
  162. u = 'Used',
  163. a = 'Address',
  164. c = 'Comment',
  165. A = 'Balance',
  166. b = 'Block',
  167. D = 'Date/Time' )
  168. yes,no = (red('Yes '),green('No ')) if color else ('Yes ','No ')
  169. id_save = data[0].al_id
  170. for n,d in enumerate(data,1):
  171. if id_save != d.al_id:
  172. id_save = d.al_id
  173. yield ''
  174. yield fs.format(
  175. n = str(n) + ')',
  176. m = d.twmmid.fmt( width=cw.mmid, color=color ),
  177. u = yes if d.recvd else no,
  178. a = d.addr.fmt( color=color, width=cw.addr ),
  179. c = d.comment.fmt( width=cw.comment, color=color, nullrepl='-' ),
  180. A = d.amt.fmt( color=color, iwidth=cw.iwidth, prec=self.disp_prec ),
  181. b = self.age_disp( d, 'block' ),
  182. D = self.age_disp( d, 'date_time' ))
  183. async def set_dates(self,addrs):
  184. if not self.dates_set:
  185. bc = self.rpc.blockcount + 1
  186. caddrs = [addr for addr in addrs if addr.confs]
  187. hashes = await self.rpc.gathered_call('getblockhash',[(n,) for n in [bc - a.confs for a in caddrs]])
  188. dates = [d['time'] for d in await self.rpc.gathered_call('getblockheader',[(h,) for h in hashes])]
  189. for idx,addr in enumerate(caddrs):
  190. addr.date = dates[idx]
  191. self.dates_set = True
  192. sort_disp = {
  193. 'age': 'AddrListID+Age',
  194. 'amt': 'AddrListID+Amt',
  195. 'twmmid': 'MMGenID',
  196. }
  197. sort_funcs = {
  198. 'age': lambda d: '{}_{}_{}'.format(
  199. d.al_id,
  200. # Hack, but OK for the foreseeable future:
  201. ('{:>012}'.format(1_000_000_000 - d.confs) if d.confs else '_'),
  202. d.twmmid.sort_key),
  203. 'amt': lambda d: '{}_{}'.format(d.al_id,d.amt),
  204. 'twmmid': lambda d: d.twmmid.sort_key,
  205. }
  206. @property
  207. def dump_fn_pfx(self):
  208. return 'listaddresses' + (f'-minconf-{self.minconf}' if self.minconf else '')
  209. def is_used(self,coinaddr):
  210. for e in self.data:
  211. if e.addr == coinaddr:
  212. return bool(e.recvd)
  213. else: # addr not in tracking wallet
  214. return None
  215. def get_change_address(self,al_id):
  216. """
  217. Get lowest-indexed unused address in tracking wallet for requested AddrListID.
  218. Return values on failure:
  219. None: no addresses in wallet with requested AddrListID
  220. False: no unused addresses in wallet with requested AddrListID
  221. """
  222. def get_start():
  223. """
  224. bisecting algorithm to find first entry with requested al_id
  225. Since 'btc' > 'F' and pre_target sorts below the first twmmid of the al_id
  226. stringwise, we can just search on raw twmmids.
  227. """
  228. pre_target = al_id + ':0'
  229. bot = 0
  230. top = len(data) - 1
  231. n = top >> 1
  232. while True:
  233. if bot == top:
  234. return bot if data[bot].al_id == al_id else None
  235. if data[n].twmmid < pre_target:
  236. bot = n + 1
  237. else:
  238. top = n
  239. n = (top + bot) >> 1
  240. self.reverse = False
  241. self.do_sort('twmmid')
  242. data = self.data
  243. start = get_start()
  244. if start is not None:
  245. for d in data[start:]:
  246. if d.al_id == al_id:
  247. if not d.recvd:
  248. return d
  249. else:
  250. return False
  251. class action(TwView.action):
  252. def s_amt(self,parent):
  253. parent.do_sort('amt')
  254. def d_showempty(self,parent):
  255. parent.showempty = not parent.showempty
  256. def d_showused(self,parent):
  257. parent.showused = (parent.showused + 1) % 3
  258. def d_all_labels(self,parent):
  259. parent.all_labels = not parent.all_labels