Skip to content

Instantly share code, notes, and snippets.

@laanwj

laanwj/stats_bitcoin.py

Last active Jul 17, 2020
Embed
What would you like to do?
Bitcoin network stats script
#!/usr/bin/env python3
import sys
sys.path.append('./bitcoin/test/functional')
from test_framework.authproxy import AuthServiceProxy, JSONRPCException
import time
import os
datadir = os.getenv("DATADIR", os.path.join(os.getenv('HOME'), '.bitcoin'))
with open(os.path.join(datadir,'.cookie'),'r') as f:
cookie = f.read()
tgt = "http://%s@127.0.0.1:8332/" % (cookie)
proxy = AuthServiceProxy(tgt)
out = sys.stdout # stream to write to
while True:
now = time.time()
peers = proxy.getpeerinfo()
in_ipv4 = 0
in_ipv6 = 0
in_tor = 0
out_ipv4 = 0
out_ipv6 = 0
out_tor = 0
for peer in peers:
addr = peer['addr']
if peer['inbound']:
if addr.startswith('['):
in_ipv6 += 1
elif addr.startswith('127.0.0.1:'):
in_tor += 1
else:
in_ipv4 += 1
else:
if addr.startswith('['):
out_ipv6 += 1
elif '.onion' in addr:
out_tor += 1
else:
out_ipv4 += 1
print('[by network]')
print('in: ipv4 %3d ipv6 %3d tor %3d' % (in_ipv4, in_ipv6, in_tor))
print('out: ipv4 %3d ipv6 %3d tor %3d' % (out_ipv4, out_ipv6, out_tor))
ni = proxy.getblockchaininfo()
bi = proxy.getblock(ni['bestblockhash'])
print()
print('Last block was %d, on %s' % (ni['blocks'], time.ctime(bi['time'])))
break
@jonatack

This comment has been minimized.

Copy link

@jonatack jonatack commented Jul 17, 2020

dropped it into test/functional and it works well, thanks!

made these changes for fun:

29            elif addr.startswith("127.0.0.1:") and ".onion" in peer["addrlocal"]:

41    print("in:  ipv4 %3d | ipv6 %3d | onion %3d" % (in_ipv4, in_ipv6, in_tor))
42    print("out: ipv4 %3d | ipv6 %3d | onion %3d" % (out_ipv4, out_ipv6, out_tor))
@jonatack

This comment has been minimized.

Copy link

@jonatack jonatack commented Jul 17, 2020

perhaps even

29            elif addr.startswith("127.0.0.1:") and ".onion" in peer["addrlocal"] and "mapped_as" not in peer.keys():
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.