main_feeview.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU General Public License as published by the Free Software
  8. # Foundation, either version 3 of the License, or (at your option) any later
  9. # version.
  10. #
  11. # This program is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU General Public License along with
  17. # this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmnode-feeview: Visualize the fee structure of a node’s mempool
  20. """
  21. from mmgen.cfg import Config
  22. from mmgen.util import async_run,die,fmt,make_timestr,check_int_between
  23. from mmgen.util2 import int2bytespec,parse_bytespec
  24. min_prec,max_prec,dfl_prec = (0,6,4)
  25. fee_brackets = [
  26. 1, 2, 3, 4, 5, 6,
  27. 8, 10, 12, 14, 16, 18,
  28. 20, 25, 30, 35, 40, 45,
  29. 50, 60, 70, 80, 90,
  30. 100, 120, 140, 160, 180,
  31. 200, 250, 300, 350, 400, 450,
  32. 500, 600, 700, 800, 900,
  33. 1000, 1200, 1400, 1600, 1800,
  34. 2000, 2500, 3000, 3500, 4000, 4500,
  35. 5000, 6000, 7000, 8000, 9000,
  36. 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000,
  37. 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 2100000000000000,
  38. ]
  39. opts_data = {
  40. 'sets': [
  41. ('detail',True,'ranges',True),
  42. ('detail',True,'show_mb_col',True),
  43. ('detail',True,'precision',6),
  44. ],
  45. 'text': {
  46. 'desc': 'Visualize the fee structure of a node’s mempool',
  47. 'usage':'[opts]',
  48. 'options': f"""
  49. -h, --help Print this help message
  50. --, --longhelp Print help message for long options (common options)
  51. -c, --include-current Include current bracket’s TXs in cumulative MB value
  52. -d, --outdir=D Write log data to directory 'D'
  53. -D, --detail Same as --ranges --show-mb-col --precision=6
  54. -e, --show-empty Show all fee brackets, including empty ones
  55. -i, --ignore-below=B Ignore fee brackets with less than 'B' bytes of TXs
  56. -l, --log Log JSON-RPC mempool data to 'mempool.json'
  57. -p, --precision=P Use 'P' decimal points of precision for megabyte amts
  58. (min: {min_prec}, max: {max_prec}, default: {dfl_prec})
  59. -P, --pager Pipe the output to a pager
  60. -r, --ranges Display fee brackets as ranges
  61. -s, --show-mb-col Display column with each fee bracket’s megabyte count
  62. """,
  63. 'notes': """
  64. + By default, fee bracket row labels include only the top of the range.
  65. + By default, empty fee brackets are not displayed.
  66. + Mempool amounts are shown in decimal megabytes.
  67. + Values in the Total MB column are cumulative and represent megabytes of
  68. transactions in the mempool with fees higher than the TOP of the current
  69. fee bracket. To change this behavior, use the --include-current option.
  70. Note that there is no global mempool in Bitcoin, and your node’s mempool may
  71. differ significantly from those of mining nodes depending on uptime and other
  72. factors.
  73. """
  74. }
  75. }
  76. cfg = Config(opts_data=opts_data)
  77. if cfg.ignore_below:
  78. if cfg.show_empty:
  79. die(1,'Conflicting options: --ignore-below, --show-empty')
  80. ignore_below = parse_bytespec(cfg.ignore_below)
  81. precision = (
  82. check_int_between(cfg.precision,min_prec,max_prec,'--precision arg')
  83. if cfg.precision else dfl_prec )
  84. from mmgen.term import get_terminal_size
  85. width = cfg.columns or get_terminal_size().width
  86. class fee_bracket:
  87. def __init__(self,top,bottom):
  88. self.top = top
  89. self.bottom = bottom
  90. self.tx_bytes = 0
  91. self.tx_bytes_cum = 0
  92. self.skip = False
  93. def log(data,fn):
  94. import json
  95. from mmgen.rpc import json_encoder
  96. from mmgen.fileutil import write_data_to_file
  97. write_data_to_file(
  98. cfg = cfg,
  99. outfile = fn,
  100. data = json.dumps(data,cls=json_encoder,sort_keys=True,indent=4),
  101. desc = 'mempool',
  102. ask_overwrite = False )
  103. def create_data(coin_amt,mempool):
  104. out = [fee_bracket(fee_brackets[i],fee_brackets[i-1] if i else 0) for i in range(len(fee_brackets))]
  105. # populate fee brackets:
  106. size_key = 'size' if proto.coin == 'BCH' else 'vsize'
  107. for tx in mempool.values():
  108. fee = coin_amt(tx['fees']['base']).to_unit('satoshi')
  109. size = tx[size_key]
  110. for bracket in out:
  111. if fee / size < bracket.top:
  112. bracket.tx_bytes += size
  113. break
  114. # remove empty top brackets:
  115. while out and out[-1].tx_bytes == 0:
  116. out.pop()
  117. out.reverse() # cumulative totals and display are top-down
  118. # calculate cumulative byte totals, filter rows:
  119. tBytes = 0
  120. for i in out:
  121. if not (i.tx_bytes or cfg.show_empty):
  122. i.skip = True
  123. if cfg.ignore_below and i.tx_bytes < ignore_below:
  124. i.skip = True
  125. i.tx_bytes_cum = tBytes
  126. tBytes += i.tx_bytes
  127. return out
  128. def gen_header(host,mempool,blockcount):
  129. yield fmt(f"""
  130. Mempool Fee Structure
  131. Date: {make_timestr()} UTC
  132. Host: {host}
  133. Network: {proto.coin.upper()} {proto.network.upper()}
  134. Block: {blockcount}
  135. TX count: {len(mempool)}
  136. """).strip()
  137. if cfg.show_empty:
  138. yield 'Displaying all fee brackets'
  139. elif cfg.ignore_below:
  140. yield 'Ignoring fee brackets with less than {:,} bytes ({})'.format(
  141. ignore_below,
  142. int2bytespec(ignore_below,'MB','0.6',strip=True,add_space=True),
  143. )
  144. if cfg.include_current:
  145. yield 'Including transactions in current fee bracket in Total MB amounts'
  146. def fmt_mb(n):
  147. return int2bytespec(n,'MB',f'0.{precision}',print_sym=False)
  148. def gen_body(data):
  149. tx_bytes_max = max((i.tx_bytes for i in data),default=0)
  150. top_max = max((i.top for i in data),default=0)
  151. bot_max = max((i.bottom for i in data),default=0)
  152. col1_w = max(len(f'{bot_max}-{top_max}') if cfg.ranges else len(f'{top_max}'),6)
  153. col2_w = len(fmt_mb(tx_bytes_max)) if cfg.show_mb_col else 0
  154. col3_w = len(fmt_mb(data[-1].tx_bytes_cum)) if data else 0
  155. col4_w = width - col1_w - col2_w - col3_w - (4 if col2_w else 3)
  156. if cfg.show_mb_col:
  157. fs = '{a:<%i} {b:>%i} {c:>%i} {d}' % (col1_w,col2_w,col3_w)
  158. else:
  159. fs = '{a:<%i} {c:>%i} {d}' % (col1_w,col3_w)
  160. yield fs.format(a='', b='', c=f'{"Total":<{col3_w}}', d='')
  161. yield fs.format(a='sat/B', b=f'{"MB":<{col2_w}}', c=f'{"MB":<{col3_w}}', d='')
  162. for i in data:
  163. if not i.skip:
  164. cum_bytes = i.tx_bytes_cum + i.tx_bytes if cfg.include_current else i.tx_bytes_cum
  165. yield fs.format(
  166. a = '{}-{}'.format(i.bottom,i.top) if cfg.ranges else i.top,
  167. b = fmt_mb(i.tx_bytes),
  168. c = fmt_mb(cum_bytes),
  169. d = '-' * int(col4_w * ( i.tx_bytes / tx_bytes_max )) )
  170. yield fs.format(
  171. a = 'TOTAL',
  172. b = '',
  173. c = fmt_mb(data[-1].tx_bytes_cum + data[-1].tx_bytes if data else 0),
  174. d = '' )
  175. async def main():
  176. global proto
  177. proto = cfg._proto
  178. from mmgen.rpc import rpc_init
  179. c = await rpc_init(cfg,ignore_wallet=True)
  180. mempool = await c.call('getrawmempool',True)
  181. if cfg.log:
  182. log(mempool,'mempool.json')
  183. data = create_data(proto.coin_amt,mempool)
  184. cfg._util.stdout_or_pager(
  185. '\n'.join(gen_header(
  186. c.host,
  187. mempool,
  188. await c.call('getblockcount') )) + '\n\n' +
  189. '\n'.join(gen_body(data)) + '\n' )
  190. async_run(main())