unspent.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. HexStr,
  28. CoinTxID,
  29. NonNegativeInt)
  30. from ..addr import CoinAddr
  31. from ..amt import CoinAmtChk
  32. from .shared import TwMMGenID, get_tw_label
  33. from .view import TwView
  34. class TwUnspentOutputs(TwView):
  35. class display_type(TwView.display_type):
  36. class squeezed(TwView.display_type.squeezed):
  37. cols = ('num', 'txid', 'vout', 'addr', 'mmid', 'comment', 'amt', 'amt2', 'date')
  38. class detail(TwView.display_type.detail):
  39. cols = ('num', 'txid', 'vout', 'addr', 'mmid', 'amt', 'amt2', 'block', 'date_time', 'comment')
  40. show_mmid = True
  41. no_rpcdata_errmsg = """
  42. No spendable outputs found! Import addresses with balances into your
  43. watch-only wallet using 'mmgen-addrimport' and then re-run this program.
  44. """
  45. update_widths_on_age_toggle = False
  46. print_output_types = ('detail',)
  47. mod_subpath = 'tw.unspent'
  48. class MMGenTwUnspentOutput(MMGenListItem):
  49. txid = ListItemAttr(CoinTxID)
  50. vout = ListItemAttr(NonNegativeInt)
  51. amt = ImmutableAttr(CoinAmtChk, include_proto=True)
  52. amt2 = ListItemAttr(CoinAmtChk, include_proto=True) # the ETH balance for token account
  53. comment = ListItemAttr(TwComment, reassign_ok=True)
  54. twmmid = ImmutableAttr(TwMMGenID, include_proto=True)
  55. addr = ImmutableAttr(CoinAddr, include_proto=True)
  56. confs = ImmutableAttr(int, typeconv=False)
  57. date = ListItemAttr(int, typeconv=False, reassign_ok=True)
  58. scriptPubKey = ImmutableAttr(HexStr)
  59. skip = ListItemAttr(str, typeconv=False, reassign_ok=True)
  60. def __init__(self, proto, **kwargs):
  61. self.__dict__['proto'] = proto
  62. MMGenListItem.__init__(self, **kwargs)
  63. async def __init__(self, cfg, proto, *, minconf=1, addrs=[]):
  64. await super().__init__(cfg, proto)
  65. self.minconf = NonNegativeInt(minconf)
  66. self.addrs = addrs
  67. from ..cfg import gc
  68. self.min_cols = gc.min_screen_width
  69. @property
  70. def total(self):
  71. return sum(i.amt for i in self.data)
  72. def gen_data(self, rpc_data, lbl_id):
  73. for o in rpc_data:
  74. if not lbl_id in o:
  75. continue # coinbase outputs have no account field
  76. l = get_tw_label(self.proto, o[lbl_id])
  77. if l:
  78. if not 'amt' in o:
  79. o['amt'] = self.proto.coin_amt(o['amount'])
  80. o.update({
  81. 'twmmid': l.mmid,
  82. 'comment': l.comment or '',
  83. 'addr': CoinAddr(self.proto, o['address']),
  84. 'confs': o['confirmations']
  85. })
  86. yield self.MMGenTwUnspentOutput(
  87. self.proto,
  88. **{k:v for k, v in o.items() if k in self.MMGenTwUnspentOutput.valid_attrs})
  89. def filter_data(self):
  90. data = self.data.copy()
  91. for d in data:
  92. d.skip = ''
  93. gkeys = {'addr': 'addr', 'twmmid': 'addr', 'txid': 'txid'}
  94. if self.group and self.sort_key in gkeys:
  95. for a, b in [(data[i], data[i+1]) for i in range(len(data)-1)]:
  96. for k in gkeys:
  97. if self.sort_key == k and getattr(a, k) == getattr(b, k):
  98. b.skip = gkeys[k]
  99. return data
  100. def get_column_widths(self, data, *, wide, interactive):
  101. show_mmid = self.show_mmid or wide
  102. # num txid vout addr [mmid] [comment] amt [amt2] date
  103. return self.compute_column_widths(
  104. widths = { # fixed cols
  105. 'num': max(2, len(str(len(data)))+1),
  106. 'vout': 4,
  107. 'mmid': max(len(d.twmmid.disp) for d in data) if show_mmid else 0,
  108. 'amt': self.amt_widths['amt'],
  109. 'amt2': self.amt_widths.get('amt2', 0),
  110. 'block': self.age_col_params['block'][0] if wide else 0,
  111. 'date_time': self.age_col_params['date_time'][0] if wide else 0,
  112. 'date': self.age_w,
  113. 'spc': 7 if show_mmid else 5, # 7(5) spaces in fs
  114. },
  115. maxws = { # expandable cols
  116. 'txid': self.txid_w,
  117. 'addr': max(len(d.addr) for d in data),
  118. 'comment': max(d.comment.screen_width for d in data) if show_mmid else 0,
  119. },
  120. minws = {
  121. 'txid': 7,
  122. 'addr': 10,
  123. 'comment': len('Comment') if show_mmid else 0,
  124. },
  125. maxws_nice = {'txid':12, 'addr':16} if show_mmid else {'txid':12},
  126. wide = wide,
  127. interactive = interactive,
  128. )
  129. def squeezed_col_hdr(self, cw, fs, color):
  130. return fs.format(
  131. n = '',
  132. t = 'TxID',
  133. v = 'Vout',
  134. a = 'Address',
  135. m = 'MMGenID',
  136. c = 'Comment',
  137. A = 'Amt({})'.format(self.proto.dcoin),
  138. B = 'Amt({})'.format(self.proto.coin),
  139. d = self.age_hdr)
  140. def detail_col_hdr(self, cw, fs, color):
  141. return fs.format(
  142. n = '',
  143. t = 'TxID',
  144. v = 'Vout',
  145. a = 'Address',
  146. m = 'MMGenID',
  147. A = 'Amt({})'.format(self.proto.dcoin),
  148. B = 'Amt({})'.format(self.proto.coin),
  149. b = 'Block',
  150. D = 'Date/Time',
  151. c = 'Comment')
  152. def gen_squeezed_display(self, data, cw, fs, color, fmt_method):
  153. for n, d in enumerate(data):
  154. yield fs.format(
  155. n = str(n+1) + ')',
  156. t = (d.txid.fmtc('|' + '.'*(cw.txid-1), cw.txid, color=color) if d.skip == 'txid'
  157. else d.txid.truncate(cw.txid, color=color)) if cw.txid else None,
  158. v = ' ' + d.vout.fmt(cw.vout-1, color=color) if cw.vout else None,
  159. a = d.addr.fmtc('|' + '.'*(cw.addr-1), cw.addr, color=color) if d.skip == 'addr'
  160. else d.addr.fmt(self.addr_view_pref, cw.addr, color=color),
  161. m = (d.twmmid.fmtc('.'*cw.mmid, cw.mmid, color=color) if d.skip == 'addr'
  162. else d.twmmid.fmt(cw.mmid, color=color)) if cw.mmid else None,
  163. c = d.comment.fmt2(cw.comment, color=color, nullrepl='-') if cw.comment else None,
  164. A = d.amt.fmt(cw.iwidth, color=color, prec=self.disp_prec),
  165. B = d.amt2.fmt(cw.iwidth2, color=color, prec=self.disp_prec) if cw.amt2 else None,
  166. d = self.age_disp(d, self.age_fmt),
  167. )
  168. def gen_detail_display(self, data, cw, fs, color, fmt_method):
  169. for n, d in enumerate(data):
  170. yield fs.format(
  171. n = str(n+1) + ')',
  172. t = d.txid.fmt(cw.txid, color=color) if cw.txid else None,
  173. v = ' ' + d.vout.fmt(cw.vout-1, color=color) if cw.vout else None,
  174. a = d.addr.fmt(self.addr_view_pref, cw.addr, color=color),
  175. m = d.twmmid.fmt(cw.mmid, color=color),
  176. A = d.amt.fmt(cw.iwidth, color=color, prec=self.disp_prec),
  177. B = d.amt2.fmt(cw.iwidth2, color=color, prec=self.disp_prec) if cw.amt2 else None,
  178. b = self.age_disp(d, 'block'),
  179. D = self.age_disp(d, 'date_time'),
  180. c = d.comment.fmt2(cw.comment, color=color, nullrepl='-'))
  181. def display_total(self):
  182. msg('\nTotal unspent: {} {} ({} {}{})'.format(
  183. self.total.hl(),
  184. self.proto.dcoin,
  185. len(self.data),
  186. self.item_desc,
  187. suf(self.data)))
  188. async def set_dates(self, us):
  189. if not self.dates_set:
  190. # 'blocktime' differs from 'time', is same as getblockheader['time']
  191. dates = [o.get('blocktime', 0)
  192. for o in await self.rpc.gathered_icall('gettransaction', [(o.txid, True, False) for o in us])]
  193. for idx, o in enumerate(us):
  194. o.date = dates[idx]
  195. self.dates_set = True
  196. class sort_action(TwView.sort_action):
  197. def s_twmmid(self, parent):
  198. parent.do_sort('twmmid')
  199. parent.show_mmid = True
  200. class display_action(TwView.display_action):
  201. def d_mmid(self, parent):
  202. parent.show_mmid = not parent.show_mmid
  203. def d_group(self, parent):
  204. if parent.can_group:
  205. parent.group = not parent.group