zmq_sub.py raw
1 #!/usr/bin/env python3
2 # Copyright (c) 2014-present 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 """
7 ZMQ example using python3's asyncio
8
9 Bitcoin should be started with the command line arguments:
10 bitcoind -testnet4 -daemon \
11 -zmqpubrawtx=tcp://127.0.0.1:28332 \
12 -zmqpubrawblock=tcp://127.0.0.1:28332 \
13 -zmqpubhashtx=tcp://127.0.0.1:28332 \
14 -zmqpubhashblock=tcp://127.0.0.1:28332 \
15 -zmqpubsequence=tcp://127.0.0.1:28332
16
17 We use the asyncio library here. `self.handle()` installs itself as a
18 future at the end of the function. Since it never returns with the event
19 loop having an empty stack of futures, this creates an infinite loop. An
20 alternative is to wrap the contents of `handle` inside `while True`.
21
22 A blocking example using python 2.7 can be obtained from the git history:
23 https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py
24 """
25
26 import asyncio
27 import zmq
28 import zmq.asyncio
29 import signal
30 import struct
31 import sys
32
33 if (sys.version_info.major, sys.version_info.minor) < (3, 5):
34 print("This example only works with Python 3.5 and greater")
35 sys.exit(1)
36
37 port = 28332
38
39 class ZMQHandler():
40 def __init__(self):
41 self.loop = asyncio.get_event_loop()
42 self.zmqContext = zmq.asyncio.Context()
43
44 self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
45 self.zmqSubSocket.setsockopt(zmq.RCVHWM, 0)
46 self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock")
47 self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx")
48 self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock")
49 self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx")
50 self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "sequence")
51 self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port)
52
53 async def handle(self) :
54 topic, body, seq = await self.zmqSubSocket.recv_multipart()
55 sequence = "Unknown"
56 if len(seq) == 4:
57 sequence = str(struct.unpack('<I', seq)[-1])
58 if topic == b"hashblock":
59 print('- HASH BLOCK ('+sequence+') -')
60 print(body.hex())
61 elif topic == b"hashtx":
62 print('- HASH TX ('+sequence+') -')
63 print(body.hex())
64 elif topic == b"rawblock":
65 print('- RAW BLOCK HEADER ('+sequence+') -')
66 print(body[:80].hex())
67 elif topic == b"rawtx":
68 print('- RAW TX ('+sequence+') -')
69 print(body.hex())
70 elif topic == b"sequence":
71 hash = body[:32].hex()
72 label = chr(body[32])
73 mempool_sequence = None if len(body) != 32+1+8 else struct.unpack("<Q", body[32+1:])[0]
74 print('- SEQUENCE ('+sequence+') -')
75 print(hash, label, mempool_sequence)
76 # schedule ourselves to receive the next message
77 asyncio.ensure_future(self.handle())
78
79 def start(self):
80 self.loop.add_signal_handler(signal.SIGINT, self.stop)
81 self.loop.create_task(self.handle())
82 self.loop.run_forever()
83
84 def stop(self):
85 self.loop.stop()
86 self.zmqContext.destroy()
87
88 daemon = ZMQHandler()
89 daemon.start()
90