|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) 2014-2016 The Bitcoin Core developers |
| 3 | +# Distributed under the MIT software license, see the accompanying |
| 4 | +# file COPYING or http://www.opensource.org/licenses/mit-license.php. |
| 5 | + |
| 6 | +# A blocking example using python 2.7 can be obtained from the git history: |
| 7 | +# https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py |
| 8 | + |
| 9 | +import array |
| 10 | +import binascii |
| 11 | +import asyncio, zmq, zmq.asyncio |
| 12 | +import signal |
| 13 | +import struct |
| 14 | +import sys |
| 15 | + |
| 16 | +if not (sys.version_info.major >= 3 and sys.version_info.minor >= 4): |
| 17 | + print("This example only works with Python 3.4 and greater") |
| 18 | + exit(1) |
| 19 | + |
| 20 | +port = 28332 |
| 21 | + |
| 22 | +class ZMQHandler(): |
| 23 | + def __init__(self): |
| 24 | + self.loop = zmq.asyncio.install() |
| 25 | + self.zmqContext = zmq.asyncio.Context() |
| 26 | + |
| 27 | + self.zmqSubSocket = self.zmqContext.socket(zmq.SUB) |
| 28 | + self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock") |
| 29 | + self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx") |
| 30 | + self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock") |
| 31 | + self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx") |
| 32 | + self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port) |
| 33 | + |
| 34 | + @asyncio.coroutine |
| 35 | + def handle(self) : |
| 36 | + msg = yield from self.zmqSubSocket.recv_multipart() |
| 37 | + topic = msg[0] |
| 38 | + body = msg[1] |
| 39 | + sequence = "Unknown"; |
| 40 | + if len(msg[-1]) == 4: |
| 41 | + msgSequence = struct.unpack('<I', msg[-1])[-1] |
| 42 | + sequence = str(msgSequence) |
| 43 | + if topic == b"hashblock": |
| 44 | + print('- HASH BLOCK ('+sequence+') -') |
| 45 | + print(binascii.hexlify(body)) |
| 46 | + elif topic == b"hashtx": |
| 47 | + print('- HASH TX ('+sequence+') -') |
| 48 | + print(binascii.hexlify(body)) |
| 49 | + elif topic == b"rawblock": |
| 50 | + print('- RAW BLOCK HEADER ('+sequence+') -') |
| 51 | + print(binascii.hexlify(body[:80])) |
| 52 | + elif topic == b"rawtx": |
| 53 | + print('- RAW TX ('+sequence+') -') |
| 54 | + print(binascii.hexlify(body)) |
| 55 | + # schedule ourselves to receive the next message |
| 56 | + asyncio.ensure_future(self.handle()) |
| 57 | + |
| 58 | + def start(self): |
| 59 | + asyncio.ensure_future(self.handle()) |
| 60 | + self.loop.run_forever() |
| 61 | + |
| 62 | + def stop(self): |
| 63 | + self.loop.stop() |
| 64 | + self.zmqContext.destroy() |
| 65 | + |
| 66 | +daemon = ZMQHandler() |
| 67 | +def signal_handler(num, frame): |
| 68 | + daemon.stop() |
| 69 | + exit(0) |
| 70 | +signal.signal(signal.SIGINT, signal_handler) |
| 71 | +daemon.start() |
0 commit comments