txhistory.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 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-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. proto.btc.tw.txhistory: Bitcoin base protocol tracking wallet transaction history class
  12. """
  13. from collections import namedtuple
  14. from ....tw.txhistory import TwTxHistory
  15. from ....tw.shared import get_tw_label,TwMMGenID
  16. from ....addr import CoinAddr
  17. from ....util import msg,msg_r
  18. from ....color import nocolor,red,pink,gray
  19. from ....obj import TwComment,CoinTxID,Int
  20. from .rpc import BitcoinTwRPC
  21. class BitcoinTwTransaction:
  22. def __init__(self,parent,proto,rpc,
  23. idx, # unique numeric identifier of this transaction in listing
  24. unspent_info, # addrs in wallet with balances: { 'mmid': {'addr','comment','amt'} }
  25. mm_map, # all addrs in wallet: ['addr', ['twmmid','comment']]
  26. tx, # the decoded transaction data
  27. wallet_vouts, # list of ints - wallet-related vouts
  28. prevouts, # list of (txid,vout) pairs
  29. prevout_txs # decoded transaction data for prevouts
  30. ):
  31. self.parent = parent
  32. self.proto = proto
  33. self.rpc = rpc
  34. self.idx = idx
  35. self.unspent_info = unspent_info
  36. self.tx = tx
  37. def gen_prevouts_data():
  38. _d = namedtuple('prevout_data',['txid','data'])
  39. for tx in prevout_txs:
  40. for e in prevouts:
  41. if e.txid == tx['txid']:
  42. yield _d( e.txid, tx['vout'][e.vout] )
  43. def gen_wallet_vouts_data():
  44. _d = namedtuple('wallet_vout_data',['txid','data'])
  45. txid = self.tx['txid']
  46. vouts = self.tx['decoded']['vout']
  47. for n in wallet_vouts:
  48. yield _d( txid, vouts[n] )
  49. def gen_vouts_info(data):
  50. _d = namedtuple('vout_info',['txid','coin_addr','twlabel','data'])
  51. def gen():
  52. for d in data:
  53. addr = d.data['scriptPubKey'].get('address') or d.data['scriptPubKey']['addresses'][0]
  54. yield _d(
  55. txid = d.txid,
  56. coin_addr = addr,
  57. twlabel = mm_map[addr] if (addr in mm_map and mm_map[addr].twmmid) else None,
  58. data = d.data )
  59. return sorted(
  60. gen(),
  61. # if address is not MMGen, ignore address and sort by TxID + vout only
  62. key = lambda d: (
  63. (d.twlabel.twmmid.sort_key if d.twlabel and d.twlabel.twmmid.type == 'mmgen' else '')
  64. + '_'
  65. + d.txid
  66. + '{:08d}'.format(d.data['n'])
  67. ))
  68. def gen_all_addrs(src):
  69. for e in self.vouts_info[src]:
  70. if e.twlabel:
  71. mmid = e.twlabel.twmmid
  72. yield (
  73. (mmid if mmid.type == 'mmgen' else mmid.split(':',1)[1]) +
  74. ('*' if mmid in self.unspent_info else '')
  75. )
  76. else:
  77. yield e.coin_addr
  78. def total(data):
  79. return sum(coin_amt(d.data['value']) for d in data)
  80. def get_best_comment():
  81. """
  82. find the most relevant comment for tabular (squeezed) display
  83. """
  84. def vouts_labels(src):
  85. return [ d.twlabel.comment for d in self.vouts_info[src] if d.twlabel and d.twlabel.comment ]
  86. ret = vouts_labels('outputs') or vouts_labels('inputs')
  87. return ret[0] if ret else TwComment('')
  88. coin_amt = self.proto.coin_amt
  89. # 'outputs' refers to wallet-related outputs only
  90. self.vouts_info = {
  91. 'inputs': gen_vouts_info( gen_prevouts_data() ),
  92. 'outputs': gen_vouts_info( gen_wallet_vouts_data() )
  93. }
  94. self.max_addrlen = {
  95. 'inputs': max(len(addr) for addr in gen_all_addrs('inputs')),
  96. 'outputs': max(len(addr) for addr in gen_all_addrs('outputs'))
  97. }
  98. self.inputs_total = total(self.vouts_info['inputs'])
  99. self.outputs_total = sum(coin_amt(i['value']) for i in self.tx['decoded']['vout'])
  100. self.wallet_outputs_total = total(self.vouts_info['outputs'])
  101. self.fee = self.inputs_total - self.outputs_total
  102. self.nOutputs = len(self.tx['decoded']['vout'])
  103. self.confirmations = self.tx['confirmations']
  104. self.comment = get_best_comment()
  105. self.vsize = self.tx['decoded'].get('vsize') or self.tx['decoded']['size']
  106. self.txid = CoinTxID(self.tx['txid'])
  107. # Though 'blocktime' is flagged as an “optional” field, it’s always present for transactions
  108. # that are in the blockchain. However, Bitcoin Core wallet saves a record of broadcast but
  109. # unconfirmed transactions, e.g. replaced transactions, and the 'blocktime' field is missing
  110. # for these, so use 'time' as a fallback.
  111. self.time = self.tx.get('blocktime') or self.tx['time']
  112. self.time_received = self.tx.get('timereceived')
  113. def blockheight_disp(self,color):
  114. return (
  115. # old/altcoin daemons return no 'blockheight' field, so use confirmations instead
  116. Int( self.rpc.blockcount + 1 - self.confirmations ).hl(color=color)
  117. if self.confirmations > 0 else None )
  118. def age_disp(self,age_fmt,width,color):
  119. if age_fmt == 'confs':
  120. ret_str = str(self.confirmations).ljust(width)
  121. return gray(ret_str) if self.confirmations < 0 and color else ret_str
  122. elif age_fmt == 'block':
  123. ret = (self.rpc.blockcount - (abs(self.confirmations) - 1)) * (-1 if self.confirmations < 0 else 1)
  124. ret_str = str(ret).ljust(width)
  125. return gray(ret_str) if ret < 0 and color else ret_str
  126. else:
  127. return self.parent.date_formatter[age_fmt](self.rpc,self.tx.get('blocktime',0))
  128. def txdate_disp(self,age_fmt):
  129. return self.parent.date_formatter[age_fmt](self.rpc,self.time)
  130. def txid_disp(self,color,width=None):
  131. return self.txid.hl(color=color) if width is None else self.txid.truncate(width=width,color=color)
  132. def vouts_list_disp(self, src, color, indent, addr_view_pref):
  133. fs1,fs2 = {
  134. 'inputs': ('{i},{n} {a} {A}', '{i},{n} {a} {A} {l}'),
  135. 'outputs': ( '{n} {a} {A}', '{n} {a} {A} {l}')
  136. }[src]
  137. def gen_output():
  138. for e in self.vouts_info[src]:
  139. mmid = e.twlabel.twmmid if e.twlabel else None
  140. if not mmid:
  141. yield fs1.format(
  142. i = CoinTxID(e.txid).hl(color=color),
  143. n = (nocolor,red)[color](str(e.data['n']).ljust(3)),
  144. a = CoinAddr(self.proto, e.coin_addr).fmt(
  145. addr_view_pref, width=self.max_addrlen[src], color=color),
  146. A = self.proto.coin_amt( e.data['value'] ).fmt(color=color)
  147. ).rstrip()
  148. else:
  149. bal_star,co = ('*','melon') if mmid in self.unspent_info else ('','brown')
  150. addr_out = mmid if mmid.type == 'mmgen' else mmid.split(':',1)[1]
  151. yield fs2.format(
  152. i = CoinTxID(e.txid).hl(color=color),
  153. n = (nocolor,red)[color](str(e.data['n']).ljust(3)),
  154. a = TwMMGenID.hl2(
  155. TwMMGenID,
  156. s = '{:{w}}'.format( addr_out + bal_star, w=self.max_addrlen[src] ),
  157. color = color,
  158. color_override = co ),
  159. A = self.proto.coin_amt( e.data['value'] ).fmt(color=color),
  160. l = e.twlabel.comment.hl(color=color)
  161. ).rstrip()
  162. return f'\n{indent}'.join( gen_output() ).strip()
  163. def vouts_disp(self, src, width, color, addr_view_pref):
  164. def gen_output():
  165. nonlocal space_left
  166. for e in self.vouts_info[src]:
  167. mmid = e.twlabel.twmmid if e.twlabel else None
  168. bal_star,addr_w,co = ('*',16,'melon') if mmid in self.unspent_info else ('',15,'brown')
  169. if not mmid:
  170. if width and space_left < addr_w:
  171. break
  172. yield CoinAddr(self.proto, e.coin_addr).fmt(addr_view_pref, width=addr_w, color=color)
  173. space_left -= addr_w
  174. elif mmid.type == 'mmgen':
  175. mmid_disp = mmid + bal_star
  176. if width and space_left < len(mmid_disp):
  177. break
  178. yield TwMMGenID.hl2( TwMMGenID, s=mmid_disp, color=color, color_override=co )
  179. space_left -= len(mmid_disp)
  180. else:
  181. if width and space_left < addr_w:
  182. break
  183. yield TwMMGenID.hl2(
  184. TwMMGenID,
  185. s = CoinAddr.fmtc( mmid.split(':',1)[1] + bal_star, width=addr_w ),
  186. color = color,
  187. color_override = co )
  188. space_left -= addr_w
  189. space_left -= 1
  190. space_left = width or 0
  191. return ' '.join(gen_output()) + ' ' * (space_left + 1 if width else 0)
  192. def amt_disp(self,show_total_amt):
  193. return (
  194. self.outputs_total if show_total_amt else
  195. self.wallet_outputs_total )
  196. def fee_disp(self,color):
  197. atomic_unit = self.proto.coin_amt.units[0]
  198. return '{} {}'.format(
  199. self.fee.hl(color=color),
  200. (nocolor,pink)[color]('({:,} {}s/byte)'.format(
  201. self.fee.to_unit(atomic_unit) // self.vsize,
  202. atomic_unit )) )
  203. class BitcoinTwTxHistory(TwTxHistory,BitcoinTwRPC):
  204. has_age = True
  205. hdr_lbl = 'transaction history'
  206. desc = 'transaction history'
  207. item_desc = 'transaction'
  208. no_data_errmsg = 'No transactions in tracking wallet!'
  209. prompt_fs_in = [
  210. 'Sort options: [t]xid, [a]mt, total a[m]t, [A]ge, block[n]um, [r]everse',
  211. 'Column options: toggle [D]ays/date/confs/block, tx[i]d, [T]otal amt',
  212. 'View/Print: pager [v]iew, full pager [V]iew, [p]rint, full [P]rint{s}',
  213. 'Filters/Actions: show [u]nconfirmed, [q]uit menu, r[e]draw:']
  214. prompt_fs_repl = {
  215. 'BCH': (1, 'Column options: toggle [D]ate/confs, cas[h]addr, tx[i]d, [T]otal amt')
  216. }
  217. key_mappings = {
  218. 'A':'s_age',
  219. 'n':'s_blockheight',
  220. 'a':'s_amt',
  221. 'm':'s_total_amt',
  222. 't':'s_txid',
  223. 'r':'s_reverse',
  224. 'D':'d_days',
  225. 'e':'d_redraw',
  226. 'u':'d_show_unconfirmed',
  227. 'i':'d_show_txid',
  228. 'T':'d_show_total_amt',
  229. 'v':'a_view',
  230. 'V':'a_view_detail',
  231. 'p':'a_print_squeezed',
  232. 'P':'a_print_detail' }
  233. async def get_rpc_data(self):
  234. blockhash = (
  235. await self.rpc.call( 'getblockhash', self.sinceblock )
  236. if self.sinceblock else '' )
  237. # bitcoin-cli help listsinceblock:
  238. # Arguments:
  239. # 1. blockhash (string, optional) If set, the block hash to list transactions since,
  240. # otherwise list all transactions.
  241. # 2. target_confirmations (numeric, optional, default=1) Return the nth block hash from the main
  242. # chain. e.g. 1 would mean the best block hash. Note: this is not used
  243. # as a filter, but only affects [lastblock] in the return value
  244. # 3. include_watchonly (boolean, optional, default=true for watch-only wallets, otherwise
  245. # false) Include transactions to watch-only addresses
  246. # 4. include_removed (boolean, optional, default=true) Show transactions that were removed
  247. # due to a reorg in the "removed" array (not guaranteed to work on
  248. # pruned nodes)
  249. return (await self.rpc.call('listsinceblock',blockhash,1,True,False))['transactions']
  250. async def gen_data(self,rpc_data,lbl_id):
  251. def gen_parsed_data():
  252. for o in rpc_data:
  253. if lbl_id in o:
  254. l = get_tw_label(self.proto,o[lbl_id])
  255. else:
  256. assert o['category'] == 'send', f"{o['address']}: {o['category']} != 'send'"
  257. l = None
  258. o.update({
  259. 'twmmid': l.mmid if l else None,
  260. 'comment': (l.comment or '') if l else None,
  261. })
  262. yield o
  263. data = list(gen_parsed_data())
  264. if self.cfg.debug_tw:
  265. import json
  266. from ....rpc import json_encoder
  267. def do_json_dump(*data):
  268. nw = f'{self.proto.coin.lower()}-{self.proto.network}'
  269. for d,fn_stem in data:
  270. with open(f'/tmp/{fn_stem}-{nw}.json','w') as fh:
  271. fh.write(json.dumps(d,cls=json_encoder))
  272. _mmp = namedtuple('mmap_datum',['twmmid','comment'])
  273. mm_map = {
  274. i['address']: (
  275. _mmp( TwMMGenID(self.proto,i['twmmid']), TwComment(i['comment']) )
  276. if i['twmmid'] else _mmp(None,None)
  277. )
  278. for i in data }
  279. if self.sinceblock: # mapping data may be incomplete for inputs, so update from 'listlabels'
  280. mm_map.update(
  281. {e.coinaddr: _mmp(e.label.mmid, e.label.comment) if e.label else _mmp(None, None)
  282. for e in await self.get_label_addr_pairs()}
  283. )
  284. msg_r('Getting wallet transactions...')
  285. _wallet_txs = await self.rpc.gathered_icall(
  286. 'gettransaction',
  287. [ (i,True,True) for i in {d['txid'] for d in data} ] )
  288. msg('done')
  289. if not 'decoded' in _wallet_txs[0]:
  290. _decoded_txs = iter(
  291. await self.rpc.gathered_call(
  292. 'decoderawtransaction',
  293. [ (d['hex'],) for d in _wallet_txs ] ))
  294. for tx in _wallet_txs:
  295. tx['decoded'] = next(_decoded_txs)
  296. if self.cfg.debug_tw:
  297. do_json_dump((_wallet_txs, 'wallet-txs'),)
  298. _wip = namedtuple('prevout',['txid','vout'])
  299. txdata = [
  300. {
  301. 'tx': tx,
  302. 'wallet_vouts': sorted({i.vout for i in
  303. [_wip( CoinTxID(d['txid']), d['vout'] ) for d in data]
  304. if i.txid == tx['txid']}),
  305. 'prevouts': [_wip( CoinTxID(vin['txid']), vin['vout'] ) for vin in tx['decoded']['vin']]
  306. }
  307. for tx in _wallet_txs]
  308. _prevout_txids = {i.txid for d in txdata for i in d['prevouts']}
  309. msg_r('Getting input transactions...')
  310. _prevout_txs = await self.rpc.gathered_call('getrawtransaction', [ (i,True) for i in _prevout_txids ])
  311. msg('done')
  312. _prevout_txs_dict = dict(zip(_prevout_txids,_prevout_txs))
  313. for d in txdata:
  314. d['prevout_txs'] = [_prevout_txs_dict[txid] for txid in {i.txid for i in d['prevouts']} ]
  315. if self.cfg.debug_tw:
  316. do_json_dump(
  317. (rpc_data, 'txhist-rpc'),
  318. (data, 'txhist'),
  319. (mm_map, 'mmap'),
  320. (_prevout_txs, 'prevout-txs'),
  321. (txdata, 'txdata'),
  322. )
  323. unspent_info = await self.get_unspent_by_mmid()
  324. return (
  325. BitcoinTwTransaction(
  326. parent = self,
  327. proto = self.proto,
  328. rpc = self.rpc,
  329. idx = idx,
  330. unspent_info = unspent_info,
  331. mm_map = mm_map,
  332. **d ) for idx,d in enumerate(txdata) )