Python code to dump bitcoin blockchain from a node


SUBMITTED BY: Guest

DATE: Nov. 18, 2012, 9:37 p.m.

FORMAT: Python

SIZE: 2.3 kB

HITS: 2193

  1. #!/usr/bin/env python
  2. #
  3. # Connect to a bitcoin node and dump out JSON-format block chain
  4. #
  5. from twisted.internet import reactor
  6. from twisted.internet.defer import Deferred
  7. from BitcoinClient import *
  8. def main():
  9. import optparse
  10. parser = optparse.OptionParser(usage="%prog [options]\n"+
  11. "Connects to a running bitcoin node and "+
  12. "prints all or part of the best-block-chain.")
  13. parser.add_option("--host", dest="host", default="127.0.0.1",
  14. help="IP/hostname to connect to (default: %default)")
  15. parser.add_option("--port", dest="port", default="8333", type="int",
  16. help="port to connect to (default: %default)")
  17. parser.add_option("--testnet", dest="testnet", action="store_true", default=False,
  18. help="Speak testnet protocol")
  19. parser.add_option("--n", dest="n_blocks", type="int", default=99999,
  20. help="Dump this many blocks (default: all)")
  21. parser.add_option("--verbose", dest="verbose", action="store_true", default=False,
  22. help="Print all messages sent/received")
  23. parser.add_option("--version", dest="version", default="0.4.0",
  24. help="Version of the protocol to speak")
  25. (options, args) = parser.parse_args()
  26. # Convert string like "1.0" or "0.3.24.0" to integer version where 1.0.0.0 == 1000000
  27. version = sum([ int(j)*(100**(3-i)) for (i,j) in enumerate(options.version.split(".")) ])
  28. def print_blocks(blocks):
  29. for b in blocks:
  30. print b
  31. def start_dumper(connection):
  32. d = Deferred()
  33. d.addCallback(print_blocks)
  34. d.addCallback(lambda x: reactor.stop() )
  35. connection.getBlocks(None, options.n_blocks, d)
  36. def connection_failed(reason):
  37. print("Connection failed: "+reason)
  38. reactor.stop()
  39. d = Deferred()
  40. d.addCallbacks(start_dumper, connection_failed)
  41. factory = BitcoinClientFactory(options.testnet, version, d)
  42. reactor.connectTCP(options.host, options.port, factory)
  43. reactor.run()if __name__ == '__main__':
  44. main()

comments powered by Disqus