addresses.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 ..base_obj import AsyncInit
  15. from ..objmethods import MMGenObject
  16. from ..obj import MMGenListItem,ImmutableAttr,ListItemAttr,TwComment,NonNegativeInt
  17. from ..rpc import rpc_init
  18. from ..addr import CoinAddr,MMGenID
  19. from ..color import red,green
  20. from .view import TwView,TwMMGenID
  21. class TwAddresses(MMGenObject,TwView,metaclass=AsyncInit):
  22. hdr_lbl = 'tracking wallet addresses'
  23. desc = 'address list'
  24. item_desc = 'address'
  25. txid_w = 64
  26. sort_key = 'twmmid'
  27. update_widths_on_age_toggle = True
  28. print_output_types = ('detail',)
  29. filters = ('showempty','showused','all_labels')
  30. showcoinaddrs = True
  31. showempty = True
  32. showused = 1 # tristate: 0:no, 1:yes, 2:all
  33. all_labels = False
  34. no_data_errmsg = 'No addresses in tracking wallet!'
  35. class display_type(TwView.display_type):
  36. class squeezed(TwView.display_type.squeezed):
  37. cols = ('num','mmid','used','addr','comment','amt','date')
  38. class detail(TwView.display_type.detail):
  39. cols = ('num','mmid','used','addr','comment','amt','block','date_time')
  40. class TwAddress(MMGenListItem):
  41. valid_attrs = {'twmmid','addr','al_id','confs','comment','amt','recvd','date','skip'}
  42. invalid_attrs = {'proto'}
  43. twmmid = ImmutableAttr(TwMMGenID,include_proto=True) # contains confs,txid(unused),date(unused),al_id
  44. addr = ImmutableAttr(CoinAddr,include_proto=True)
  45. al_id = ImmutableAttr(str) # set to '_' for non-MMGen addresses
  46. confs = ImmutableAttr(int,typeconv=False)
  47. comment = ListItemAttr(TwComment,reassign_ok=True)
  48. amt = ImmutableAttr(None)
  49. recvd = ImmutableAttr(None)
  50. date = ListItemAttr(int,typeconv=False,reassign_ok=True)
  51. skip = ListItemAttr(str,typeconv=False,reassign_ok=True)
  52. def __init__(self,proto,**kwargs):
  53. self.__dict__['proto'] = proto
  54. MMGenListItem.__init__(self,**kwargs)
  55. class conv_funcs:
  56. def amt(self,value):
  57. return self.proto.coin_amt(value)
  58. def recvd(self,value):
  59. return self.proto.coin_amt(value)
  60. @property
  61. def coinaddr_list(self):
  62. return [d.addr for d in self.data]
  63. def __new__(cls,proto,*args,**kwargs):
  64. return MMGenObject.__new__(proto.base_proto_subclass(cls,'tw','addresses'))
  65. async def __init__(self,proto,minconf=1,mmgen_addrs='',wallet=None,get_data=False):
  66. self.proto = proto
  67. self.minconf = NonNegativeInt(minconf)
  68. self.usr_addr_list = []
  69. self.rpc = await rpc_init(proto)
  70. from .ctl import TrackingWallet
  71. self.wallet = wallet or await TrackingWallet(proto,mode='w')
  72. if mmgen_addrs:
  73. a = mmgen_addrs.rsplit(':',1)
  74. if len(a) != 2:
  75. from ..util import die
  76. die(1,
  77. f'{mmgen_addrs}: invalid address list argument ' +
  78. '(must be in form <seed ID>:[<type>:]<idx list>)' )
  79. from ..addrlist import AddrIdxList
  80. self.usr_addr_list = [MMGenID(self.proto,f'{a[0]}:{i}') for i in AddrIdxList(a[1])]
  81. if get_data:
  82. await self.get_data()
  83. @property
  84. def no_rpcdata_errmsg(self):
  85. return 'No addresses {}found!'.format(
  86. f'with {self.minconf} confirmations ' if self.minconf else '')
  87. async def gen_data(self,rpc_data,lbl_id):
  88. return (
  89. self.TwAddress(
  90. self.proto,
  91. twmmid = twmmid,
  92. addr = data['addr'],
  93. al_id = getattr(twmmid.obj,'al_id','_'),
  94. confs = data['confs'],
  95. comment = data['lbl'].comment,
  96. amt = data['amt'],
  97. recvd = data['recvd'],
  98. date = 0,
  99. skip = '' )
  100. for twmmid,data in rpc_data.items()
  101. )
  102. def filter_data(self):
  103. if self.usr_addr_list:
  104. return (d for d in self.data if d.twmmid.obj in self.usr_addr_list)
  105. else:
  106. return (d for d in self.data if
  107. (self.all_labels and d.comment) or
  108. (self.showused == 2 and d.recvd) or
  109. (not (d.recvd and not self.showused) and (d.amt or self.showempty))
  110. )
  111. def get_column_widths(self,data,wide=False):
  112. return self.compute_column_widths(
  113. widths = { # fixed cols
  114. 'num': max(2,len(str(len(data)))+1),
  115. 'mmid': max(len(d.twmmid.disp) for d in data),
  116. 'used': 4,
  117. 'amt': self.disp_prec + 5,
  118. 'date': self.age_w if self.has_age else 0,
  119. 'block': self.age_col_params['block'][0] if wide and self.has_age else 0,
  120. 'date_time': self.age_col_params['date_time'][0] if wide and self.has_age else 0,
  121. 'spc': 7, # 6 spaces between cols + 1 leading space in fs
  122. },
  123. maxws = { # expandable cols
  124. 'addr': max(len(d.addr) for d in data) if self.showcoinaddrs else 0,
  125. 'comment': max(d.comment.screen_width for d in data),
  126. },
  127. minws = {
  128. 'addr': 12 if self.showcoinaddrs else 0,
  129. 'comment': len('Comment'),
  130. },
  131. maxws_nice = {'addr': 18},
  132. wide = wide,
  133. )
  134. def subheader(self,color):
  135. if self.minconf:
  136. return f'Displaying balances with at least {self.minconf} confirmation{suf(self.minconf)}\n'
  137. else:
  138. return ''
  139. def gen_squeezed_display(self,data,cw,hdr_fs,fs,color):
  140. yield hdr_fs.format(
  141. n = '',
  142. m = 'MMGenID',
  143. u = 'Used',
  144. a = 'Address',
  145. c = 'Comment',
  146. A = 'Balance',
  147. d = self.age_hdr )
  148. yes,no = (red('Yes '),green('No ')) if color else ('Yes ','No ')
  149. id_save = data[0].al_id
  150. for n,d in enumerate(data,1):
  151. if id_save != d.al_id:
  152. id_save = d.al_id
  153. yield ''
  154. yield fs.format(
  155. n = str(n) + ')',
  156. m = d.twmmid.fmt(width=cw.mmid,color=color),
  157. u = yes if d.recvd else no,
  158. a = d.addr.fmt(color=color,width=cw.addr),
  159. c = d.comment.fmt(width=cw.comment,color=color,nullrepl='-'),
  160. A = d.amt.fmt(color=color,prec=self.disp_prec),
  161. d = self.age_disp( d, self.age_fmt )
  162. )
  163. def gen_detail_display(self,data,cw,hdr_fs,fs,color):
  164. yield hdr_fs.format(
  165. n = '',
  166. m = 'MMGenID',
  167. u = 'Used',
  168. a = 'Address',
  169. c = 'Comment',
  170. A = 'Balance',
  171. b = 'Block',
  172. D = 'Date/Time' ).rstrip()
  173. yes,no = (red('Yes '),green('No ')) if color else ('Yes ','No ')
  174. id_save = data[0].al_id
  175. for n,d in enumerate(data,1):
  176. if id_save != d.al_id:
  177. id_save = d.al_id
  178. yield ''
  179. yield fs.format(
  180. n = str(n) + ')',
  181. m = d.twmmid.fmt(width=cw.mmid,color=color),
  182. u = yes if d.recvd else no,
  183. a = d.addr.fmt(color=color,width=cw.addr),
  184. c = d.comment.fmt(width=cw.comment,color=color,nullrepl='-'),
  185. A = d.amt.fmt(color=color,prec=self.disp_prec),
  186. b = self.age_disp( d, 'block' ),
  187. D = self.age_disp( d, 'date_time' ),
  188. ).rstrip()
  189. async def set_dates(self,addrs):
  190. if not self.dates_set:
  191. bc = self.rpc.blockcount + 1
  192. caddrs = [addr for addr in addrs if addr.confs]
  193. hashes = await self.rpc.gathered_call('getblockhash',[(n,) for n in [bc - a.confs for a in caddrs]])
  194. dates = [d['time'] for d in await self.rpc.gathered_call('getblockheader',[(h,) for h in hashes])]
  195. for idx,addr in enumerate(caddrs):
  196. addr.date = dates[idx]
  197. self.dates_set = True
  198. sort_disp = {
  199. 'age': 'AddrListID+Age',
  200. 'amt': 'AddrListID+Amt',
  201. 'twmmid': 'MMGenID',
  202. }
  203. sort_funcs = {
  204. 'age': lambda d: '{}_{}_{}'.format(
  205. d.al_id,
  206. # Hack, but OK for the foreseeable future:
  207. ('{:>012}'.format(1_000_000_000 - d.confs) if d.confs else '_'),
  208. d.twmmid.sort_key),
  209. 'amt': lambda d: '{}_{}'.format(d.al_id,d.amt),
  210. 'twmmid': lambda d: d.twmmid.sort_key,
  211. }
  212. @property
  213. def dump_fn_pfx(self):
  214. return 'listaddresses' + (f'-minconf-{self.minconf}' if self.minconf else '')
  215. class action(TwView.action):
  216. def s_amt(self,parent):
  217. parent.do_sort('amt')
  218. def d_showempty(self,parent):
  219. parent.showempty = not parent.showempty
  220. def d_showused(self,parent):
  221. parent.showused = (parent.showused + 1) % 3
  222. def d_all_labels(self,parent):
  223. parent.all_labels = not parent.all_labels