|
4 | 4 | from pubnub.pnconfiguration import PNConfiguration |
5 | 5 | from pubnub.callbacks import SubscribeCallback |
6 | 6 |
|
| 7 | +from backend.blockchain.block import Block |
| 8 | + |
7 | 9 | pnconfig = PNConfiguration() |
8 | 10 | pnconfig.subscribe_key = 'sub-c-666638f6-ec63-11e9-b715-9abbdb5d0da2' |
9 | 11 | pnconfig.publish_key = 'pub-c-82bf7695-ce5e-4bc5-9cd9-a8f8147dc2a8' |
10 | | -pubnub = PubNub(pnconfig) |
11 | | - |
12 | | -TEST_CHANNEL = 'TEST_CHANNEL' |
13 | 12 |
|
14 | | -pubnub.subscribe().channels([TEST_CHANNEL]).execute() |
| 13 | +CHANNELS = { |
| 14 | + 'TEST': 'TEST', |
| 15 | + 'BLOCK': 'BLOCK' |
| 16 | +} |
15 | 17 |
|
16 | 18 | class Listener(SubscribeCallback): |
| 19 | + def __init__(self, blockchain): |
| 20 | + self.blockchain = blockchain |
| 21 | + |
17 | 22 | def message(self, pubnub, message_object): |
18 | | - print(f'\n-- Incoming message_object: {message_object}') |
| 23 | + print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}') |
| 24 | + |
| 25 | + if message_object.channel == CHANNELS['BLOCK']: |
| 26 | + block = Block.from_json(message_object.message) |
| 27 | + potential_chain = self.blockchain.chain[:] |
| 28 | + potential_chain.append(block) |
19 | 29 |
|
| 30 | + try: |
| 31 | + self.blockchain.replace_chain(potential_chain) |
| 32 | + print('\n -- Successfully replaced the local chain') |
| 33 | + except Exception as e: |
| 34 | + print(f'\n -- Did not replace chain: {e}') |
20 | 35 |
|
21 | | -pubnub.add_listener(Listener()) |
| 36 | +class PubSub(): |
| 37 | + """ |
| 38 | + Handles the publish/subscribe layer of the application. |
| 39 | + Provides communication between the nodes of the blockchain network. |
| 40 | + """ |
| 41 | + def __init__(self, blockchain): |
| 42 | + self.pubnub = PubNub(pnconfig) |
| 43 | + self.pubnub.subscribe().channels(CHANNELS.values()).execute() |
| 44 | + self.pubnub.add_listener(Listener(blockchain)) |
| 45 | + |
| 46 | + def publish(self, channel, message): |
| 47 | + """ |
| 48 | + Publish the message object to the channel. |
| 49 | + """ |
| 50 | + self.pubnub.publish().channel(channel).message(message).sync() |
| 51 | + |
| 52 | + def broadcast_block(self, block): |
| 53 | + """ |
| 54 | + Broadcast a block object to all nodes. |
| 55 | + """ |
| 56 | + self.publish(CHANNELS['BLOCK'], block.to_json()) |
22 | 57 |
|
23 | 58 | def main(): |
| 59 | + pubsub = PubSub() |
| 60 | + |
24 | 61 | time.sleep(1) |
25 | 62 |
|
26 | | - pubnub.publish().channel(TEST_CHANNEL).message({ 'foo': 'bar' }).sync() |
| 63 | + pubsub.publish(CHANNELS['TEST'], { 'foo': 'bar' }) |
27 | 64 |
|
28 | 65 | if __name__ == '__main__': |
29 | 66 | main() |
0 commit comments