mmnode-peerblocks 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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 mmgen.common import *
  23. opts_data = {
  24. 'text': {
  25. 'desc': 'List blocks in flight, disconnect stalling nodes',
  26. 'usage': '[opts]',
  27. 'options': """
  28. -h, --help Print this help message
  29. --, --longhelp Print help message for long options (common options)
  30. """
  31. }
  32. }
  33. opts.init(opts_data)
  34. async def inflight_display(rpc):
  35. def gen_peers(peerinfo):
  36. global min_height
  37. min_height = None
  38. for d in peerinfo:
  39. if 'inflight' in d and d['inflight']:
  40. blks = d['inflight']
  41. if not min_height or min_height > blks[0]:
  42. min_height = blks[0]
  43. blks_trunc = ' '.join(map(str,blks))[:term_width-6].split()
  44. trim = blks_trunc[-1] != str(blks[len(blks_trunc)-1])
  45. blks = blks[:len(blks_trunc)-trim]
  46. else:
  47. blks = []
  48. yield { 'id': d['id'], 'data': blks }
  49. def gen_line(peer):
  50. for blk in peer['data']:
  51. if blk == min_height:
  52. yield RED + str(blk) + RESET
  53. else:
  54. yield COLORS[blk % 10] + str(blk) + RESET
  55. from mmgen.term import get_terminal_size
  56. term_width = get_terminal_size()[0]
  57. count = 1
  58. while True:
  59. info = await rpc.call('getpeerinfo')
  60. msg_r(CUR_HOME+ERASE_ALL+CUR_HOME)
  61. msg(f'ACTIVE PEERS ({len(info)}) - poll {count}')
  62. for peer in gen_peers(info):
  63. sys.stderr.write('\r{} {:>3}: {}\n'.format(
  64. ERASE_LINE,
  65. peer['id'],
  66. ' '.join(gen_line(peer)) ))
  67. msg_r(ERASE_ALL+'Hit ENTER for disconnect prompt: ')
  68. await asyncio.sleep(2)
  69. count += 1
  70. async def do_inflight(rpc):
  71. task = asyncio.ensure_future(inflight_display(rpc)) # Python 3.7+: create_task()
  72. from select import select
  73. while True:
  74. key = select([sys.stdin], [], [], 0.1)[0]
  75. if key:
  76. sys.stdin.read(1)
  77. task.cancel()
  78. break
  79. await asyncio.sleep(0.1)
  80. try:
  81. await task
  82. except asyncio.CancelledError:
  83. pass
  84. async def do_disconnect_menu(rpc):
  85. while True:
  86. peerinfo = await rpc.call('getpeerinfo')
  87. ids = [str(d['id']) for d in peerinfo]
  88. msg_r(CUR_HOME+ERASE_ALL+CUR_HOME)
  89. msg(f'ACTIVE PEERS ({len(peerinfo)})')
  90. if peerinfo:
  91. msg('\n'.join([f"{d['id']:>3}: {d['addr']:30} {d['subver']}" for d in peerinfo]))
  92. reply = input("Peer number to disconnect, ENTER to quit menu, 'u' to update peer list> ")
  93. if reply == '':
  94. return
  95. elif reply == 'u':
  96. msg(f'Updating peer list')
  97. await asyncio.sleep(0.5)
  98. elif reply in ids:
  99. addr = peerinfo[ids.index(reply)]['addr']
  100. msg(f'Disconnecting peer {reply} ({addr})')
  101. try:
  102. await rpc.call('disconnectnode',addr)
  103. except RPCFailure:
  104. msg(f'Unable to disconnect peer {addr}')
  105. await asyncio.sleep(1.5)
  106. else:
  107. msg(f'{reply!r}: invalid peer number')
  108. await asyncio.sleep(0.5)
  109. async def main():
  110. msg_r(CUR_HOME+ERASE_ALL)
  111. from mmgen.rpc import rpc_init
  112. rpc = await rpc_init()
  113. while True:
  114. await do_inflight(rpc)
  115. await do_disconnect_menu(rpc)
  116. RED,RESET = ('\033[31m','\033[0m')
  117. COLORS = ['\033[38;5;%s;1m' % c for c in (238,240,242,244,246,247,249,251,253,255)]
  118. ERASE_ALL,ERASE_LINE,CUR_HOME,CUR_HIDE,CUR_SHOW = (
  119. '\033[J','\033[K','\033[H','\033[?25l','\033[?25h')
  120. try:
  121. run_session(main(),do_rpc_init=False)
  122. except:
  123. from subprocess import run
  124. run(['stty','sane'])
  125. msg('')