55from pubnub .callbacks import SubscribeCallback
66
77from backend .blockchain .block import Block
8+ from backend .wallet .transaction import Transaction
89
910pnconfig = PNConfiguration ()
1011pnconfig .subscribe_key = 'sub-c-666638f6-ec63-11e9-b715-9abbdb5d0da2'
1112pnconfig .publish_key = 'pub-c-82bf7695-ce5e-4bc5-9cd9-a8f8147dc2a8'
1213
1314CHANNELS = {
1415 'TEST' : 'TEST' ,
15- 'BLOCK' : 'BLOCK'
16+ 'BLOCK' : 'BLOCK' ,
17+ 'TRANSACTION' : 'TRANSACTION'
1618}
1719
1820class Listener (SubscribeCallback ):
19- def __init__ (self , blockchain ):
21+ def __init__ (self , blockchain , transaction_pool ):
2022 self .blockchain = blockchain
23+ self .transaction_pool = transaction_pool
2124
2225 def message (self , pubnub , message_object ):
2326 print (f'\n -- Channel: { message_object .channel } | Message: { message_object .message } ' )
@@ -32,16 +35,20 @@ def message(self, pubnub, message_object):
3235 print ('\n -- Successfully replaced the local chain' )
3336 except Exception as e :
3437 print (f'\n -- Did not replace chain: { e } ' )
38+ elif message_object .channel == CHANNELS ['TRANSACTION' ]:
39+ transaction = Transaction .from_json (message_object .message )
40+ self .transaction_pool .set_transaction (transaction )
41+ print ('\n -- Set the new transaction in the transaction pool' )
3542
3643class PubSub ():
3744 """
3845 Handles the publish/subscribe layer of the application.
3946 Provides communication between the nodes of the blockchain network.
4047 """
41- def __init__ (self , blockchain ):
48+ def __init__ (self , blockchain , transaction_pool ):
4249 self .pubnub = PubNub (pnconfig )
4350 self .pubnub .subscribe ().channels (CHANNELS .values ()).execute ()
44- self .pubnub .add_listener (Listener (blockchain ))
51+ self .pubnub .add_listener (Listener (blockchain , transaction_pool ))
4552
4653 def publish (self , channel , message ):
4754 """
@@ -55,6 +62,12 @@ def broadcast_block(self, block):
5562 """
5663 self .publish (CHANNELS ['BLOCK' ], block .to_json ())
5764
65+ def broadcast_transaction (self , transaction ):
66+ """
67+ Broadcast a transaction to all nodes.
68+ """
69+ self .publish (CHANNELS ['TRANSACTION' ], transaction .to_json ())
70+
5871def main ():
5972 pubsub = PubSub ()
6073
0 commit comments