main_peerblocks.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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-peerblocks: List blocks in flight, disconnect stalling nodes
  20. """
  21. import asyncio
  22. from collections import namedtuple
  23. from mmgen.common import *
  24. opts_data = {
  25. 'text': {
  26. 'desc': 'List blocks in flight, disconnect stalling nodes',
  27. 'usage': '[opts]',
  28. 'options': """
  29. -h, --help Print this help message
  30. --, --longhelp Print help message for long options (common options)
  31. """
  32. }
  33. }
  34. def format_peer_info(peerinfo):
  35. pd = namedtuple('peer_data',['id','blocks_data','screen_width'])
  36. def gen_peers(peerinfo):
  37. global min_height
  38. min_height = None
  39. for d in peerinfo:
  40. if 'inflight' in d and d['inflight']:
  41. blocks = d['inflight']
  42. if not min_height or min_height > blocks[0]:
  43. min_height = blocks[0]
  44. line = ' '.join(map(str,blocks))[:term_width - 2 - id_width]
  45. blocks_disp = line.split()
  46. yield pd(
  47. d['id'],
  48. [(blocks[i],blocks_disp[i]) for i in range(len(blocks_disp))],
  49. len(line) )
  50. else:
  51. yield pd( d['id'], [], 0 )
  52. def gen_line(peer):
  53. if peer.blocks_data:
  54. if peer.blocks_data[0][0] == min_height:
  55. yield RED + peer.blocks_data[0][1] + RESET
  56. peer.blocks_data.pop(0)
  57. for blk,blk_disp in peer.blocks_data:
  58. yield COLORS[blk % 10] + blk_disp + RESET
  59. id_width = max(2,max(len(str(i['id'])) for i in peerinfo))
  60. for peer in tuple(gen_peers(peerinfo)):
  61. line = '{:>{iw}}: {}'.format(
  62. peer.id,
  63. ' '.join(gen_line(peer)),
  64. iw = id_width )
  65. yield line + ' ' * (term_width - 2 - id_width - peer.screen_width)
  66. def test_format():
  67. import json
  68. info = json.loads(open('test_data/peerinfo.json').read())
  69. print('\n'.join(format_peer_info(info)) + '\n')
  70. sys.exit(0)
  71. async def inflight_display(rpc):
  72. count = 1
  73. while True:
  74. info = await rpc.call('getpeerinfo')
  75. msg_r(
  76. CUR_HOME
  77. + f'ACTIVE PEERS ({len(info)}) Blocks in Flight - poll {count} \n'
  78. + ('\n'.join(format_peer_info(info)) + '\n' if info else '')
  79. + ERASE_ALL + 'Hit ENTER for disconnect menu: ' )
  80. await asyncio.sleep(2)
  81. count += 1
  82. async def do_inflight(rpc):
  83. task = asyncio.ensure_future(inflight_display(rpc)) # Python 3.7+: create_task()
  84. from select import select
  85. while True:
  86. key = select([sys.stdin], [], [], 0.1)[0]
  87. if key:
  88. sys.stdin.read(1)
  89. task.cancel()
  90. break
  91. await asyncio.sleep(0.1)
  92. try:
  93. await task
  94. except asyncio.CancelledError:
  95. pass
  96. async def do_disconnect_menu(rpc):
  97. while True:
  98. peerinfo = await rpc.call('getpeerinfo')
  99. ids = [str(d['id']) for d in peerinfo]
  100. msg(f'{CUR_HOME}ACTIVE PEERS ({len(peerinfo)}) Disconnect Menu' + ' '*16)
  101. def gen_peerinfo():
  102. for d in peerinfo:
  103. line = f"{d['id']:>{id_width}}: {d['addr']:30} {d['subver']}"
  104. yield line + ' ' * (term_width - len(line))
  105. if peerinfo:
  106. id_width = max(2,max(len(str(i['id'])) for i in peerinfo))
  107. msg('\n'.join(gen_peerinfo()))
  108. msg_r(ERASE_ALL)
  109. reply = input("Type peer number to disconnect, ENTER to quit menu, 'u' to update peer list: ")
  110. if reply == '':
  111. return
  112. elif reply == 'u':
  113. msg(f'Updating peer list')
  114. await asyncio.sleep(0.5)
  115. elif reply in ids:
  116. addr = peerinfo[ids.index(reply)]['addr']
  117. msg(f'Disconnecting peer {reply} ({addr})')
  118. try:
  119. await rpc.call('disconnectnode',addr)
  120. except RPCFailure:
  121. msg(f'Unable to disconnect peer {addr}')
  122. await asyncio.sleep(1.5)
  123. else:
  124. msg(f'{reply!r}: invalid peer number')
  125. await asyncio.sleep(0.5)
  126. async def main():
  127. msg_r(CUR_HOME+ERASE_ALL)
  128. from mmgen.protocol import init_proto_from_opts
  129. proto = init_proto_from_opts()
  130. from mmgen.rpc import rpc_init
  131. rpc = await rpc_init(proto)
  132. while True:
  133. await do_inflight(rpc)
  134. await do_disconnect_menu(rpc)
  135. opts.init(opts_data)
  136. from mmgen.term import get_terminal_size
  137. term_width = get_terminal_size()[0]
  138. RED,RESET = ('\033[31m','\033[0m')
  139. COLORS = ['\033[38;5;%s;1m' % c for c in (247,248,249,250,251,252,253,254,255,231)]
  140. ERASE_ALL,ERASE_LINE,CUR_HOME,CUR_HIDE,CUR_SHOW = (
  141. '\033[J','\033[K','\033[H','\033[?25l','\033[?25h')
  142. try:
  143. run_session(main())
  144. except:
  145. from subprocess import run
  146. run(['stty','sane'])
  147. msg('')