#!/usr/bin/env python
#
# Connect to a bitcoin node and dump out JSON-format block chain
#
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from BitcoinClient import *
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]\n"+
"Connects to a running bitcoin node and "+
"prints all or part of the best-block-chain.")
parser.add_option("--host", dest="host", default="127.0.0.1",
help="IP/hostname to connect to (default: %default)")
parser.add_option("--port", dest="port", default="8333", type="int",
help="port to connect to (default: %default)")
parser.add_option("--testnet", dest="testnet", action="store_true", default=False,
help="Speak testnet protocol")
parser.add_option("--n", dest="n_blocks", type="int", default=99999,
help="Dump this many blocks (default: all)")
parser.add_option("--verbose", dest="verbose", action="store_true", default=False,
help="Print all messages sent/received")
parser.add_option("--version", dest="version", default="0.4.0",
help="Version of the protocol to speak")
(options, args) = parser.parse_args()
# Convert string like "1.0" or "0.3.24.0" to integer version where 1.0.0.0 == 1000000
version = sum([ int(j)*(100**(3-i)) for (i,j) in enumerate(options.version.split(".")) ])
def print_blocks(blocks):
for b in blocks:
print b
def start_dumper(connection):
d = Deferred()
d.addCallback(print_blocks)
d.addCallback(lambda x: reactor.stop() )
connection.getBlocks(None, options.n_blocks, d)
def connection_failed(reason):
print("Connection failed: "+reason)
reactor.stop()
d = Deferred()
d.addCallbacks(start_dumper, connection_failed)
factory = BitcoinClientFactory(options.testnet, version, d)
reactor.connectTCP(options.host, options.port, factory)
reactor.run()if __name__ == '__main__':
main()