mmnode-peerblocks 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. mmgen-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. for blk,blk_disp in peer.blocks_data:
  54. if blk == min_height:
  55. yield RED + blk_disp + RESET
  56. else:
  57. yield COLORS[blk % 10] + blk_disp + RESET
  58. id_width = max(2,max(len(str(i['id'])) for i in peerinfo))
  59. for peer in gen_peers(peerinfo):
  60. line = '{:>{iw}}: {}'.format(
  61. peer.id,
  62. ' '.join(gen_line(peer)),
  63. iw = id_width )
  64. yield line + ' ' * (term_width - 2 - id_width - peer.screen_width)
  65. async def inflight_display(rpc):
  66. count = 1
  67. while True:
  68. info = await rpc.call('getpeerinfo')
  69. msg_r(
  70. CUR_HOME
  71. + f'ACTIVE PEERS ({len(info)}) Blocks in Flight - poll {count} \n'
  72. + ('\n'.join(format_peer_info(info)) + '\n' if info else '')
  73. + ERASE_ALL + 'Hit ENTER for disconnect menu: ' )
  74. await asyncio.sleep(2)
  75. count += 1
  76. async def do_inflight(rpc):
  77. task = asyncio.ensure_future(inflight_display(rpc)) # Python 3.7+: create_task()
  78. from select import select
  79. while True:
  80. key = select([sys.stdin], [], [], 0.1)[0]
  81. if key:
  82. sys.stdin.read(1)
  83. task.cancel()
  84. break
  85. await asyncio.sleep(0.1)
  86. try:
  87. await task
  88. except asyncio.CancelledError:
  89. pass
  90. async def do_disconnect_menu(rpc):
  91. while True:
  92. peerinfo = await rpc.call('getpeerinfo')
  93. ids = [str(d['id']) for d in peerinfo]
  94. msg(f'{CUR_HOME}ACTIVE PEERS ({len(peerinfo)}) Disconnect Menu' + ' '*16)
  95. def gen_peerinfo():
  96. for d in peerinfo:
  97. line = f"{d['id']:>{id_width}}: {d['addr']:30} {d['subver']}"
  98. yield line + ' ' * (term_width - len(line))
  99. if peerinfo:
  100. id_width = max(2,max(len(str(i['id'])) for i in peerinfo))
  101. msg('\n'.join(gen_peerinfo()))
  102. msg_r(ERASE_ALL)
  103. reply = input("Type peer number to disconnect, ENTER to quit menu, 'u' to update peer list: ")
  104. if reply == '':
  105. return
  106. elif reply == 'u':
  107. msg(f'Updating peer list')
  108. await asyncio.sleep(0.5)
  109. elif reply in ids:
  110. addr = peerinfo[ids.index(reply)]['addr']
  111. msg(f'Disconnecting peer {reply} ({addr})')
  112. try:
  113. await rpc.call('disconnectnode',addr)
  114. except RPCFailure:
  115. msg(f'Unable to disconnect peer {addr}')
  116. await asyncio.sleep(1.5)
  117. else:
  118. msg(f'{reply!r}: invalid peer number')
  119. await asyncio.sleep(0.5)
  120. async def main():
  121. msg_r(CUR_HOME+ERASE_ALL)
  122. from mmgen.rpc import rpc_init
  123. rpc = await rpc_init()
  124. while True:
  125. await do_inflight(rpc)
  126. await do_disconnect_menu(rpc)
  127. opts.init(opts_data)
  128. from mmgen.term import get_terminal_size
  129. term_width = get_terminal_size()[0]
  130. RED,RESET = ('\033[31m','\033[0m')
  131. COLORS = ['\033[38;5;%s;1m' % c for c in (247,248,249,250,251,252,253,254,255,231)]
  132. ERASE_ALL,ERASE_LINE,CUR_HOME,CUR_HIDE,CUR_SHOW = (
  133. '\033[J','\033[K','\033[H','\033[?25l','\033[?25h')
  134. try:
  135. run_session(main(),do_rpc_init=False)
  136. except:
  137. from subprocess import run
  138. run(['stty','sane'])
  139. msg('')