unspent.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 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.unspent: Tracking wallet unspent outputs class for the MMGen suite
  20. """
  21. from ..util import msg, suf
  22. from ..obj import (
  23. ImmutableAttr,
  24. ListItemAttr,
  25. MMGenListItem,
  26. TwComment,
  27. CoinTxID,
  28. NonNegativeInt)
  29. from ..addr import CoinAddr, MoneroIdx
  30. from ..amt import CoinAmtChk
  31. from .shared import TwMMGenID, TwLabel, get_tw_label
  32. from .view import TwView
  33. class TwUnspentOutputs(TwView):
  34. has_age = False
  35. show_mmid = True
  36. hdr_lbl = 'tracked addresses'
  37. desc = 'address balances'
  38. item_desc = 'address'
  39. item_desc_pl = 'addresses'
  40. no_rpcdata_errmsg = """
  41. No spendable outputs found! Import addresses with balances into your
  42. watch-only wallet using 'mmgen-addrimport' and then re-run this program.
  43. """
  44. update_widths_on_age_toggle = False
  45. print_output_types = ('detail',)
  46. mod_subpath = 'tw.unspent'
  47. dump_fn_pfx = 'balances'
  48. prompt_fs_in = [
  49. 'Sort options: [a]mount, a[d]dr, [M]mgen addr, [r]everse',
  50. 'Display options: show [m]mgen addr, r[e]draw screen',
  51. 'View/Print: pager [v]iew, [w]ide pager view, [p]rint to file{s}',
  52. 'Actions: [q]uit menu, [D]elete addr, add [l]abel, [R]efresh balance:']
  53. key_mappings = {
  54. 'a':'s_amt',
  55. 'd':'s_addr',
  56. 'r':'s_reverse',
  57. 'M':'s_twmmid',
  58. 'm':'d_mmid',
  59. 'e':'d_redraw',
  60. 'p':'a_print_detail',
  61. 'v':'a_view',
  62. 'w':'a_view_detail',
  63. 'l':'i_comment_add'}
  64. extra_key_mappings = {
  65. 'D':'i_addr_delete',
  66. 'R':'i_balance_refresh'}
  67. disp_spc = 3
  68. vout_w = 0
  69. class display_type(TwView.display_type):
  70. class squeezed(TwView.display_type.squeezed):
  71. cols = ('num', 'addr', 'mmid', 'comment', 'amt', 'amt2')
  72. class detail(TwView.display_type.detail):
  73. cols = ('num', 'addr', 'mmid', 'amt', 'amt2', 'comment')
  74. class MMGenTwUnspentOutput(MMGenListItem):
  75. valid_attrs = {'txid', 'vout', 'amt', 'amt2', 'comment', 'twmmid', 'addr', 'confs', 'skip'}
  76. invalid_attrs = {'proto'}
  77. txid = ListItemAttr(CoinTxID)
  78. vout = ListItemAttr(NonNegativeInt)
  79. amt = ImmutableAttr(CoinAmtChk, include_proto=True)
  80. amt2 = ListItemAttr(CoinAmtChk, include_proto=True) # the ETH balance for token account
  81. comment = ListItemAttr(TwComment, reassign_ok=True)
  82. twmmid = ImmutableAttr(TwMMGenID, include_proto=True)
  83. addr = ImmutableAttr(CoinAddr, include_proto=True)
  84. confs = ImmutableAttr(int, typeconv=False)
  85. skip = ListItemAttr(str, typeconv=False, reassign_ok=True)
  86. def __init__(self, proto, **kwargs):
  87. self.__dict__['proto'] = proto
  88. MMGenListItem.__init__(self, **kwargs)
  89. async def __init__(self, cfg, proto, *, minconf=1, addrs=[]):
  90. await super().__init__(cfg, proto)
  91. self.minconf = NonNegativeInt(minconf)
  92. self.addrs = addrs
  93. from ..cfg import gc
  94. self.min_cols = gc.min_screen_width
  95. @property
  96. def total(self):
  97. return sum(i.amt for i in self.data)
  98. def gen_data(self, rpc_data, lbl_id):
  99. for o in rpc_data:
  100. if not lbl_id in o:
  101. continue # coinbase outputs have no account field
  102. l = get_tw_label(self.proto, o[lbl_id])
  103. if l:
  104. if not 'amt' in o:
  105. o['amt'] = self.proto.coin_amt(o['amount'])
  106. o.update({
  107. 'twmmid': l.mmid,
  108. 'comment': l.comment or '',
  109. 'addr': CoinAddr(self.proto, o['address']),
  110. 'confs': o['confirmations'],
  111. 'skip': ''})
  112. yield self.MMGenTwUnspentOutput(
  113. self.proto,
  114. **{k: v for k, v in o.items() if k in self.MMGenTwUnspentOutput.valid_attrs})
  115. async def get_rpc_data(self):
  116. wl = self.twctl.sorted_list
  117. minconf = int(self.minconf)
  118. block = self.twctl.rpc.get_block_from_minconf(minconf)
  119. if self.addrs:
  120. wl = [d for d in wl if d['addr'] in self.addrs]
  121. return [{
  122. 'account': TwLabel(self.proto, d['mmid']+' '+d['comment']),
  123. 'address': d['addr'],
  124. 'amt': await self.twctl.get_balance(d['addr'], block=block),
  125. 'confirmations': minconf,
  126. } for d in wl]
  127. def get_disp_data(self):
  128. for d in self.data:
  129. d.skip = ''
  130. if self.group and (e := self.sort_key) in self.groupable:
  131. data = self.data
  132. skip = self.groupable[e]
  133. for i in range(len(data) - 1):
  134. if getattr(data[i], e) == getattr(data[i + 1], e):
  135. data[i + 1].skip = skip
  136. return self.data
  137. def get_column_widths(self, data, *, wide, interactive):
  138. show_mmid = self.show_mmid or wide
  139. return self.compute_column_widths(
  140. widths = { # fixed cols
  141. 'num': max(2, len(str(len(data)))+1),
  142. 'txid': 0,
  143. 'vout': self.vout_w,
  144. 'mmid': max(len(d.twmmid.disp) for d in data) if show_mmid else 0,
  145. 'amt': self.amt_widths['amt'],
  146. 'amt2': self.amt_widths.get('amt2', 0),
  147. 'block': self.age_col_params['block'][0] if wide else 0,
  148. 'date_time': self.age_col_params['date_time'][0] if wide else 0,
  149. 'addr_idx': MoneroIdx.max_digits,
  150. 'acct_idx': MoneroIdx.max_digits,
  151. 'date': self.age_w,
  152. 'spc': self.disp_spc + (2 * show_mmid) + self.has_amt2},
  153. maxws = { # expandable cols
  154. 'addr': max(len(d.addr) for d in data),
  155. 'comment': max(d.comment.screen_width for d in data) if show_mmid else 0,
  156. } | self.txid_max_w,
  157. minws = {
  158. 'addr': 10,
  159. 'comment': len('Comment') if show_mmid else 0,
  160. } | self.txid_min_w,
  161. maxws_nice = (
  162. self.nice_addr_w if show_mmid else {}
  163. ) | self.txid_nice_w,
  164. wide = wide,
  165. interactive = interactive)
  166. def squeezed_col_hdr(self, cw, fs, color):
  167. return fs.format(
  168. n = '',
  169. t = 'TxID',
  170. v = 'Vout',
  171. a = 'Address',
  172. m = 'MMGenID',
  173. c = 'Comment',
  174. A = 'Amt({})'.format(self.proto.dcoin),
  175. B = 'Amt({})'.format(self.proto.coin),
  176. d = self.age_hdr)
  177. def detail_col_hdr(self, cw, fs, color):
  178. return fs.format(
  179. n = '',
  180. t = 'TxID',
  181. v = 'Vout',
  182. a = 'Address',
  183. m = 'MMGenID',
  184. A = 'Amt({})'.format(self.proto.dcoin),
  185. B = 'Amt({})'.format(self.proto.coin),
  186. b = 'Block',
  187. D = 'Date/Time',
  188. c = 'Comment')
  189. def gen_squeezed_display(self, data, cw, fs, color, fmt_method):
  190. for n, d in enumerate(data):
  191. yield fs.format(
  192. n = str(n+1) + ')',
  193. t = (d.txid.fmtc('|' + '.'*(cw.txid-1), cw.txid, color=color) if d.skip == 'txid'
  194. else d.txid.truncate(cw.txid, color=color)) if cw.txid else None,
  195. v = ' ' + d.vout.fmt(cw.vout-1, color=color) if cw.vout else None,
  196. a = d.addr.fmtc('|' + '.'*(cw.addr-1), cw.addr, color=color) if d.skip == 'addr'
  197. else d.addr.fmt(self.addr_view_pref, cw.addr, color=color),
  198. m = (d.twmmid.fmtc('.'*cw.mmid, cw.mmid, color=color) if d.skip == 'addr'
  199. else d.twmmid.fmt(cw.mmid, color=color)) if cw.mmid else None,
  200. c = d.comment.fmt2(cw.comment, color=color, nullrepl='-') if cw.comment else None,
  201. A = d.amt.fmt(cw.iwidth, color=color, prec=self.disp_prec),
  202. B = d.amt2.fmt(cw.iwidth2, color=color, prec=self.disp_prec) if cw.amt2 else None,
  203. d = self.age_disp(d, self.age_fmt))
  204. def gen_detail_display(self, data, cw, fs, color, fmt_method):
  205. for n, d in enumerate(data):
  206. yield fs.format(
  207. n = str(n+1) + ')',
  208. t = d.txid.fmt(cw.txid, color=color) if cw.txid else None,
  209. v = ' ' + d.vout.fmt(cw.vout-1, color=color) if cw.vout else None,
  210. a = d.addr.fmt(self.addr_view_pref, cw.addr, color=color),
  211. m = d.twmmid.fmt(cw.mmid, color=color),
  212. A = d.amt.fmt(cw.iwidth, color=color, prec=self.disp_prec),
  213. B = d.amt2.fmt(cw.iwidth2, color=color, prec=self.disp_prec) if cw.amt2 else None,
  214. b = self.age_disp(d, 'block'),
  215. D = self.age_disp(d, 'date_time'),
  216. c = d.comment.fmt2(cw.comment, color=color, nullrepl='-'))
  217. def display_total(self):
  218. msg('\nTotal unspent: {} {} ({} {}{})'.format(
  219. self.total.hl(),
  220. self.proto.dcoin,
  221. len(self.data),
  222. self.item_desc,
  223. suf(self.data)))
  224. async def set_dates(self, us):
  225. if not self.dates_set:
  226. # 'blocktime' differs from 'time', is same as getblockheader['time']
  227. dates = [o.get('blocktime', 0)
  228. for o in await self.rpc.gathered_icall(
  229. 'gettransaction',
  230. [(o.txid, True, False) for o in us])]
  231. for idx, o in enumerate(us):
  232. o.date = dates[idx]
  233. self.dates_set = True
  234. class sort_action(TwView.sort_action):
  235. def s_twmmid(self, parent):
  236. parent.sort_data('twmmid')
  237. parent.show_mmid = True
  238. class display_action(TwView.display_action):
  239. def d_mmid(self, parent):
  240. parent.show_mmid = not parent.show_mmid
  241. def d_group(self, parent):
  242. if parent.groupable:
  243. parent.group = not parent.group