Skip to content

Commit

Permalink
Add preliminary key functionality to Peer and Artwork classes (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
thompalex authored Jan 25, 2024
1 parent d662260 commit 6db97ad
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 20 deletions.
9 changes: 8 additions & 1 deletion src/main/py/commission/artwork.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ class Artwork:
Class to manage artwork commissions
"""

def __init__(self, width: float, height: float, wait_time: timedelta):
def __init__(
self,
width: float,
height: float,
wait_time: timedelta,
originator_public_key: str = "",
):
"""
Initializes an instance of the Artwork class.
- width (float): The width of the artwork in pixels.
Expand All @@ -30,6 +36,7 @@ def __init__(self, width: float, height: float, wait_time: timedelta):
self.key = self.generate_key()
start_time = datetime.now()
self.end_time = start_time + self.wait_time
self.originator_public_key = originator_public_key

def generate_key(self):
"""
Expand Down
48 changes: 35 additions & 13 deletions src/main/py/peer/peer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""
import asyncio
from datetime import timedelta
import hashlib
import ipaddress
import pickle
import logging
Expand All @@ -19,14 +20,22 @@ class Peer:

logger = logging.getLogger("Peer")

def __init__(self, port: int, peer_network_address: str, kdm) -> None:
def __init__(
self,
port: int,
key_filename: str,
peer_network_address: str,
kdm,
) -> None:
"""
Initialize the Peer class by joining the kademlia network.
Params:
- port (int): The port number for the peer to listen on.
- public_key_filename (str): The filename of the public key.
- private_key_filename (str): The filename of the private key.
- peer_network_address (str): String containing the IP address and port number of a peer
on the network separated by a colon.
- port (int): The port number for the peer to listen on.
"""
if peer_network_address is not None:
try:
Expand All @@ -38,9 +47,11 @@ def __init__(self, port: int, peer_network_address: str, kdm) -> None:
"Invalid network address. Please provide a valid network address."
) from exc
self.port = port
with open(f"{key_filename}.pub", "r", encoding="utf-8") as public_key_file:
self.public_key = public_key_file.read()
with open(key_filename, "r", encoding="utf-8") as private_key_file:
self.private_key = private_key_file.read()
self.kdm = kdm
self.commissions = []
self.deadline_timers = {}
self.node = None

async def send_deadline_reached(self, commission: Artwork) -> None:
Expand All @@ -66,12 +77,11 @@ async def setup_deadline_timer(self, commission: Artwork) -> None:
"""

deadline_seconds = commission.get_remaining_time()
deadline_timer = asyncio.get_event_loop().call_later(
asyncio.get_event_loop().call_later(
deadline_seconds,
asyncio.create_task,
self.send_deadline_reached(commission),
)
self.deadline_timers[commission.get_key()] = deadline_timer

async def send_commission_request(self, commission: Artwork) -> None:
"""
Expand All @@ -84,7 +94,6 @@ async def send_commission_request(self, commission: Artwork) -> None:
)
if set_success:
self.logger.info("Commission sent")
self.commissions.append(commission)
else:
self.logger.error("Commission failed to send")
await self.setup_deadline_timer(commission)
Expand All @@ -101,9 +110,14 @@ async def commission_art_piece(self) -> None:
width = float(input("Enter commission width: "))
height = float(input("Enter commission height: "))
wait_time = float(input("Enter wait time in seconds: "))
commission = Artwork(width, height, timedelta(seconds=wait_time))
commission = Artwork(
width,
height,
timedelta(seconds=wait_time),
originator_public_key=self.public_key,
)
await self.send_commission_request(commission)
break
return commission
except ValueError:
self.logger.error("Invalid input. Please enter a valid float.")

Expand Down Expand Up @@ -149,7 +163,10 @@ async def connect_to_network(self):
Connect to the kademlia network.
"""

self.node = self.kdm.network.NotifyingServer(self.data_stored_callback)
self.node = self.kdm.network.NotifyingServer(
self.data_stored_callback,
node_id=hashlib.sha1(self.public_key.encode()).digest(),
)
await self.node.listen(self.port)
if self.network_ip_address is not None:
await self.node.bootstrap(
Expand All @@ -159,17 +176,22 @@ async def connect_to_network(self):


async def main():
"""Main function"""
"""Main function
Run the file with the following:
python3 peer.py <port_num> <key_filename> <address>
"""

logging.basicConfig(
format="%(asctime)s %(name)s %(levelname)s | %(message)s", level=logging.INFO
)
port_num = sys.argv[1]
if len(sys.argv) == 2:
key_filename = sys.argv[2]
if len(sys.argv) == 3:
address = None
else:
address = sys.argv[2]
peer = Peer(port_num, address, kademlia)
peer = Peer(port_num, key_filename, address, kademlia)
await peer.connect_to_network()
await peer.commission_art_piece()

Expand Down
4 changes: 2 additions & 2 deletions src/main/py/server/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class NotifyingServer(Server):
"""

def __init__(self, data_stored_callback, ksize=20, alpha=3):
def __init__(self, data_stored_callback, ksize=20, alpha=3, node_id=None):
"""
Initializes a new instance of the NewServer class.
Expand All @@ -33,7 +33,7 @@ def __init__(self, data_stored_callback, ksize=20, alpha=3):
"""
self.data_stored_callback = data_stored_callback
# Call the parent class's __init__ with the new protocol
super().__init__(ksize, alpha)
super().__init__(ksize, alpha, node_id=node_id)

def _create_protocol(self):
"""
Expand Down
11 changes: 7 additions & 4 deletions src/test/py/peer/peer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,12 @@ def setUp(self):
self.mock_kdm = MagicMock()
self.mock_node = AsyncMock(spec=MockNode)
self.mock_kdm.network.NotifyingServer.return_value = self.mock_node
self.peer = Peer(5001, "127.0.0.1:5000", self.mock_kdm)
self.peer = Peer(
5001,
"src/test/py/resources/peer_test",
"127.0.0.1:5000",
self.mock_kdm,
)
self.deadline_task = None

def test_initialization(self):
Expand Down Expand Up @@ -97,9 +102,7 @@ async def test_commission_art_piece(self, mock_input):
):
self.test_logger.debug(mock_input)
self.peer.node = self.mock_node
await self.peer.commission_art_piece()
self.assertEqual(len(self.peer.commissions), 1)
commission = self.peer.commissions[0]
commission = await self.peer.commission_art_piece()
self.mock_node.set.assert_called_with(
commission.get_key(), pickle.dumps(commission)
)
Expand Down
7 changes: 7 additions & 0 deletions src/test/py/resources/peer_test
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACAHL+2x3zpXlrZaiqQs8Nl4kkYAyHCpEYGICruenpVpawAAAJj0nFRW9JxU
VgAAAAtzc2gtZWQyNTUxOQAAACAHL+2x3zpXlrZaiqQs8Nl4kkYAyHCpEYGICruenpVpaw
AAAEBCytIyK/oHfMcRk4F+6vy3UiR1JFZJreWXjPL+To6r/gcv7bHfOleWtlqKpCzw2XiS
RgDIcKkRgYgKu56elWlrAAAAEGFsZXhfQGFsZXgtcmF6ZXIBAgMEBQ==
-----END OPENSSH PRIVATE KEY-----
1 change: 1 addition & 0 deletions src/test/py/resources/peer_test.pub
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAcv7bHfOleWtlqKpCzw2XiSRgDIcKkRgYgKu56elWlr alex_@alex-razer

0 comments on commit 6db97ad

Please sign in to comment.