forked from 15Dkatz/python-blockchain-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub.py
More file actions
82 lines (66 loc) · 2.7 KB
/
pubsub.py
File metadata and controls
82 lines (66 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import time
from pubnub.pubnub import PubNub
from pubnub.pnconfiguration import PNConfiguration
from pubnub.callbacks import SubscribeCallback
from backend.blockchain.block import Block
from backend.wallet.transaction import Transaction
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'sub-c-666638f6-ec63-11e9-b715-9abbdb5d0da2'
pnconfig.publish_key = 'pub-c-82bf7695-ce5e-4bc5-9cd9-a8f8147dc2a8'
CHANNELS = {
'TEST': 'TEST',
'BLOCK': 'BLOCK',
'TRANSACTION': 'TRANSACTION'
}
class Listener(SubscribeCallback):
def __init__(self, blockchain, transaction_pool):
self.blockchain = blockchain
self.transaction_pool = transaction_pool
def message(self, pubnub, message_object):
print(f'\n-- Channel: {message_object.channel} | Message: {message_object.message}')
if message_object.channel == CHANNELS['BLOCK']:
block = Block.from_json(message_object.message)
potential_chain = self.blockchain.chain[:]
potential_chain.append(block)
try:
self.blockchain.replace_chain(potential_chain)
self.transaction_pool.clear_blockchain_transactions(
self.blockchain
)
print('\n -- Successfully replaced the local chain')
except Exception as e:
print(f'\n -- Did not replace chain: {e}')
elif message_object.channel == CHANNELS['TRANSACTION']:
transaction = Transaction.from_json(message_object.message)
self.transaction_pool.set_transaction(transaction)
print('\n -- Set the new transaction in the transaction pool')
class PubSub():
"""
Handles the publish/subscribe layer of the application.
Provides communication between the nodes of the blockchain network.
"""
def __init__(self, blockchain, transaction_pool):
self.pubnub = PubNub(pnconfig)
self.pubnub.subscribe().channels(CHANNELS.values()).execute()
self.pubnub.add_listener(Listener(blockchain, transaction_pool))
def publish(self, channel, message):
"""
Publish the message object to the channel.
"""
self.pubnub.publish().channel(channel).message(message).sync()
def broadcast_block(self, block):
"""
Broadcast a block object to all nodes.
"""
self.publish(CHANNELS['BLOCK'], block.to_json())
def broadcast_transaction(self, transaction):
"""
Broadcast a transaction to all nodes.
"""
self.publish(CHANNELS['TRANSACTION'], transaction.to_json())
def main():
pubsub = PubSub()
time.sleep(1)
pubsub.publish(CHANNELS['TEST'], { 'foo': 'bar' })
if __name__ == '__main__':
main()