├── requirements.txt ├── p2pnetwork ├── tests │ ├── __init__.py │ ├── test_nodeconnection.py │ ├── test_node_compression.py │ └── test_node.py ├── __init__.py ├── nodeconnection.py └── node.py ├── .gitignore ├── tox.ini ├── setup.py ├── examples ├── README.md ├── my_own_p2p_application_using_dict.py ├── MyOwnPeer2PeerNode.py ├── my_own_p2p_application.py ├── my_own_p2p_application_callback.py └── my_own_p2p_application_compression.py ├── GETTING_STARTED.md ├── README.md └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /p2pnetwork/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pyc 3 | venv/ 4 | .idea/ 5 | 6 | /dist 7 | /p2pnetwork*.egg-info 8 | /build 9 | /.eggs 10 | 11 | # Added tox 12 | .tox -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # content of: tox.ini , put in same dir as setup.py 2 | [tox] 3 | envlist = py38 4 | 5 | [testenv] 6 | # install pytest in the virtualenv where commands will be executed 7 | deps = pytest 8 | commands = 9 | # NOTE: you can run any command line tool here - not just tests 10 | pytest -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="p2pnetwork", 8 | version="1.2", 9 | author="Maurice Snoeren", 10 | author_email="macsnoeren@gmail.com", 11 | description="Python decentralized peer-to-peer network application framework.", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/macsnoeren/python-p2p-network", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 19 | "Operating System :: OS Independent", 20 | ], 21 | python_requires='>=3.6', 22 | ) -------------------------------------------------------------------------------- /p2pnetwork/__init__.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.1 beta (use at your own risk) # 4 | # # 5 | # Package p2pnet for decentralized peer-to-peer network applications # 6 | ####################################################################################################################### 7 | 8 | __title__ = 'python-p2p-network' 9 | __author__ = 'Maurice Snoeren' 10 | __license__ = "GNU 3.0" 11 | __main__ = "p2pnetwork" 12 | 13 | __all__ = ["node", "Node", "nodeconnection", "NodeConnection"] 14 | 15 | from .node import Node 16 | from .nodeconection import NodeConnection 17 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Example peer-to-peer decentralized applications 2 | This directory contains several examples and one real project of a peer-to-peer decentralized application. It is really nice to play around with decentralized applications. The following examples have been provided: 3 | 1. Implementation p2p application with callback 4 | 2. Implementation p2p application by extending p2pnet.Node 5 | 3. Implementation of p2p security application 6 | 7 | # Example 1 and 2 8 | The examples 1 and 2 can be found in the documentation README.md in de main code. So, feel free to visit this specific file. 9 | 10 | # Example 3: SecurityNode 11 | This example (principally a real project to me) is about a decentralized peer-to-peer network application that creates security to its used. It provides different kind of security aspect to protect the data of the users. All nodes have a private/public key and signs all the messages they send. These messages are also verified. When successfull the application gets the message to process it. The messages are checked on integrity and non-repudiation. 12 | 13 | ## Python requirements 14 | Use Python version 3.x and install the following modules: 15 | 1. pycryptodome 16 | 17 | -------------------------------------------------------------------------------- /examples/my_own_p2p_application_using_dict.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.1 beta (use at your own risk) # 4 | # # 5 | # This example show how to derive a own Node class (MyOwnPeer2PeerNode) from p2pnet.Node to implement your own Node # 6 | # implementation. See the MyOwnPeer2PeerNode.py for all the details. In that class all your own application specific # 7 | # details are coded. # 8 | ####################################################################################################################### 9 | 10 | import sys 11 | import time 12 | sys.path.insert(0, '..') # Import the files where the modules are located 13 | 14 | from MyOwnPeer2PeerNode import MyOwnPeer2PeerNode 15 | 16 | node_1 = MyOwnPeer2PeerNode("127.0.0.1", 8001) 17 | node_2 = MyOwnPeer2PeerNode("127.0.0.1", 8002) 18 | node_3 = MyOwnPeer2PeerNode("127.0.0.1", 8003) 19 | 20 | time.sleep(1) 21 | 22 | node_1.start() 23 | node_2.start() 24 | node_3.start() 25 | 26 | time.sleep(1) 27 | 28 | node_1.connect_with_node('127.0.0.1', 8002) 29 | node_2.connect_with_node('127.0.0.1', 8003) 30 | node_3.connect_with_node('127.0.0.1', 8001) 31 | 32 | time.sleep(2) 33 | 34 | node_1.send_to_nodes({ "name" : "Maurice", "number" : 11 }) 35 | 36 | time.sleep(5) 37 | 38 | node_1.stop() 39 | node_2.stop() 40 | node_3.stop() 41 | print('end test') 42 | -------------------------------------------------------------------------------- /examples/MyOwnPeer2PeerNode.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.2 beta (use at your own risk) # 4 | # # 5 | # MyOwnPeer2PeerNode is an example how to use the p2pnet.Node to implement your own peer-to-peer network node. # 6 | # 28/06/2021: Added the new developments on id and max_connections 7 | ####################################################################################################################### 8 | from p2pnetwork.node import Node 9 | 10 | class MyOwnPeer2PeerNode (Node): 11 | 12 | # Python class constructor 13 | def __init__(self, host, port, id=None, callback=None, max_connections=0): 14 | super(MyOwnPeer2PeerNode, self).__init__(host, port, id, callback, max_connections) 15 | print("MyPeer2PeerNode: Started") 16 | 17 | # all the methods below are called when things happen in the network. 18 | # implement your network node behavior to create the required functionality. 19 | 20 | def outbound_node_connected(self, node): 21 | print("outbound_node_connected (" + self.id + "): " + node.id) 22 | 23 | def inbound_node_connected(self, node): 24 | print("inbound_node_connected: (" + self.id + "): " + node.id) 25 | 26 | def inbound_node_disconnected(self, node): 27 | print("inbound_node_disconnected: (" + self.id + "): " + node.id) 28 | 29 | def outbound_node_disconnected(self, node): 30 | print("outbound_node_disconnected: (" + self.id + "): " + node.id) 31 | 32 | def node_message(self, node, data): 33 | print("node_message (" + self.id + ") from " + node.id + ": " + str(data)) 34 | 35 | def node_disconnect_with_outbound_node(self, node): 36 | print("node wants to disconnect with oher outbound node: (" + self.id + "): " + node.id) 37 | 38 | def node_request_to_stop(self): 39 | print("node is requested to stop (" + self.id + "): ") 40 | 41 | -------------------------------------------------------------------------------- /examples/my_own_p2p_application.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.1 beta (use at your own risk) # 4 | # # 5 | # This example show how to derive a own Node class (MyOwnPeer2PeerNode) from p2pnet.Node to implement your own Node # 6 | # implementation. See the MyOwnPeer2PeerNode.py for all the details. In that class all your own application specific # 7 | # details are coded. # 8 | ####################################################################################################################### 9 | 10 | import sys 11 | import time 12 | sys.path.insert(0, '..') # Import the files where the modules are located 13 | 14 | from MyOwnPeer2PeerNode import MyOwnPeer2PeerNode 15 | 16 | node_1 = MyOwnPeer2PeerNode("127.0.0.1", 8001, 1) 17 | node_2 = MyOwnPeer2PeerNode("127.0.0.1", 8002, 2) 18 | node_3 = MyOwnPeer2PeerNode("127.0.0.1", 8003, 3) 19 | 20 | time.sleep(1) 21 | 22 | node_1.start() 23 | node_2.start() 24 | node_3.start() 25 | 26 | time.sleep(1) 27 | 28 | debug = False 29 | node_1.debug = debug 30 | node_2.debug = debug 31 | node_3.debug = debug 32 | 33 | 34 | node_1.connect_with_node('127.0.0.1', 8002) 35 | node_2.connect_with_node('127.0.0.1', 8003) 36 | node_3.connect_with_node('127.0.0.1', 8001) 37 | 38 | time.sleep(2) 39 | 40 | node_1.send_to_nodes("message: Hi there!") 41 | 42 | time.sleep(2) 43 | 44 | print("node 1 is stopping..") 45 | node_1.stop() 46 | 47 | time.sleep(20) 48 | 49 | node_2.send_to_nodes("message: Hi there node 2!") 50 | node_2.send_to_nodes("message: Hi there node 2!") 51 | node_2.send_to_nodes("message: Hi there node 2!") 52 | node_3.send_to_nodes("message: Hi there node 2!") 53 | node_3.send_to_nodes("message: Hi there node 2!") 54 | node_3.send_to_nodes("message: Hi there node 2!") 55 | 56 | time.sleep(10) 57 | 58 | time.sleep(5) 59 | 60 | node_1.stop() 61 | node_2.stop() 62 | node_3.stop() 63 | print('end test') 64 | -------------------------------------------------------------------------------- /examples/my_own_p2p_application_callback.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.1 beta (use at your own risk) # 4 | # # 5 | # This example show how to create your own peer 2 peer network using the callback. So, you do not need to implement # 6 | # a new class. However, it is adviced to implement your own class rather than use the callback. Callback will get you # 7 | # a big and large method implementation. # 8 | ####################################################################################################################### 9 | 10 | import sys 11 | import time 12 | sys.path.insert(0, '..') # Import the files where the modules are located 13 | 14 | from p2pnetwork.node import Node 15 | 16 | # The big callback method that gets all the events that happen inside the p2p network. 17 | # Implement here your own application logic. The event holds the event that occurred within 18 | # the network. The main_node contains the node that is handling the connection with and from 19 | # other nodes. An event is most probably triggered by the connected_node! If there is data 20 | # it is represented by the data variable. 21 | def node_callback(event, main_node, connected_node, data): 22 | try: 23 | if event != 'node_request_to_stop': # node_request_to_stop does not have any connected_node, while it is the main_node that is stopping! 24 | print('Event: {} from main node {}: connected node {}: {}'.format(event, main_node.id, connected_node.id, data)) 25 | 26 | except Exception as e: 27 | print(e) 28 | 29 | # Just for test we spin off multiple nodes, however it is more likely that these nodes are running 30 | # on computers on the Internet! Otherwise we do not have any peer2peer application. 31 | node_1 = Node("127.0.0.1", 8001, callback=node_callback) 32 | node_2 = Node("127.0.0.1", 8002, callback=node_callback) 33 | node_3 = Node("127.0.0.1", 8003, callback=node_callback) 34 | 35 | time.sleep(1) 36 | #node_1.debug = True 37 | #node_2.debug = True 38 | #node_3.debug = True 39 | node_1.start() 40 | node_2.start() 41 | node_3.start() 42 | time.sleep(1) 43 | 44 | node_1.connect_with_node('127.0.0.1', 8002) 45 | node_2.connect_with_node('127.0.0.1', 8003) 46 | node_3.connect_with_node('127.0.0.1', 8001) 47 | 48 | time.sleep(2) 49 | 50 | node_1.send_to_nodes("message: hoi from node 1") 51 | 52 | time.sleep(5) 53 | 54 | node_1.stop() 55 | node_2.stop() 56 | node_3.stop() 57 | 58 | print('end') 59 | -------------------------------------------------------------------------------- /examples/my_own_p2p_application_compression.py: -------------------------------------------------------------------------------- 1 | ####################################################################################################################### 2 | # Author: Maurice Snoeren # 3 | # Version: 0.1 beta (use at your own risk) # 4 | # # 5 | # This example show how to derive a own Node class (MyOwnPeer2PeerNode) from p2pnet.Node to implement your own Node # 6 | # implementation. See the MyOwnPeer2PeerNode.py for all the details. In that class all your own application specific # 7 | # details are coded. # 8 | ####################################################################################################################### 9 | 10 | import sys 11 | import time 12 | sys.path.insert(0, '..') # Import the files where the modules are located 13 | 14 | from MyOwnPeer2PeerNode import MyOwnPeer2PeerNode 15 | 16 | node_1 = MyOwnPeer2PeerNode("127.0.0.1", 8001, 1) 17 | node_2 = MyOwnPeer2PeerNode("127.0.0.1", 8002, 2) 18 | #node_3 = MyOwnPeer2PeerNode("127.0.0.1", 8003, 3) 19 | 20 | time.sleep(1) 21 | 22 | node_1.debug = True 23 | node_2.debug = True 24 | 25 | node_1.start() 26 | node_2.start() 27 | #node_3.start() 28 | 29 | time.sleep(1) 30 | 31 | #node_1.connect_with_node('127.0.0.1', 8002) 32 | node_2.connect_with_node('127.0.0.1', 8001) 33 | #node_3.connect_with_node('127.0.0.1', 8001) 34 | 35 | time.sleep(2) 36 | 37 | node_1.send_to_nodes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", compression="zlib") 38 | node_1.send_to_nodes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", compression="bzip2") 39 | node_1.send_to_nodes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", compression="lzma") 40 | node_1.send_to_nodes({"key": "value", "key2": "value2"}, compression="zlib") 41 | 42 | time.sleep(2) 43 | 44 | print("node 1 is stopping..") 45 | node_1.stop() 46 | 47 | time.sleep(20) 48 | 49 | #node_2.send_to_nodes("message: Hi there node 2!") 50 | #node_2.send_to_nodes("message: Hi there node 2!") 51 | #node_2.send_to_nodes("message: Hi there node 2!") 52 | #node_3.send_to_nodes("message: Hi there node 2!") 53 | #node_3.send_to_nodes("message: Hi there node 2!") 54 | #node_3.send_to_nodes("message: Hi there node 2!") 55 | 56 | time.sleep(10) 57 | 58 | time.sleep(5) 59 | 60 | node_1.stop() 61 | node_2.stop() 62 | #node_3.stop() 63 | print('end test') 64 | -------------------------------------------------------------------------------- /p2pnetwork/tests/test_nodeconnection.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import time 3 | import struct 4 | 5 | from p2pnetwork.node import Node 6 | 7 | """ 8 | Author: Maurice Snoeren 9 | Version: 0.1 beta (use at your own risk) 10 | 11 | Testing the node communication by sending large amount of str and dict data 12 | to see whether the node is correctly handling this. 13 | TODO: testing sending bytes 14 | TODO: bufferoverlow testing 15 | """ 16 | class TestNode(unittest.TestCase): 17 | """Testing the NodeConnection class.""" 18 | 19 | def test_node_send_data_str(self): 20 | """Testing whether NodeConnections handle sending str well enough.""" 21 | global messages 22 | messages = [] 23 | 24 | class MyTestNode (Node): 25 | def __init__(self, host, port): 26 | super(MyTestNode, self).__init__(host, port, None) 27 | global messages 28 | messages.append("mytestnode started") 29 | 30 | def node_message(self, node, data): 31 | global messages 32 | messages.append(type(data)) 33 | messages.append(len(data)) 34 | 35 | node1 = MyTestNode("127.0.0.1", 10001) 36 | node2 = MyTestNode("127.0.0.1", 10002) 37 | node3 = MyTestNode("127.0.0.1", 10003) 38 | 39 | node1.start() 40 | node2.start() 41 | node3.start() 42 | 43 | node1.connect_with_node('127.0.0.1', 10002) 44 | time.sleep(2) 45 | 46 | node3.connect_with_node('127.0.0.1', 10001) 47 | time.sleep(2) 48 | 49 | # Create large message; large than used buffer 4096! 50 | data = "" 51 | for i in range(5000): 52 | data += "a" 53 | 54 | # Send multiple messages after each other (5 * 5000 bytes) 55 | node1.send_to_nodes(data) 56 | node1.send_to_nodes(data) 57 | node1.send_to_nodes(data) 58 | node1.send_to_nodes(data) 59 | node1.send_to_nodes(data) 60 | time.sleep(7) 61 | 62 | node1.stop() 63 | node2.stop() 64 | node3.stop() 65 | node1.join() 66 | node2.join() 67 | node3.join() 68 | 69 | self.assertTrue(len(messages) > 0, "There should have been sent some messages around!") 70 | self.assertEqual(len(messages), 23, "There should have been sent 23 message around!") 71 | 72 | self.assertEqual(messages[0], "mytestnode started", "MyTestNode should have seen this event!") 73 | self.assertEqual(messages[1], "mytestnode started", "MyTestNode should have seen this event!") 74 | self.assertEqual(messages[2], "mytestnode started", "MyTestNode should have seen this event!") 75 | 76 | # Check if all the message are correctly received 77 | for i in range(0, 10, 2): 78 | self.assertEqual(str(messages[3+i]), "") 79 | self.assertEqual(messages[4+i], 5000) 80 | 81 | def test_node_send_data_dict(self): 82 | """Testing whether NodeConnections handle sending dict well enough.""" 83 | global messages 84 | messages = [] 85 | 86 | class MyTestNode (Node): 87 | def __init__(self, host, port): 88 | super(MyTestNode, self).__init__(host, port, None) 89 | global messages 90 | messages.append("mytestnode started") 91 | 92 | def node_message(self, node, data): 93 | global messages 94 | messages.append(type(data)) 95 | messages.append(len(data["values"])) 96 | # messages.append("instance byte:" + isinstance(data, bytes)) 97 | # Check the message here wether it is correct! 98 | 99 | node1 = MyTestNode("127.0.0.1", 10001) 100 | node2 = MyTestNode("127.0.0.1", 10002) 101 | node3 = MyTestNode("127.0.0.1", 10003) 102 | 103 | node1.start() 104 | node2.start() 105 | node3.start() 106 | 107 | node1.connect_with_node('127.0.0.1', 10002) 108 | time.sleep(2) 109 | 110 | node3.connect_with_node('127.0.0.1', 10001) 111 | time.sleep(2) 112 | 113 | # Create large message; large than used buffer 4096! 114 | data = { "type": "My Dict", 115 | "values": [] 116 | } 117 | for i in range(5000): 118 | data["values"].append("i: " + str(i)) 119 | 120 | # Send multiple messages after each other (5 * 5000 bytes) 121 | node1.send_to_nodes(data) 122 | node1.send_to_nodes(data) 123 | node1.send_to_nodes(data) 124 | node1.send_to_nodes(data) 125 | node1.send_to_nodes(data) 126 | time.sleep(7) 127 | 128 | node1.stop() 129 | node2.stop() 130 | node3.stop() 131 | node1.join() 132 | node2.join() 133 | node3.join() 134 | 135 | self.assertTrue(len(messages) > 0, "There should have been sent some messages around!") 136 | self.assertEqual(len(messages), 23, "There should have been sent 23 message around!") 137 | 138 | self.assertEqual(messages[0], "mytestnode started", "MyTestNode should have seen this event!") 139 | self.assertEqual(messages[1], "mytestnode started", "MyTestNode should have seen this event!") 140 | self.assertEqual(messages[2], "mytestnode started", "MyTestNode should have seen this event!") 141 | 142 | # Check if all the message are correctly received 143 | for i in range(0, 10, 2): 144 | self.assertEqual(str(messages[3+i]), "") 145 | self.assertEqual(messages[4+i], 5000) 146 | -------------------------------------------------------------------------------- /p2pnetwork/tests/test_node_compression.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import time 3 | 4 | from p2pnetwork.node import Node 5 | 6 | """ 7 | Author: Maurice Snoeren 8 | Version: 0.1 beta (use at your own risk) 9 | 10 | Testing the compression functionality that has been added. 11 | """ 12 | 13 | class TestNode(unittest.TestCase): 14 | """Testing communication compression of the Node class.""" 15 | 16 | def test_node_compression_zlib(self): 17 | """Testing the zlib compression.""" 18 | global message 19 | message = [] 20 | 21 | # Using the callback we are able to see the events and messages of the Node 22 | def node_callback(event, main_node, connected_node, data): 23 | global message 24 | try: 25 | if event == "node_message": 26 | message.append(event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data)) 27 | 28 | except Exception as e: 29 | message = "exception: " + str(e) 30 | 31 | node1 = Node(host="localhost", port=10001, callback=node_callback) 32 | node2 = Node(host="localhost", port=10002, callback=node_callback) 33 | 34 | node1.start() 35 | node2.start() 36 | time.sleep(2) 37 | 38 | node1.connect_with_node("localhost", 10002) 39 | time.sleep(2) 40 | 41 | node1.send_to_nodes("Hi from node 1!", compression='zlib') 42 | time.sleep(1) 43 | node1_message = message 44 | 45 | node2.send_to_nodes("Hi from node 2!", compression='zlib') 46 | time.sleep(1) 47 | node2_message = message 48 | 49 | node1.stop() 50 | node2.stop() 51 | node1.join() 52 | node2.join() 53 | 54 | time.sleep(10) 55 | 56 | self.assertIn("Hi from node", message[0], "The message is not correctly received") 57 | self.assertIn("Hi from node", message[1], "The message is not correctly received") 58 | 59 | def test_node_compression_lzma(self): 60 | """Testing the lzma compression.""" 61 | global message 62 | message = [] 63 | 64 | # Using the callback we are able to see the events and messages of the Node 65 | def node_callback(event, main_node, connected_node, data): 66 | global message 67 | try: 68 | if event == "node_message": 69 | message.append(event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data)) 70 | 71 | except Exception as e: 72 | message = "exception: " + str(e) 73 | 74 | node1 = Node(host="localhost", port=10001, callback=node_callback) 75 | node2 = Node(host="localhost", port=10002, callback=node_callback) 76 | 77 | node1.start() 78 | node2.start() 79 | time.sleep(2) 80 | 81 | node1.connect_with_node("localhost", 10002) 82 | time.sleep(2) 83 | 84 | node1.send_to_nodes("Hi from node 1!", compression='lzma') 85 | time.sleep(1) 86 | node1_message = message 87 | 88 | node2.send_to_nodes("Hi from node 2!", compression='lzma') 89 | time.sleep(1) 90 | node2_message = message 91 | 92 | node1.stop() 93 | node2.stop() 94 | node1.join() 95 | node2.join() 96 | 97 | time.sleep(10) 98 | 99 | self.assertIn("Hi from node", message[0], "The message is not correctly received") 100 | self.assertIn("Hi from node", message[1], "The message is not correctly received") 101 | 102 | def test_node_compression_bzip2(self): 103 | """Testing the bzip2 compression.""" 104 | global message 105 | message = [] 106 | 107 | # Using the callback we are able to see the events and messages of the Node 108 | def node_callback(event, main_node, connected_node, data): 109 | global message 110 | try: 111 | if event == "node_message": 112 | message.append(event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data)) 113 | 114 | except Exception as e: 115 | message = "exception: " + str(e) 116 | 117 | node1 = Node(host="localhost", port=10001, callback=node_callback) 118 | node2 = Node(host="localhost", port=10002, callback=node_callback) 119 | 120 | node1.start() 121 | node2.start() 122 | time.sleep(2) 123 | 124 | node1.connect_with_node("localhost", 10002) 125 | time.sleep(2) 126 | 127 | node1.send_to_nodes("Hi from node 1!", compression='bzip2') 128 | time.sleep(1) 129 | node1_message = message 130 | 131 | node2.send_to_nodes("Hi from node 2!", compression='bzip2') 132 | time.sleep(1) 133 | node2_message = message 134 | 135 | node1.stop() 136 | node2.stop() 137 | node1.join() 138 | node2.join() 139 | 140 | time.sleep(10) 141 | 142 | self.assertIn("Hi from node", message[0], "The message is not correctly received") 143 | self.assertIn("Hi from node", message[1], "The message is not correctly received") 144 | 145 | def test_node_compression_unknown(self): 146 | """Testing when the compression is unknown.""" 147 | global message 148 | message = [] 149 | 150 | # Using the callback we are able to see the events and messages of the Node 151 | def node_callback(event, main_node, connected_node, data): 152 | global message 153 | try: 154 | if event == "node_message": 155 | message.append(event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data)) 156 | 157 | except Exception as e: 158 | message = "exception: " + str(e) 159 | 160 | node1 = Node(host="localhost", port=10001, callback=node_callback) 161 | node2 = Node(host="localhost", port=10002, callback=node_callback) 162 | 163 | node1.start() 164 | node2.start() 165 | time.sleep(2) 166 | 167 | node1.connect_with_node("localhost", 10002) 168 | time.sleep(2) 169 | 170 | node1.send_to_nodes("Hi from node 1!", compression='unknown') 171 | time.sleep(1) 172 | node1_message = message 173 | 174 | node2.send_to_nodes("Hi from node 2!", compression='unknown') 175 | time.sleep(1) 176 | node2_message = message 177 | 178 | node1.stop() 179 | node2.stop() 180 | node1.join() 181 | node2.join() 182 | 183 | time.sleep(10) 184 | 185 | self.assertEqual(len(message), 0, "No messages should have been send") 186 | 187 | if __name__ == '__main__': 188 | unittest.main() 189 | -------------------------------------------------------------------------------- /GETTING_STARTED.md: -------------------------------------------------------------------------------- 1 | # Getting started with p2pnetwork 2 | This tutorial provides you with a walk through how to use the p2pnetwork framework. If you would like to use this framework, you can use these steps to get familiar with the module. Eventually it is up to you to use and implement your specific details to the p2pnetwork applications. 3 | 4 | This example is also available on github: https://github.com/macsnoeren/python-p2p-network-example.git. 5 | 6 | ## Should I use this module? 7 | **If you would like to create peer-to-peer network applications ... the answer is yes!** The module provides you with all the basic details of peer-to-peer network applications. It starts a node that is able to connect to other nodes and is able to receive connections from other nodes. When running a node, you get all the details using an event based structure. When some node is connecting or sending a message, methods are invokes, so you immediatly can react on it. In other words, implementing your application details. 8 | 9 | Note that it is a framework that provide the basics of a peer-to-peer network application. The basic idea is not to implement application specifics, so the developer is really in the lead. For example, a peer-to-peer network application implements most likely a discovery function. This function discovers the nodes that form the network. You need to implement this on your own. Meaning that you need to design a protocol and implement it within your class. 10 | 11 | ## Example project 12 | In this tutorial we focus on a peer-to-peer file sharing network application. The application forms a peer-to-peer network and is able to discover other nodes. Nodes share a directory on their computer that hold files to be shared within the network. A node is able to search for a specific file and download the file respectively. 13 | 14 | ## Step 1: Install the module 15 | To install the package for you to use (https://pypi.org/project/p2pnetwork/): 16 | ```` 17 | pip install p2pnetwork 18 | ```` 19 | 20 | ## Step 2: Create your project 21 | Create a directory on your computer and create two files. The first file is the class that implements the file sharing peer-to-peer network application. This class extends from the Node class of the p2p-network module. The second file is the python executable file that initiates the class and implements a console interface to interact with our file sharing node. When you are ready the directory should like this: 22 | ```` 23 | FileSharingNode.py 24 | file_sharing_node.py 25 | ```` 26 | ## Step 3: Setup the file sharing class 27 | Open the file ````FileSharingNode.py```` and create the class FileSharingNode that extends from the Node class of the p2pnetwork modules. The code below shows the example. 28 | ````python 29 | from p2pnetwork.node import Node 30 | 31 | class FileSharingNode (Node): 32 | 33 | def __init__(self, host, port, id=None, callback=None, max_connections=0): 34 | super(FileSharingNode, self).__init__(host, port, id, callback, max_connections) 35 | 36 | def outbound_node_connected(self, connected_node): 37 | print("outbound_node_connected: " + connected_node.id) 38 | 39 | def inbound_node_connected(self, connected_node): 40 | print("inbound_node_connected: " + connected_node.id) 41 | 42 | def inbound_node_disconnected(self, connected_node): 43 | print("inbound_node_disconnected: " + connected_node.id) 44 | 45 | def outbound_node_disconnected(self, connected_node): 46 | print("outbound_node_disconnected: " + connected_node.id) 47 | 48 | def node_message(self, connected_node, data): 49 | print("node_message from " + connected_node.id + ": " + str(data)) 50 | 51 | def node_disconnect_with_outbound_node(self, connected_node): 52 | print("node wants to disconnect with oher outbound node: " + connected_node.id) 53 | 54 | def node_request_to_stop(self): 55 | print("node is requested to stop!") 56 | 57 | ```` 58 | ## Step 4: Setup console application 59 | Open the file ````file_sharing_node.py```` and create a console application that instantiates the ````FileSharingNode.py````. 60 | 61 | ````python 62 | import sys 63 | 64 | from FileSharingNode import FileSharingNode 65 | 66 | # The port to listen for incoming node connections 67 | port = 9876 # default 68 | 69 | # Syntax file_sharing_node.py port 70 | if len(sys.argv) > 1: 71 | port = int(sys.argv[1]) 72 | 73 | # Instantiate the node FileSharingNode, it creates a thread to handle all functionality 74 | node = FileSharingNode("127.0.0.1", port) 75 | 76 | # Start the node, if not started it shall not handle any requests! 77 | node.start() 78 | 79 | # The method prints the help commands text to the console 80 | def print_help(): 81 | print("stop - Stops the application.") 82 | print("help - Prints this help text.") 83 | 84 | # Implement a console application 85 | command = input("? ") 86 | while ( command != "stop" ): 87 | if ( command == "help" ): 88 | print_help() 89 | 90 | command = input("? ") 91 | 92 | node.stop() 93 | ```` 94 | Running this example code results in the following console output: 95 | ```` 96 | Initialisation of the Node on port: 9876 on node (e5ab15fdf31dcf6f0c4490d5ebb216f6ee8a6f86fca5a33bcbc8b63d7c963b2caf6c46410d5667bcd792fc02d7652e7cb50475d949c45506c6585f059637a449) 97 | ? help 98 | stop - Stops the application. 99 | help - Prints this help text. 100 | ? stop 101 | node is requested to stop! 102 | Node stopping... 103 | Node stopped 104 | ```` 105 | 106 | From this moment, you have already a bare minimum application that implements the framework p2pnetwork. No application specifics have been coded yet. The node is already listening to incoming connections and able to connect to other nodes at your command. From this point, we will add the required functionality to the application. In order to test this applications, you need to run the application twice on different ports. In this case you could open two terminals and run the following commands: 107 | 1. ````python file_sharing_node.py 9876```` 108 | 2. ````python file_sharing_node.py 9877```` 109 | 110 | ## Step 5: Connect to another node 111 | We are going to add the functionality to connect with another node. In this case, you should spin off in another terminal the application on port 9877: ````file_sharing_node.py 9877````. When the user wants to connect to another node, you need to provide a host/ip and port number. Add the following code to ````file_sharing_node.py````. 112 | 113 | ````python 114 | .... 115 | def connect_to_node(node:FileSharingNode): 116 | host = input("host or ip of node? ") 117 | port = int(input("port? ")) 118 | node.connect_with_node(host, port) 119 | 120 | # Implement a console application 121 | command = input("? ") 122 | while ( command != "stop" ): 123 | if ( command == "help" ): 124 | print_help() 125 | if ( command == "connect"): 126 | connect_to_node(node) 127 | 128 | command = input("? ") 129 | .... 130 | ```` 131 | When you run the application and connect to another node, you immediatly see the invoked message of the methods in the ````FileSharingNode.py````. Below the console output of the application. When you connect to another node, it will be placed in the outbound list, because it is an outgoing connection. 132 | ```` 133 | $>file_sharing_node.py 9876 134 | Initialisation of the Node on port: 9876 on node (ceccce67f62d2d067bca76901ba3da2028539754b451afa81b0ffe2fcc64e070386f5573ee6cf4da9223202d363c3aeb035b360ad5bd95985e1797e93cd93b28) 135 | ? connect 136 | host or ip of node? localhost 137 | port? 9877 138 | outbound_node_connected: df643d3c0063b40fcb0c185a9f39e4743551ef426c9acc0355cb01b04288dd87909f7d2ca74d594b266ee6dd149d8e2b3a82c4ee9584382ec4e91230aad1118d 139 | ```` 140 | This application running at port 9877 is receives the connection. Therefore, you see an inbound message. The incoming connection from the node is added to the inbound list, because it is a connection with us. 141 | ```` 142 | $>file_sharing_node.py 9877 143 | Initialisation of the Node on port: 9877 on node (df643d3c0063b40fcb0c185a9f39e4743551ef426c9acc0355cb01b04288dd87909f7d2ca74d594b266ee6dd149d8e2b3a82c4ee9584382ec4e91230aad1118d) 144 | ? inbound_node_connected: ceccce67f62d2d067bca76901ba3da2028539754b451afa81b0ffe2fcc64e070386f5573ee6cf4da9223202d363c3aeb035b360ad5bd95985e1797e93cd93b28 145 | ```` 146 | You already see that you have a lot of control of what happens. Immediatly, you get notified when nodes are connected. Eventually, how nodes are connected is not really important when messages are send to each other. 147 | 148 | _work in progress..._ -------------------------------------------------------------------------------- /p2pnetwork/nodeconnection.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import time 3 | import threading 4 | import json 5 | import zlib, bz2, lzma, base64 6 | 7 | """ 8 | Author : Maurice Snoeren 9 | Version: 0.3 beta (use at your own risk) 10 | Date: 7-5-2020 11 | 12 | Python package p2pnet for implementing decentralized peer-to-peer network applications 13 | """ 14 | 15 | 16 | class NodeConnection(threading.Thread): 17 | """The class NodeConnection is used by the class Node and represent the TCP/IP socket connection with another node. 18 | Both inbound (nodes that connect with the server) and outbound (nodes that are connected to) are represented by 19 | this class. The class contains the client socket and hold the id information of the connecting node. Communication 20 | is done by this class. When a connecting node sends a message, the message is relayed to the main node (that created 21 | this NodeConnection in the first place). 22 | 23 | Instantiates a new NodeConnection. Do not forget to start the thread. All TCP/IP communication is handled by this 24 | connection. 25 | main_node: The Node class that received a connection. 26 | sock: The socket that is assiociated with the client connection. 27 | id: The id of the connected node (at the other side of the TCP/IP connection). 28 | host: The host/ip of the main node. 29 | port: The port of the server of the main node.""" 30 | 31 | def __init__(self, main_node, sock, id, host, port): 32 | """Instantiates a new NodeConnection. Do not forget to start the thread. All TCP/IP communication is handled by this connection. 33 | main_node: The Node class that received a connection. 34 | sock: The socket that is assiociated with the client connection. 35 | id: The id of the connected node (at the other side of the TCP/IP connection). 36 | host: The host/ip of the main node. 37 | port: The port of the server of the main node.""" 38 | 39 | self.host = host 40 | self.port = port 41 | self.main_node = main_node 42 | self.sock = sock 43 | self.terminate_flag = threading.Event() 44 | 45 | # The id of the connected node 46 | self.id = str(id) # Make sure the ID is a string 47 | 48 | # End of transmission character for the network streaming messages. 49 | self.EOT_CHAR = 0x04.to_bytes(1, 'big') 50 | 51 | # Indication that the message has been compressed 52 | self.COMPR_CHAR = 0x02.to_bytes(1, 'big') 53 | 54 | # Datastore to store additional information concerning the node. 55 | self.info = {} 56 | 57 | # Use socket timeout to determine problems with the connection 58 | self.sock.settimeout(10.0) 59 | 60 | self.main_node.debug_print( 61 | "NodeConnection: Started with client (" + self.id + ") '" + self.host + ":" + str(self.port) + "'") 62 | super(NodeConnection, self).__init__() 63 | 64 | def compress(self, data, compression): 65 | """Compresses the data given the type. It is used to provide compression to lower the network traffic in case of 66 | large data chunks. It stores the compression type inside the data, so it can be easily retrieved.""" 67 | 68 | self.main_node.debug_print(self.id + ":compress:" + compression) 69 | self.main_node.debug_print(self.id + ":compress:input: " + str(data)) 70 | 71 | compressed = data 72 | 73 | try: 74 | if compression == 'zlib': 75 | compressed = base64.b64encode(zlib.compress(data, 6) + b'zlib') 76 | 77 | elif compression == 'bzip2': 78 | compressed = base64.b64encode(bz2.compress(data) + b'bzip2') 79 | 80 | elif compression == 'lzma': 81 | compressed = base64.b64encode(lzma.compress(data) + b'lzma') 82 | 83 | else: 84 | self.main_node.debug_print(self.id + ":compress:Unknown compression") 85 | return None 86 | 87 | except Exception as e: 88 | self.main_node.debug_print("compress: exception: " + str(e)) 89 | 90 | self.main_node.debug_print(self.id + ":compress:b64encode:" + str(compressed)) 91 | self.main_node.debug_print( 92 | self.id + ":compress:compression:" + str(int(10000 * len(compressed) / len(data)) / 100) + "%") 93 | 94 | return compressed 95 | 96 | def decompress(self, compressed): 97 | """Decompresses the data given the type. It is used to provide compression to lower the network traffic in case of 98 | large data chunks.""" 99 | self.main_node.debug_print(self.id + ":decompress:input: " + str(compressed)) 100 | compressed = base64.b64decode(compressed) 101 | self.main_node.debug_print(self.id + ":decompress:b64decode: " + str(compressed)) 102 | 103 | try: 104 | if compressed[-4:] == b'zlib': 105 | compressed = zlib.decompress(compressed[0:len(compressed) - 4]) 106 | 107 | elif compressed[-5:] == b'bzip2': 108 | compressed = bz2.decompress(compressed[0:len(compressed) - 5]) 109 | 110 | elif compressed[-4:] == b'lzma': 111 | compressed = lzma.decompress(compressed[0:len(compressed) - 4]) 112 | except Exception as e: 113 | print("Exception: " + str(e)) 114 | 115 | self.main_node.debug_print(self.id + ":decompress:result: " + str(compressed)) 116 | 117 | return compressed 118 | 119 | def send(self, data, encoding_type='utf-8', compression='none'): 120 | """Send the data to the connected node. The data can be pure text (str), dict object (send as json) and bytes object. 121 | When sending bytes object, it will be using standard socket communication. A end of transmission character 0x04 122 | utf-8/ascii will be used to decode the packets ate the other node. When the socket is corrupted the node connection 123 | is closed. Compression can be enabled by using zlib, bzip2 or lzma. When enabled the data is compressed and send to 124 | the client. This could reduce the network bandwith when sending large data chunks. 125 | """ 126 | if isinstance(data, str): 127 | try: 128 | if compression == 'none': 129 | self.sock.sendall(data.encode(encoding_type) + self.EOT_CHAR) 130 | else: 131 | data = self.compress(data.encode(encoding_type), compression) 132 | if data != None: 133 | self.sock.sendall(data + self.COMPR_CHAR + self.EOT_CHAR) 134 | 135 | except Exception as e: # Fixed issue #19: When sending is corrupted, close the connection 136 | self.main_node.debug_print("nodeconnection send: Error sending data to node: " + str(e)) 137 | self.stop() # Stopping node due to failure 138 | 139 | elif isinstance(data, dict): 140 | try: 141 | if compression == 'none': 142 | self.sock.sendall(json.dumps(data).encode(encoding_type) + self.EOT_CHAR) 143 | else: 144 | data = self.compress(json.dumps(data).encode(encoding_type), compression) 145 | if data != None: 146 | self.sock.sendall(data + self.COMPR_CHAR + self.EOT_CHAR) 147 | 148 | except TypeError as type_error: 149 | self.main_node.debug_print('This dict is invalid') 150 | self.main_node.debug_print(type_error) 151 | 152 | except Exception as e: # Fixed issue #19: When sending is corrupted, close the connection 153 | self.main_node.debug_print("nodeconnection send: Error sending data to node: " + str(e)) 154 | self.stop() # Stopping node due to failure 155 | 156 | elif isinstance(data, bytes): 157 | try: 158 | if compression == 'none': 159 | self.sock.sendall(data + self.EOT_CHAR) 160 | else: 161 | data = self.compress(data, compression) 162 | if data != None: 163 | self.sock.sendall(data + self.COMPR_CHAR + self.EOT_CHAR) 164 | 165 | except Exception as e: # Fixed issue #19: When sending is corrupted, close the connection 166 | self.main_node.debug_print("nodeconnection send: Error sending data to node: " + str(e)) 167 | self.stop() # Stopping node due to failure 168 | 169 | else: 170 | self.main_node.debug_print('datatype used is not valid plese use str, dict (will be send as json) or bytes') 171 | 172 | def stop(self): 173 | """Terminates the connection and the thread is stopped. Stop the node client. Please make sure you join the thread.""" 174 | self.terminate_flag.set() 175 | 176 | def parse_packet(self, packet): 177 | """Parse the packet and determines wheter it has been send in str, json or byte format. It returns 178 | the according data.""" 179 | if packet.find(self.COMPR_CHAR) == len(packet) - 1: # Check if packet was compressed 180 | packet = self.decompress(packet[0:-1]) 181 | 182 | try: 183 | packet_decoded = packet.decode('utf-8') 184 | 185 | try: 186 | return json.loads(packet_decoded) 187 | 188 | except json.decoder.JSONDecodeError: 189 | return packet_decoded 190 | 191 | except UnicodeDecodeError: 192 | return packet 193 | 194 | # Required to implement the Thread. This is the main loop of the node client. 195 | def run(self): 196 | """The main loop of the thread to handle the connection with the node. Within the 197 | main loop the thread waits to receive data from the node. If data is received 198 | the method node_message will be invoked of the main node to be processed.""" 199 | buffer = b'' # Hold the stream that comes in! 200 | 201 | while not self.terminate_flag.is_set(): 202 | chunk = b'' 203 | 204 | try: 205 | chunk = self.sock.recv(4096) 206 | 207 | except socket.timeout: 208 | self.main_node.debug_print("NodeConnection: timeout") 209 | 210 | except Exception as e: 211 | self.terminate_flag.set() # Exception occurred terminating the connection 212 | self.main_node.debug_print('Unexpected error') 213 | self.main_node.debug_print(e) 214 | 215 | # BUG: possible buffer overflow when no EOT_CHAR is found => Fix by max buffer count or so? 216 | if chunk != b'': 217 | buffer += chunk 218 | eot_pos = buffer.find(self.EOT_CHAR) 219 | 220 | while eot_pos > 0: 221 | packet = buffer[:eot_pos] 222 | buffer = buffer[eot_pos + 1:] 223 | 224 | self.main_node.message_count_recv += 1 225 | self.main_node.node_message(self, self.parse_packet(packet)) 226 | 227 | eot_pos = buffer.find(self.EOT_CHAR) 228 | 229 | time.sleep(0.01) 230 | 231 | # IDEA: Invoke (event) a method in main_node so the user is able to send a bye message to the node before it is closed? 232 | self.sock.settimeout(None) 233 | self.sock.close() 234 | self.main_node.node_disconnected( 235 | self) # Fixed issue #19: Send to main_node when a node is disconnected. We do not know whether it is inbounc or outbound. 236 | self.main_node.debug_print("NodeConnection: Stopped") 237 | 238 | def set_info(self, key, value): 239 | self.info[key] = value 240 | 241 | def get_info(self, key): 242 | return self.info[key] 243 | 244 | def __str__(self): 245 | return 'NodeConnection: {}:{} <-> {}:{} ({})'.format(self.main_node.host, self.main_node.port, self.host, 246 | self.port, self.id) 247 | 248 | def __repr__(self): 249 | return ' Connection {}:{}>'.format(self.main_node.host, self.main_node.port, 250 | self.host, self.port) 251 | 252 | def __hash__(self): 253 | return hash(self.main_node.id + self.id) 254 | 255 | def __eq__(self, other): 256 | return self.main_node == other.main_node and self.id == other.id 257 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Badges](https://img.shields.io/github/repo-size/macsnoeren/python-p2p-network) 2 | ![Badges](https://img.shields.io/github/last-commit/macsnoeren/python-p2p-network) 3 | ![Badges](https://img.shields.io/github/stars/macsnoeren/python-p2p-network) 4 | ![Badges](https://img.shields.io/github/v/release/macsnoeren/python-p2p-network) 5 | 6 | # Python implementation of a peer-to-peer decentralized network 7 | This project provides a basic and simple peer-to-peer decentralized network classes (framework) to build your own network. Basic functionality of the nodes and the connection to and from these nodes has been implemented. Application specific functionality is up to you to implement yourself. The intention of the module is to provide a good basis, without specific implementation, so everyone is really free to implement like they would like to do. 8 | 9 | You can use the project to implement a peer-to-peer decentralized network application, like Bitcoin or file sharing applications. I have used this software to provide my students, during a technical introduction to Blockchain, basic functionality. So, they were able to focus on how they would like to implement the Blockchain functionality and protocols. Without some direction from my side. Some of the students have used the code base to implement their application in C# or C++, for example. That is the freedom I would like to give to everyone. 10 | 11 | To install the package for you to use (https://pypi.org/project/p2pnetwork/): 12 | ```` 13 | pip install p2pnetwork 14 | ```` 15 | See p2pnetwork in action https://github.com/macsnoeren/python-p2p-secure-node. This SecureNode implements a node that communicates securely between the nodes. A good example how a specific application is created by using this framework. 16 | 17 | # Evolution of the software 18 | While I started this project in the year 2018, it was mainly focussed to provide my students some software to be able to implement a peer-to-peer decentralized network. Without the hassle to design and create everything by themselves. While I did not have any experience with Python yet and there was not much time, I put everything in place in a very large pace. One of my students was annoyed by the camelCase programming style, while the Python community uses PEP-8. So, Christian decided to help me out and structured the software to the PEP style. Two years later, Samuel decided to clean up the code and create a real module from it. From then, I decided to jump in again and made the proposed changes, while maintaining the intention of the software: basic peer-to-peer decentralized functionality without specific implementation of protocols, so the programmer is able to freely implement these on their own. I still think that the software is a good basis and already have a new goal to use this software for a decentralized security application. 19 | 20 | On github I was wandering around and noticed that others contributed as well to the code. No pull request, but still nice things. Therefore, I have not transformed the Python software to a package to be available on pypi.org. Anyway, thanks for all the collaboration and I hope you will still help me out and others will join as well. It is possible to develop more specific applications by other modules and classes. Adding these to the repository will create a nice overview about the possibilities of these kind of applications. 21 | 22 | # Design 23 | At first glance, peer-to-peer decentralized network applications are complex and difficult. While you need to provide some networking functionality on application level, the architecture is really simple. You have a network of the "same" nodes. The "same" means the same application (or an application that implements the same protocol). 24 | 25 | Nodes are connected with each other. This means that each node provides a TCP/IP server on a specific port to provide inbound nodes to connect. The same node is able to connect to other nodes; called outbound nodes. When a node has a lot of connections with nodes in the network, the node will get most likely the required messages. You are able to send a message over the TCP/IP channel to the connected (inbound and outbound) nodes. How they react to the messages is in your hands. When you would like to implement discovery, meaning to see which nodes are connected within the network and see if you would like to connect to those, you need to relay this message to the other nodes connected to you. Note that you need to make sure that the messages will not echo around, but that you keep track which messages you have received. 26 | 27 | How to optimize these node connections depend on what you would like to solve. When providing file sharing, you would like to have a lot of connections when nodes have a large bandwith. However, when you are running Bitcoin, you would like to have your connections spread over the world to minimize the single identity problem. 28 | 29 | ## You have two options 30 | Because of my lack of Python experience, I started off with an event scheme that is used within C. When an event occurred, a callback function is called with the necessary variables to be able to process the request and implement the network protocol you desire. 31 | 32 | However, having a class and being able to extend the class with your own implementation is much nicer. Therefore, I started to change the code towards this new scheme. While maintaining the callback functionality, while my students where already busy. I could not let them be victim from my changes. 33 | 34 | So, you have therefore two options: 35 | 1. Implement your p2p application by extending Node and NodeConnection classes 36 | 2. Implement your p2p application with one callback function 37 | 38 | Examples have been provided by the package. These files can be found in the examples directory. My preference is to extend the classes, so we could build on each other's ideas in the future. 39 | 40 | ## Option 1: Implement your p2p application by extending Node and NodeConnection classes 41 | This option is preferred and gives the most flexibility. To implement your p2p network application, you could also extend the classes Node and/or NodeConnection. At least you need to extend the class Node with your own implementation. To implement the application specific functionality, you override the methods that represent the events. You are able to create different classes and methods to provide the code to implement the application protocol and functionality. While more files are involved an example is given by the next sections. 42 | 43 | ### Extend class Node 44 | Extending the class Node is easy. Make sure you override at least all the events. Whenever, you extend the class, it is not possible to use the callback function anymore. See the example below. You can also check the file examples/MyOwnPeer2PeerNode.py. 45 | 46 | ````python 47 | from p2pnetwork.node import Node 48 | 49 | class MyOwnPeer2PeerNode (Node): 50 | # Python class constructor 51 | def __init__(self, host, port, id=None, callback=None, max_connections=0): 52 | super(MyOwnPeer2PeerNode, self).__init__(host, port, id, callback, max_connections) 53 | 54 | def outbound_node_connected(self, connected_node): 55 | print("outbound_node_connected: " + connected_node.id) 56 | 57 | def inbound_node_connected(self, connected_node): 58 | print("inbound_node_connected: " + connected_node.id) 59 | 60 | def inbound_node_disconnected(self, connected_node): 61 | print("inbound_node_disconnected: " + connected_node.id) 62 | 63 | def outbound_node_disconnected(self, connected_node): 64 | print("outbound_node_disconnected: " + connected_node.id) 65 | 66 | def node_message(self, connected_node, data): 67 | print("node_message from " + connected_node.id + ": " + str(data)) 68 | 69 | def node_disconnect_with_outbound_node(self, connected_node): 70 | print("node wants to disconnect with oher outbound node: " + connected_node.id) 71 | 72 | def node_request_to_stop(self): 73 | print("node is requested to stop!") 74 | 75 | # OPTIONAL 76 | # If you need to override the NodeConection as well, you need to 77 | # override this method! In this method, you can initiate 78 | # you own NodeConnection class. 79 | def create_new_connection(self, connection, id, host, port): 80 | return MyOwnNodeConnection(self, connection, id, host, port) 81 | ```` 82 | ### Extend class NodeConnection 83 | The NodeConnection class only hold the TCP/IP connection with the other node, to manage the different connections to and from the main node. It does not implement application specific elements. Mostly, you will only need to extend the Node class. However, when you would like to create your own NodeConnection class you can do this. Make sure that you override ````create_new_connection(self, connection, id, host, port)```` in the class Node, to make sure you initiate your own NodeConnection class. The example below shows some example. 84 | 85 | ````python 86 | from p2pnetwork.node import Node 87 | 88 | class MyOwnPeer2PeerNode (Node): 89 | # Python class constructor 90 | def __init__(self, host, port, id=None, callback=None, max_connections=0): 91 | super(MyOwnPeer2PeerNode, self).__init__(host, port, id, callback, max_connections) 92 | 93 | # Override event functions... 94 | 95 | # Override this method to initiate your own NodeConnection class. 96 | def create_new_connection(self, connection, id, host, port): 97 | return MyOwnNodeConnection(self, connection, id, host, port) 98 | ```` 99 | 100 | ````python 101 | from p2pnetwork.nodeconnection import NodeConnection 102 | 103 | class MyOwnNodeConnection (NodeConnection): 104 | # Python class constructor 105 | def __init__(self, main_node, sock, id, host, port): 106 | super(MyOwnNodeConnection, self).__init__(main_node, sock, id, host, port) 107 | 108 | # Check yourself what you would like to change and override! See the 109 | # documentation and code of the nodeconnection class. 110 | ```` 111 | 112 | ### Using your new classes 113 | You have extended the Node class and maybe also the NodeConnection class. The next aspect it to use your new p2p network application by using these classes. You create a new python file and start using your classes. See the example below. Check the file example/my_own_p2p_application.py for this implementation. 114 | 115 | ````python 116 | import sys 117 | import time 118 | 119 | from MyOwnPeer2PeerNode import MyOwnPeer2PeerNode 120 | 121 | node = MyOwnPeer2PeerNode("127.0.0.1", 10001) 122 | time.sleep(1) 123 | 124 | # Do not forget to start your node! 125 | node.start() 126 | time.sleep(1) 127 | 128 | # Connect with another node, otherwise you do not create any network! 129 | node.connect_with_node('127.0.0.1', 10002) 130 | time.sleep(2) 131 | 132 | # Example of sending a message to the nodes (dict). 133 | node.send_to_nodes({"message": "Hi there!"}) 134 | 135 | time.sleep(5) # Create here your main loop of the application 136 | 137 | node.stop() 138 | ```` 139 | 140 | ## Option 2: Implement your p2p application with one callback function 141 | While this is the least preferable method, you are in the lead! You need to create a callback method and spin off the Node from the module p2pnet. All events that happen within the network will be transferred to the callback function. All application specific functionality can be implemented within this callback and the methods provided by the classes Node and NodeConnection. See below an example of an implementation. You can check the file examples/my_own_p2p_application_callback.py for the full implementation. 142 | 143 | ````python 144 | import time 145 | from p2pnetwork.node import Node 146 | 147 | # node_callback 148 | # event : event name 149 | # node : the node (Node) that holds the node connections 150 | # connected_node: the node (NodeConnection) that is involved 151 | # data : data that is send by the node (could be empty) 152 | def node_callback(event, node, connected_node, data): 153 | try: 154 | if event != 'node_request_to_stop': # node_request_to_stop does not have any connected_node, while it is the main_node that is stopping! 155 | print('Event: {} from main node {}: connected node {}: {}'.format(event, node.id, connected_node.id, data)) 156 | 157 | except Exception as e: 158 | print(e) 159 | 160 | # The main node that is able to make connections to other nodes 161 | # and accept connections from other nodes on port 8001. 162 | node = Node("127.0.0.1", 10001, callback=node_callback) 163 | 164 | # Do not forget to start it, it spins off a new thread! 165 | node.start() 166 | time.sleep(1) 167 | 168 | # Connect to another node, otherwise you do not have any network. 169 | node.connect_with_node('127.0.0.1', 10002) 170 | time.sleep(2) 171 | 172 | # Send some message to the other nodes 173 | node.send_to_nodes('{"message": "hoi from node 1"}') 174 | 175 | time.sleep(5) # Replace this sleep with your main loop! 176 | 177 | # Gracefully stop the node. 178 | node.stop() 179 | ```` 180 | 181 | ## Events that can occur 182 | 183 | ### outbound_node_connected 184 | The node connects with another node - ````node.connect_with_node('127.0.0.1', 8002)```` - and the connection is successful. While the basic functionality is to exchange the node id's, no user data is involved. 185 | 186 | ### inbound_node_connected 187 | Another node has made a connection with this node and the connection is successful. While the basic functionality is to exchange the node id's, no user data is involved. 188 | 189 | ### outbound_node_disconnected 190 | A node, to which we had made a connection in the past, is disconnected. 191 | 192 | ### inbound_node_disconnected 193 | A node, that had made a connection with us in the past, is disconnected. 194 | 195 | ### node_message 196 | A node - ```` connected_node ```` - sends a message. At this moment the basic functionality expects JSON format. It tries to decode JSON when the message is received. If it is not possible, the message is rejected. 197 | 198 | ### node_disconnect_with_outbound_node 199 | The application actively wants to disconnect the outbound node, a node with which we had made a connection in the past. You could send some last message to the node, that you are planning to disconnect, for example. 200 | 201 | ### node_request_to_stop 202 | The main node, also the application, is stopping itself. Note that the variable connected_node is empty, while there is no connected node involved. 203 | 204 | # Debugging 205 | 206 | When things go wrong, you could enable debug messages of the Node class. The class shows these messages in the console and shows all the details of what happens within the class. To enable debugging for a node, use the code example below. 207 | 208 | ````python 209 | node = Node("127.0.0.1", 10001) 210 | node.debug = True 211 | ```` 212 | 213 | # Unit testing 214 | 215 | Several unit tests have been implemented to make sure all the functionality of the provided classes are working correctly. The tests can be executed using Tox. This can be easily installed by ```pip install tox```. To run these tests, you can use the following code: 216 | 217 | ````bash 218 | $ tox 219 | ```` 220 | 221 | # Example 222 | 223 | Examples are available in the github repository of this project: https://github.com/macsnoeren/python-p2p-network. All examples can be found in the directory examples. 224 | 225 | # Node and NodeConnection class 226 | 227 | See the Python documentation for all the details of these classes. 228 | 229 | # Show case: SecureNode 230 | As a show case, I have created the SecureNode class that extends the Node class. This node uses JSON, hashing and signing to communicate between the nodes. My main thought with this secure node is to be able to exchange data securely with each other and give others permissions to read the data, for example. You are the owner of your data! Anyway, some project that I am currently working on. See the documentation of this specific class file. 231 | 232 | ````python 233 | import sys 234 | import time 235 | 236 | from p2pnetwork.securenode import SecureNode 237 | 238 | node = SecureNode("127.0.0.1", 10001) 239 | time.sleep(1) 240 | 241 | node.start() 242 | ```` 243 | An example node that uses SecureNode class is found in the example directory on github: ````secure_node.py````. 244 | -------------------------------------------------------------------------------- /p2pnetwork/node.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import time 3 | import threading 4 | import random 5 | import hashlib 6 | 7 | from p2pnetwork.nodeconnection import NodeConnection 8 | 9 | """ 10 | Author: Maurice Snoeren 11 | Version: 0.3 beta (use at your own risk) 12 | Date: 7-5-2020 13 | 14 | Python package p2pnet for implementing decentralized peer-to-peer network applications 15 | 16 | TODO: Also create events when things go wrong, like a connection with a node has failed. 17 | """ 18 | 19 | class Node(threading.Thread): 20 | """Implements a node that is able to connect to other nodes and is able to accept connections from other nodes. 21 | After instantiation, the node creates a TCP/IP server with the given port. 22 | 23 | Create instance of a Node. If you want to implement the Node functionality with a callback, you should 24 | provide a callback method. It is preferred to implement a new node by extending this Node class. 25 | host: The host name or ip address that is used to bind the TCP/IP server to. 26 | port: The port number that is used to bind the TCP/IP server to. 27 | callback: (optional) The callback that is invoked when events happen inside the network 28 | def node_callback(event, main_node, connected_node, data): 29 | event: The event string that has happened. 30 | main_node: The main node that is running all the connections with the other nodes. 31 | connected_node: Which connected node caused the event. 32 | data: The data that is send by the connected node.""" 33 | 34 | def __init__(self, host, port, id=None, callback=None, max_connections=1): 35 | """Create instance of a Node. If you want to implement the Node functionality with a callback, you should 36 | provide a callback method. It is preferred to implement a new node by extending this Node class. 37 | host: The host name or ip address that is used to bind the TCP/IP server to. 38 | port: The port number that is used to bind the TCP/IP server to. 39 | id: (optional) This id will be associated with the node. When not given a unique ID will be created. 40 | callback: (optional) The callback that is invoked when events happen inside the network. 41 | max_connections: (optional) limiting the maximum nodes that are able to connect to this node.""" 42 | super(Node, self).__init__() 43 | 44 | # When this flag is set, the node will stop and close 45 | self.terminate_flag = threading.Event() 46 | 47 | # Server details, host (or ip) to bind to and the port 48 | self.host = host 49 | self.port = port 50 | 51 | # Events are send back to the given callback 52 | self.callback = callback 53 | 54 | # Nodes that have established a connection with this node 55 | self.nodes_inbound = set() # Nodes that are connect with us N->(US) 56 | 57 | # Nodes that this nodes is connected to 58 | self.nodes_outbound = set() # Nodes that we are connected to (US)->N 59 | 60 | # A list of nodes that should be reconnected to whenever the connection was lost 61 | self.reconnect_to_nodes = [] 62 | 63 | # Create a unique ID for each node if the ID is not given. 64 | if id == None: 65 | self.id = self.generate_id() 66 | 67 | else: 68 | self.id = str(id) # Make sure the ID is a string! 69 | 70 | # Start the TCP/IP server 71 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 72 | self.init_server() 73 | 74 | # Message counters to make sure everyone is able to track the total messages 75 | self.message_count_send = 0 76 | self.message_count_recv = 0 77 | self.message_count_rerr = 0 78 | 79 | # Connection limit of inbound nodes (nodes that connect to us) 80 | self.max_connections = max_connections 81 | 82 | # Debugging on or off! 83 | self.debug = False 84 | 85 | @property 86 | def all_nodes(self): 87 | """Return a list of all the nodes, inbound and outbound, that are connected with this node.""" 88 | return self.nodes_inbound | self.nodes_outbound 89 | 90 | def debug_print(self, message): 91 | """When the debug flag is set to True, all debug messages are printed in the console.""" 92 | if self.debug: 93 | print("DEBUG (" + self.id + "): " + message) 94 | 95 | def generate_id(self): 96 | """Generates a unique ID for each node.""" 97 | id = hashlib.sha512() 98 | t = self.host + str(self.port) + str(random.randint(1, 99999999)) 99 | id.update(t.encode('ascii')) 100 | return id.hexdigest() 101 | 102 | def init_server(self): 103 | """Initialization of the TCP/IP server to receive connections. It binds to the given host and port.""" 104 | print("Initialisation of the Node on port: " + str(self.port) + " on node (" + self.id + ")") 105 | self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 106 | self.sock.bind((self.host, self.port)) 107 | self.sock.settimeout(10.0) 108 | self.sock.listen(1) 109 | 110 | def print_connections(self): 111 | """Prints the connection overview of the node. How many inbound and outbound connections have been made.""" 112 | print("Node connection overview:") 113 | print("- Total nodes connected with us: %d" % len(self.nodes_inbound)) 114 | print("- Total nodes connected to : %d" % len(self.nodes_outbound)) 115 | 116 | def send_to_nodes(self, data, exclude=[], compression='none'): 117 | """ Send a message to all the nodes that are connected with this node. data is a python variable which is 118 | converted to JSON that is send over to the other node. exclude list gives all the nodes to which this 119 | data should not be sent. 120 | TODO: When sending was not successfull, the user is not notified.""" 121 | self.message_count_send = self.message_count_send + 1 122 | for n in self.nodes_inbound: 123 | if n in exclude: 124 | self.debug_print("Node send_to_nodes: Excluding node in sending the message") 125 | else: 126 | self.send_to_node(n, data, compression) 127 | 128 | for n in self.nodes_outbound: 129 | if n in exclude: 130 | self.debug_print("Node send_to_nodes: Excluding node in sending the message") 131 | else: 132 | self.send_to_node(n, data, compression) 133 | 134 | def send_to_node(self, n, data, compression='none'): 135 | """ Send the data to the node n if it exists.""" 136 | self.message_count_send = self.message_count_send + 1 137 | if n in self.nodes_inbound or n in self.nodes_outbound: 138 | n.send(data, compression=compression) 139 | 140 | else: 141 | self.debug_print("Node send_to_node: Could not send the data, node is not found!") 142 | 143 | def connect_with_node(self, host, port, reconnect=False): 144 | """ Make a connection with another node that is running on host with port. When the connection is made, 145 | an event is triggered outbound_node_connected. When the connection is made with the node, it exchanges 146 | the id's of the node. First we send our id and then we receive the id of the node we are connected to. 147 | When the connection is made the method outbound_node_connected is invoked. If reconnect is True, the 148 | node will try to reconnect to the code whenever the node connection was closed. The method returns 149 | True when the node is connected with the specific host.""" 150 | 151 | if host == self.host and port == self.port: 152 | print("connect_with_node: Cannot connect with yourself!!") 153 | return False 154 | 155 | # Check if node is already connected with this node! 156 | for node in self.nodes_outbound: 157 | if node.host == host and node.port == port: 158 | print("connect_with_node: Already connected with this node (" + node.id + ").") 159 | return True 160 | 161 | try: 162 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 163 | self.debug_print("connecting to %s port %s" % (host, port)) 164 | sock.connect((host, port)) 165 | 166 | # Basic information exchange (not secure) of the id's of the nodes! 167 | sock.send((self.id + ":" + str(self.port)).encode('utf-8')) # Send my id and port to the connected node! 168 | connected_node_id = sock.recv(4096).decode('utf-8') # When a node is connected, it sends its id! 169 | 170 | # Cannot connect with yourself 171 | if self.id == connected_node_id: 172 | print("connect_with_node: You cannot connect with yourself?!") 173 | sock.send("CLOSING: Already having a connection together".encode('utf-8')) 174 | sock.close() 175 | return True 176 | 177 | # Fix bug: Cannot connect with nodes that are already connected with us! 178 | # Send message and close the socket. 179 | for node in self.nodes_inbound: 180 | if node.host == host and node.id == connected_node_id: 181 | print("connect_with_node: This node (" + node.id + ") is already connected with us.") 182 | sock.send("CLOSING: Already having a connection together".encode('utf-8')) 183 | sock.close() 184 | return True 185 | 186 | thread_client = self.create_new_connection(sock, connected_node_id, host, port) 187 | thread_client.start() 188 | 189 | self.nodes_outbound.add(thread_client) 190 | self.outbound_node_connected(thread_client) 191 | 192 | # If reconnection to this host is required, it will be added to the list! 193 | if reconnect: 194 | self.debug_print("connect_with_node: Reconnection check is enabled on node " + host + ":" + str(port)) 195 | self.reconnect_to_nodes.append({ 196 | "host": host, "port": port, "tries": 0 197 | }) 198 | 199 | return True 200 | 201 | except Exception as e: 202 | self.debug_print("TcpServer.connect_with_node: Could not connect with node. (" + str(e) + ")") 203 | return False 204 | 205 | def disconnect_with_node(self, node): 206 | """Disconnect the TCP/IP connection with the specified node. It stops the node and joins the thread. 207 | The node will be deleted from the nodes_outbound list. Before closing, the method 208 | node_disconnect_with_outbound_node is invoked.""" 209 | if node in self.nodes_outbound: 210 | self.node_disconnect_with_outbound_node(node) 211 | node.stop() 212 | 213 | else: 214 | self.debug_print("Node disconnect_with_node: cannot disconnect with a node with which we are not connected.") 215 | 216 | def stop(self): 217 | """Stop this node and terminate all the connected nodes.""" 218 | self.node_request_to_stop() 219 | self.terminate_flag.set() 220 | 221 | # This method can be overrided when a different nodeconnection is required! 222 | def create_new_connection(self, connection, id, host, port): 223 | """When a new connection is made, with a node or a node is connecting with us, this method is used 224 | to create the actual new connection. The reason for this method is to be able to override the 225 | connection class if required. In this case a NodeConnection will be instantiated to represent 226 | the node connection.""" 227 | return NodeConnection(self, connection, id, host, port) 228 | 229 | def reconnect_nodes(self): 230 | """This method checks whether nodes that have the reconnection status are still connected. If not 231 | connected these nodes are started again.""" 232 | for node_to_check in self.reconnect_to_nodes: 233 | found_node = False 234 | self.debug_print("reconnect_nodes: Checking node " + node_to_check["host"] + ":" + str(node_to_check["port"])) 235 | 236 | for node in self.nodes_outbound: 237 | if node.host == node_to_check["host"] and node.port == node_to_check["port"]: 238 | found_node = True 239 | node_to_check["trials"] = 0 # Reset the trials 240 | self.debug_print("reconnect_nodes: Node " + node_to_check["host"] + ":" + str(node_to_check["port"]) + " still running!") 241 | 242 | if not found_node: # Reconnect with node 243 | node_to_check["trials"] += 1 244 | if self.node_reconnection_error(node_to_check["host"], node_to_check["port"], node_to_check["trials"]): 245 | self.connect_with_node(node_to_check["host"], node_to_check["port"]) # Perform the actual connection 246 | 247 | else: 248 | self.debug_print("reconnect_nodes: Removing node (" + node_to_check["host"] + ":" + str(node_to_check["port"]) + ") from the reconnection list!") 249 | self.reconnect_to_nodes.remove(node_to_check) 250 | 251 | def run(self): 252 | """The main loop of the thread that deals with connections from other nodes on the network. When a 253 | node is connected it will exchange the node id's. First we receive the id of the connected node 254 | and secondly we will send our node id to the connected node. When connected the method 255 | inbound_node_connected is invoked.""" 256 | while not self.terminate_flag.is_set(): # Check whether the thread needs to be closed 257 | try: 258 | self.debug_print("Node: Wait for incoming connection") 259 | connection, client_address = self.sock.accept() 260 | 261 | self.debug_print("Total inbound connections:" + str(len(self.nodes_inbound))) 262 | # When the maximum connections is reached, it disconnects the connection 263 | if len(self.nodes_inbound) < self.max_connections: 264 | 265 | # Basic information exchange (not secure) of the id's of the nodes! 266 | connected_node_port = client_address[1] # backward compatibilty 267 | connected_node_id = connection.recv(4096).decode('utf-8') 268 | if ":" in connected_node_id: 269 | # When a node is connected, it sends its id! 270 | (connected_node_id, connected_node_port) = connected_node_id.split(':') 271 | connection.send(self.id.encode('utf-8')) # Send my id to the connected node! 272 | 273 | thread_client = self.create_new_connection(connection, connected_node_id, client_address[0], connected_node_port) 274 | thread_client.start() 275 | 276 | self.nodes_inbound.add(thread_client) 277 | self.inbound_node_connected(thread_client) 278 | 279 | else: 280 | self.debug_print("New connection is closed. You have reached the maximum connection limit!") 281 | connection.close() 282 | 283 | except socket.timeout: 284 | self.debug_print('Node: Connection timeout!') 285 | 286 | except Exception as e: 287 | raise e 288 | 289 | self.reconnect_nodes() 290 | 291 | time.sleep(0.01) 292 | 293 | print("Node stopping...") 294 | for t in self.nodes_inbound: 295 | t.stop() 296 | 297 | for t in self.nodes_outbound: 298 | t.stop() 299 | 300 | time.sleep(1) 301 | 302 | for t in self.nodes_inbound: 303 | t.join() 304 | 305 | for t in self.nodes_outbound: 306 | t.join() 307 | 308 | self.sock.settimeout(None) 309 | self.sock.close() 310 | print("Node stopped") 311 | 312 | def outbound_node_connected(self, node): 313 | """This method is invoked when a connection with a outbound node was 314 | successfull. The node `self` made the connection.""" 315 | self.debug_print("outbound_node_connected: " + node.id) 316 | if self.callback is not None: 317 | self.callback("outbound_node_connected", self, node, {}) 318 | 319 | def inbound_node_connected(self, node): 320 | """This method is invoked when a node successfully connected with us.""" 321 | self.debug_print("inbound_node_connected: " + node.id) 322 | if self.callback is not None: 323 | self.callback("inbound_node_connected", self, node, {}) 324 | 325 | def node_disconnected(self, node): 326 | """While the same nodeconnection class is used, the class itself is not able to 327 | determine if it is a inbound or outbound connection. This function is making 328 | sure the correct method is used.""" 329 | self.debug_print("node_disconnected: " + node.id) 330 | 331 | if node in self.nodes_inbound: 332 | self.nodes_inbound.remove(node) 333 | self.inbound_node_disconnected(node) 334 | 335 | if node in self.nodes_outbound: 336 | self.nodes_outbound.remove(node) 337 | self.outbound_node_disconnected(node) 338 | 339 | def inbound_node_disconnected(self, node): 340 | """This method is invoked when a node, that was previously connected with us, is in a disconnected 341 | state.""" 342 | self.debug_print("inbound_node_disconnected: " + node.id) 343 | if self.callback is not None: 344 | self.callback("inbound_node_disconnected", self, node, {}) 345 | 346 | def outbound_node_disconnected(self, node): 347 | """This method is invoked when a node, that we have connected to, is in a disconnected state.""" 348 | self.debug_print("outbound_node_disconnected: " + node.id) 349 | if self.callback is not None: 350 | self.callback("outbound_node_disconnected", self, node, {}) 351 | 352 | def node_message(self, node, data): 353 | """This method is invoked when a node send us a message.""" 354 | self.debug_print("node_message: " + node.id + ": " + str(data)) 355 | if self.callback is not None: 356 | self.callback("node_message", self, node, data) 357 | 358 | def node_disconnect_with_outbound_node(self, node): 359 | """This method is invoked just before the connection is closed with the outbound node. From the node 360 | this request is created.""" 361 | self.debug_print("node wants to disconnect with oher outbound node: " + node.id) 362 | if self.callback is not None: 363 | self.callback("node_disconnect_with_outbound_node", self, node, {}) 364 | 365 | def node_request_to_stop(self): 366 | """This method is invoked just before we will stop. A request has been given to stop the node and close 367 | all the node connections. It could be used to say goodbey to everyone.""" 368 | self.debug_print("node is requested to stop!") 369 | if self.callback is not None: 370 | self.callback("node_request_to_stop", self, {}, {}) 371 | 372 | def node_reconnection_error(self, host, port, trials): 373 | """This method is invoked when a reconnection error occurred. The node connection is disconnected and the 374 | flag for reconnection is set to True for this node. This function can be overidden to implement your 375 | specific logic to take action when a lot of trials have been done. If the method returns True, the 376 | node will try to perform the reconnection. If the method returns False, the node will stop reconnecting 377 | to this node. The node will forever try to perform the reconnection.""" 378 | self.debug_print("node_reconnection_error: Reconnecting to node " + host + ":" + str(port) + " (trials: " + str(trials) + ")") 379 | return True 380 | 381 | def __str__(self): 382 | return 'Node: {}:{}'.format(self.host, self.port) 383 | 384 | def __repr__(self): 385 | return ''.format(self.host, self.port, self.id) 386 | -------------------------------------------------------------------------------- /p2pnetwork/tests/test_node.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import time 3 | 4 | from p2pnetwork.node import Node 5 | 6 | """ 7 | Author: Maurice Snoeren 8 | Version: 0.1 beta (use at your own risk) 9 | 10 | Testing the node on its basic functionality, like connecting to other nodes and 11 | sending data around. Furthermore, the events are tested whether they are handled 12 | correctly in the case of the callback and in the case of extending the class. 13 | TODO: Tests to check the reconnection functionality of the node. 14 | """ 15 | 16 | class TestNode(unittest.TestCase): 17 | """Testing the Node class.""" 18 | 19 | def test_node_connection(self): 20 | """Testing whether two Node instances are able to connect with each other.""" 21 | node1 = Node(host="localhost", port=10001) 22 | node2 = Node(host="localhost", port=10002) 23 | 24 | node1.start() 25 | node2.start() 26 | time.sleep(2) 27 | 28 | step_1_node1_total_inbound_nodes = len(node1.nodes_inbound) 29 | step_1_node1_total_outbound_nodes = len(node1.nodes_outbound) 30 | step_1_node2_total_inbound_nodes = len(node2.nodes_inbound) 31 | step_1_node2_total_outbound_nodes = len(node2.nodes_outbound) 32 | 33 | node1.connect_with_node("localhost", 10001) 34 | time.sleep(1) 35 | 36 | step_2_node1_total_inbound_nodes = len(node1.nodes_inbound) 37 | step_2_node1_total_outbound_nodes = len(node1.nodes_outbound) 38 | 39 | node1.connect_with_node("localhost", 10002) 40 | time.sleep(2) 41 | 42 | step_3_node1_total_inbound_nodes = len(node1.nodes_inbound) 43 | step_3_node1_total_outbound_nodes = len(node1.nodes_outbound) 44 | step_3_node2_total_inbound_nodes = len(node2.nodes_inbound) 45 | step_3_node2_total_outbound_nodes = len(node2.nodes_outbound) 46 | 47 | node1.stop() 48 | node2.stop() 49 | node1.join() 50 | node2.join() 51 | 52 | self.assertEqual(step_1_node1_total_inbound_nodes, 0, "The node 1 should not have any inbound nodes.") 53 | self.assertEqual(step_1_node1_total_outbound_nodes, 0, "The node 1 should not have any outbound nodes.") 54 | self.assertEqual(step_1_node2_total_inbound_nodes, 0, "The node 2 should not have any inbound nodes.") 55 | self.assertEqual(step_1_node2_total_outbound_nodes, 0, "The node 2 should not have any outbound nodes.") 56 | 57 | self.assertEqual(step_2_node1_total_inbound_nodes, 0, "The node 1 should not have any inbound nodes.") 58 | self.assertEqual(step_2_node1_total_outbound_nodes, 0, "The node 1 should not have any outbound nodes.") 59 | 60 | self.assertEqual(step_3_node1_total_inbound_nodes, 0, "The node 1 should not have any inbound node.") 61 | self.assertEqual(step_3_node1_total_outbound_nodes, 1, "The node 1 should have one outbound nodes.") 62 | self.assertEqual(step_3_node2_total_inbound_nodes, 1, "The node 2 should have one inbound node.") 63 | self.assertEqual(step_3_node2_total_outbound_nodes, 0, "The node 2 should not have any outbound nodes.") 64 | 65 | def test_node_communication(self): 66 | """Test whether the connected nodes are able to send messages to each other.""" 67 | global message 68 | message = "unknown" 69 | 70 | # Using the callback we are able to see the events and messages of the Node 71 | def node_callback(event, main_node, connected_node, data): 72 | global message 73 | try: 74 | if event == "node_message": 75 | message = event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data) 76 | 77 | except Exception as e: 78 | message = "exception: " + str(e) 79 | 80 | node1 = Node(host="localhost", port=10001, callback=node_callback) 81 | node2 = Node(host="localhost", port=10002, callback=node_callback) 82 | 83 | node1.start() 84 | node2.start() 85 | time.sleep(2) 86 | 87 | node1.connect_with_node("localhost", 10002) 88 | time.sleep(2) 89 | 90 | node1.send_to_nodes("Hi from node 1!") 91 | time.sleep(1) 92 | node1_message = message 93 | 94 | node2.send_to_nodes("Hi from node 2!") 95 | time.sleep(1) 96 | node2_message = message 97 | 98 | node1.stop() 99 | node2.stop() 100 | node1.join() 101 | node2.join() 102 | 103 | time.sleep(10) 104 | 105 | self.assertEqual("node_message:" + node2.id + ":" + node1.id + ":Hi from node 1!", node1_message, "The message is not correctly received by node 2") 106 | self.assertEqual("node_message:" + node1.id + ":" + node2.id + ":Hi from node 2!", node2_message, "The message is not correctly received by node 1") 107 | 108 | def test_node_complete(self): 109 | """Testing the complete sequence of the Node based on Samuel complete_test.py.""" 110 | 111 | global message 112 | message = [] 113 | 114 | # Using the callback we are able to see the events and messages of the Node 115 | def node_callback(event, main_node, connected_node, data): 116 | global message 117 | try: 118 | if event == "node_message": 119 | message.append(event + ":" + main_node.id + ":" + connected_node.id + ":" + str(data)) 120 | 121 | except Exception as e: 122 | message.append("exception: " + str(e)) 123 | 124 | node_0 = Node(host='127.0.0.1', port=10000, callback=node_callback) 125 | node_1 = Node(host='127.0.0.1', port=10001, callback=node_callback) 126 | node_2 = Node(host='127.0.0.1', port=10002, callback=node_callback) 127 | 128 | node_0.start() 129 | node_1.start() 130 | node_2.start() 131 | time.sleep(1) 132 | 133 | # Test the connections 134 | node_0.connect_with_node('127.0.0.1', 10001) 135 | time.sleep(2) 136 | 137 | node_0_connections = node_0.nodes_outbound 138 | step_1_node_0_total_connections = len(node_0_connections) # should be 1 139 | step_1_node_0_connection_node = "none" 140 | if step_1_node_0_total_connections > 0: 141 | step_1_node_0_connection_node = node_0_connections[0].id + ":" + node_0_connections[0].host + ":" + str(node_0_connections[0].port) # node1.id:127.0.0.1:10001 142 | 143 | node_1_connections = node_1.nodes_inbound 144 | step_1_node_1_total_connections = len(node_1_connections) 145 | step_1_node_1_connection_node = "none" 146 | if step_1_node_1_total_connections > 0: 147 | step_1_node_1_connection_node = node_1_connections[0].id + ":" + node_1_connections[0].host # node0.id:127.0.0.1, inbound port is port of client 148 | 149 | node_2.connect_with_node('127.0.0.1', 10000) 150 | time.sleep(2) 151 | 152 | node_2_connections = node_2.nodes_outbound 153 | step_2_node_2_total_connections = len(node_2_connections) # should be 1 154 | step_2_node_2_connection_node = "none" 155 | if step_2_node_2_total_connections > 0: 156 | step_2_node_2_connection_node = node_2_connections[0].id + ":" + node_2_connections[0].host + ":" + str(node_2_connections[0].port) # node0.id:127.0.0.1:10000 157 | 158 | node_0_connections = node_0.nodes_inbound 159 | step_2_node_0_total_connections = len(node_2_connections) # should be 1 160 | step_2_node_0_connection_node = "none" 161 | if step_2_node_0_total_connections > 0: 162 | step_2_node_0_connection_node = node_0_connections[0].id + ":" + node_0_connections[0].host # node2.id:127.0.0.1 163 | 164 | # Send messages 165 | node_0.send_to_nodes('hello from node 0') 166 | node_1.send_to_nodes('hello from node 1') 167 | node_2.send_to_nodes('hello from node 2') 168 | 169 | node_0.stop() 170 | node_1.stop() 171 | node_2.stop() 172 | node_0.join() 173 | node_1.join() 174 | node_2.join() 175 | 176 | # Perform the asserts! 177 | self.assertEqual(step_1_node_0_total_connections, 1, "Node 0 should have one outbound connection.") 178 | self.assertEqual(step_1_node_0_connection_node, node_1.id + ":127.0.0.1:10001", "Node 0 should be connected (outbound) with node 1.") 179 | self.assertEqual(step_1_node_1_total_connections, 1, "Node 1 should have one inbound connection.") 180 | self.assertEqual(step_1_node_1_connection_node, node_0.id + ":127.0.0.1", "Node 1 should be connected (inbound) with node 0.") 181 | 182 | self.assertEqual(step_2_node_2_total_connections, 1, "Node 2 shoud have one outbound connection.") 183 | self.assertEqual(step_2_node_2_connection_node, node_0.id + ":127.0.0.1:10000", "Node 2 should be connected (outbound) with node 0.") 184 | self.assertEqual(step_2_node_0_total_connections, 1, "Node 0 should have one inbound connection.") 185 | self.assertEqual(step_2_node_0_connection_node, node_2.id + ":127.0.0.1", "Node 0 should be connected (inbound) with node 2.") 186 | 187 | self.assertTrue(len(message) > 0, "There should have been sent some messages around!") 188 | self.assertTrue(len(message) == 4, "There should have been sent 4 message around!") 189 | 190 | def test_node_events(self): 191 | """Testing the events that are triggered by the Node.""" 192 | 193 | global message 194 | message = [] 195 | 196 | # Using the callback we are able to see the events and messages of the Node 197 | def node_callback(event, main_node, connected_node, data): 198 | global message 199 | message.append(event + ":" + main_node.id) 200 | 201 | node_0 = Node(host='127.0.0.1', port=10000, callback=node_callback) 202 | node_1 = Node(host='127.0.0.1', port=10001, callback=node_callback) 203 | node_2 = Node(host='127.0.0.1', port=10002, callback=node_callback) 204 | 205 | node_0.start() 206 | node_1.start() 207 | node_2.start() 208 | time.sleep(1) 209 | 210 | # Test the connections 211 | node_0.connect_with_node('127.0.0.1', 10001) 212 | time.sleep(2) 213 | 214 | node_2.connect_with_node('127.0.0.1', 10000) 215 | time.sleep(2) 216 | 217 | # Send messages 218 | node_0.send_to_nodes('hello from node 0') 219 | time.sleep(2) 220 | 221 | node_1.send_to_nodes('hello from node 1') 222 | time.sleep(2) 223 | 224 | node_2.send_to_nodes('hello from node 2') 225 | time.sleep(2) 226 | 227 | node_0.stop() 228 | node_1.stop() 229 | node_2.stop() 230 | node_0.join() 231 | node_1.join() 232 | node_2.join() 233 | 234 | dt = "\n".join(message) 235 | 236 | # Perform the asserts! 237 | self.assertTrue(len(message) > 0, "There should have been sent some messages around!") 238 | self.assertTrue(len(message) == 15, "There should have been sent 15 message around!"+ str(len(message)) + " messages\n" + dt) 239 | 240 | if "outbound" in message[0]: 241 | self.assertEqual(message[0], "outbound_node_connected:" + node_0.id, "Event should have occurred") 242 | self.assertEqual(message[1], "inbound_node_connected:" + node_1.id, "Event should have occurred") 243 | else: 244 | self.assertEqual(message[1], "outbound_node_connected:" + node_0.id, "Event should have occurred") 245 | self.assertEqual(message[0], "inbound_node_connected:" + node_1.id, "Event should have occurred") 246 | 247 | if "outbound" in message[2]: 248 | self.assertEqual(message[2], "outbound_node_connected:" + node_2.id, "Event should have occurred") 249 | self.assertEqual(message[3], "inbound_node_connected:" + node_0.id, "Event should have occurred") 250 | else: 251 | self.assertEqual(message[3], "outbound_node_connected:" + node_2.id, "Event should have occurred") 252 | self.assertEqual(message[2], "inbound_node_connected:" + node_0.id, "Event should have occurred") 253 | 254 | if node_2.id in message[4]: 255 | self.assertEqual(message[4], "node_message:" + node_2.id, "Event should have occurred") 256 | self.assertEqual(message[5], "node_message:" + node_1.id, "Event should have occurred") 257 | else: 258 | self.assertEqual(message[5], "node_message:" + node_2.id, "Event should have occurred") 259 | self.assertEqual(message[4], "node_message:" + node_1.id, "Event should have occurred") 260 | 261 | self.assertEqual(message[6], "node_message:" + node_0.id, "Event should have occurred") 262 | self.assertEqual(message[7], "node_message:" + node_0.id, "Event should have occurred") 263 | self.assertEqual(message[8], "node_request_to_stop:" + node_0.id, "Event should have occurred") 264 | self.assertEqual(message[9], "node_request_to_stop:" + node_1.id, "Event should have occurred") 265 | self.assertEqual(message[10], "node_request_to_stop:" + node_2.id, "Event should have occurred") 266 | 267 | self.assertIn("disconnected", message[11], "Message should contain a disconnection message") 268 | self.assertIn("disconnected", message[12], "Message should contain a disconnection message") 269 | self.assertIn("disconnected", message[13], "Message should contain a disconnection message") 270 | self.assertIn("disconnected", message[14], "Message should contain a disconnection message") 271 | 272 | def test_extending_class_of_node(self): 273 | """Testing the class implementation of the Node.""" 274 | 275 | global message 276 | message = [] 277 | 278 | class MyTestNode (Node): 279 | def __init__(self, host, port): 280 | super(MyTestNode, self).__init__(host, port, None) 281 | global message 282 | message.append("mytestnode started") 283 | 284 | def outbound_node_connected(self, node): 285 | global message 286 | message.append("outbound_node_connected: " + node.id) 287 | 288 | def inbound_node_connected(self, node): 289 | global message 290 | message.append("inbound_node_connected: " + node.id) 291 | 292 | def inbound_node_disconnected(self, node): 293 | global message 294 | message.append("inbound_node_disconnected: " + node.id) 295 | 296 | def outbound_node_disconnected(self, node): 297 | global message 298 | message.append("outbound_node_disconnected: " + node.id) 299 | 300 | def node_message(self, node, data): 301 | global message 302 | message.append("node_message from " + node.id + ": " + str(data)) 303 | 304 | def node_disconnect_with_outbound_node(self, node): 305 | global message 306 | message.append("node wants to disconnect with oher outbound node: " + node.id) 307 | 308 | def node_request_to_stop(self): 309 | global message 310 | message.append("node is requested to stop!") 311 | 312 | node1 = MyTestNode(host="127.0.0.1", port=10001) 313 | node2 = MyTestNode(host="127.0.0.1", port=10002) 314 | node3 = MyTestNode(host="127.0.0.1", port=10003) 315 | 316 | node1.start() 317 | node2.start() 318 | node3.start() 319 | 320 | node1.connect_with_node('127.0.0.1', 10002) 321 | time.sleep(2) 322 | 323 | node3.connect_with_node('127.0.0.1', 10001) 324 | time.sleep(2) 325 | 326 | # Send messages 327 | node1.send_to_nodes('hello from node 1') 328 | time.sleep(2) 329 | 330 | node2.send_to_nodes('hello from node 2') 331 | time.sleep(2) 332 | 333 | node3.send_to_nodes('hello from node 3') 334 | time.sleep(2) 335 | 336 | node1.stop() 337 | node2.stop() 338 | node3.stop() 339 | node1.join() 340 | node2.join() 341 | node3.join() 342 | 343 | dt = "\n".join(message) 344 | 345 | self.assertTrue(len(message) > 0, "There should have been sent some messages around!") 346 | self.assertTrue(len(message) == 18, "There should have been sent 18 message around! " + str(len(message)) + " messages\n" + dt) 347 | 348 | self.assertEqual(message[0], "mytestnode started", "MyTestNode should have seen this event!") 349 | self.assertEqual(message[1], "mytestnode started", "MyTestNode should have seen this event!") 350 | self.assertEqual(message[2], "mytestnode started", "MyTestNode should have seen this event!") 351 | 352 | if "inbound" in message[3]: 353 | self.assertEqual(message[3], "inbound_node_connected: " + node1.id, "MyTestNode should have seen this event!") 354 | self.assertEqual(message[4], "outbound_node_connected: " + node2.id, "MyTestNode should have seen this event!") 355 | else: 356 | self.assertEqual(message[4], "inbound_node_connected: " + node1.id, "MyTestNode should have seen this event!") 357 | self.assertEqual(message[3], "outbound_node_connected: " + node2.id, "MyTestNode should have seen this event!") 358 | 359 | if "outbound" in message[5]: 360 | self.assertEqual(message[5], "outbound_node_connected: " + node1.id, "MyTestNode should have seen this event!") 361 | self.assertEqual(message[6], "inbound_node_connected: " + node3.id, "MyTestNode should have seen this event!") 362 | else: 363 | self.assertEqual(message[6], "outbound_node_connected: " + node1.id, "MyTestNode should have seen this event!") 364 | self.assertEqual(message[5], "inbound_node_connected: " + node3.id, "MyTestNode should have seen this event!") 365 | 366 | self.assertEqual(message[7], "node_message from " + node1.id + ": hello from node 1", "MyTestNode should have seen this event!") 367 | self.assertEqual(message[8], "node_message from " + node1.id + ": hello from node 1", "MyTestNode should have seen this event!") 368 | self.assertEqual(message[9], "node_message from " + node2.id + ": hello from node 2", "MyTestNode should have seen this event!") 369 | self.assertEqual(message[10], "node_message from " + node3.id + ": hello from node 3", "MyTestNode should have seen this event!") 370 | 371 | self.assertEqual(message[11], "node is requested to stop!", "MyTestNode should have seen this event!") 372 | self.assertEqual(message[12], "node is requested to stop!", "MyTestNode should have seen this event!") 373 | self.assertEqual(message[13], "node is requested to stop!", "MyTestNode should have seen this event!") 374 | 375 | self.assertIn("disconnected", message[14], "Message should contain a disconnection message") 376 | self.assertIn("disconnected", message[15], "Message should contain a disconnection message") 377 | self.assertIn("disconnected", message[16], "Message should contain a disconnection message") 378 | self.assertIn("disconnected", message[17], "Message should contain a disconnection message") 379 | 380 | def test_node_max_connections(self): 381 | """Testing the maximum connections of the node.""" 382 | 383 | global message 384 | message = [] 385 | 386 | # Using the callback we are able to see the events and messages of the Node 387 | def node_callback(event, main_node, connected_node, data): 388 | global message 389 | message.append(event + ":" + main_node.id) 390 | 391 | node_0 = Node(host='127.0.0.1', port=10000, callback=node_callback, max_connections=1) # max connection of 1 392 | node_1 = Node(host='127.0.0.1', port=10001, callback=node_callback, max_connections=2) # max connection of 2 393 | node_2 = Node(host='127.0.0.1', port=10002, callback=node_callback) 394 | 395 | node_0.start() 396 | node_1.start() 397 | node_2.start() 398 | time.sleep(1) 399 | 400 | # Test the connections 401 | node_1.connect_with_node('127.0.0.1', 10000) # This works! 402 | time.sleep(2) 403 | 404 | node_2.connect_with_node('127.0.0.1', 10000) # This should be rejected 405 | time.sleep(2) 406 | 407 | node_0.connect_with_node('127.0.0.1', 10001) # This works! 408 | time.sleep(2) 409 | 410 | node_2.connect_with_node('127.0.0.1', 10001) # This works! 411 | time.sleep(2) 412 | 413 | # Send messages 414 | node_0.send_to_nodes('hello from node 0') 415 | time.sleep(2) 416 | 417 | node_1.send_to_nodes('hello from node 1') 418 | time.sleep(2) 419 | 420 | node_2.send_to_nodes('hello from node 2') 421 | time.sleep(2) 422 | 423 | node_0_inbound = len(node_0.nodes_inbound) 424 | node_1_inbound = len(node_1.nodes_inbound) 425 | node_2_outbound = len(node_2.nodes_outbound) 426 | 427 | node_0.stop() 428 | node_1.stop() 429 | node_2.stop() 430 | node_0.join() 431 | node_1.join() 432 | node_2.join() 433 | 434 | # Perform the asserts! 435 | self.assertEqual(node_0_inbound, 1, "More inbound connections have been accepted bij node_0!") 436 | self.assertEqual(node_1_inbound, 2, "Node 1 should have two connections from node_0 and node_2!") 437 | self.assertEqual(node_2_outbound, 1, "Node 2 should have one outbound connection with node_1!") 438 | 439 | def test_node_id(self): 440 | """Testing the ID settings of the node.""" 441 | 442 | global message 443 | message = [] 444 | 445 | # Using the callback we are able to see the events and messages of the Node 446 | def node_callback(event, main_node, connected_node, data): 447 | global message 448 | message.append(event + ":" + main_node.id) 449 | 450 | node_0 = Node(host='127.0.0.1', port=10000, id="thisisanidtest", callback=node_callback) 451 | node_1 = Node(host='127.0.0.1', port=10001, callback=node_callback) 452 | 453 | node_0.start() 454 | node_1.start() 455 | time.sleep(1) 456 | 457 | node_0.stop() 458 | node_1.stop() 459 | node_0.join() 460 | node_1.join() 461 | 462 | # Perform the asserts! 463 | self.assertEqual(node_0.id, "thisisanidtest", "Node 0 shoud have id \"thisisanidtest\"") 464 | self.assertNotEqual(node_1.id, "thisisanidtest", "Node 1 should have a different id than node 0") 465 | self.assertNotEqual(node_1.id, None, "The ID pf node 1 should not be equal to None") 466 | 467 | if __name__ == '__main__': 468 | unittest.main() 469 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------