diff --git a/frontend/src/components/BuyOfferDetailItem/BuyOfferDetailItem.js b/frontend/src/components/BuyOfferDetailItem/BuyOfferDetailItem.js index 4c4c8d83..05b24a1d 100644 --- a/frontend/src/components/BuyOfferDetailItem/BuyOfferDetailItem.js +++ b/frontend/src/components/BuyOfferDetailItem/BuyOfferDetailItem.js @@ -40,12 +40,12 @@ export default function BuyOfferDetailItem({ const onPeerClick = (event) => { event.preventDefault(); - const peerId = getPeerId(); - if (peerId == null) { + const peerHash = getPeerHash(); + if (peerHash == null) { return; } - console.log("Handling peer click for peerId: " + peerId); - goToPeerPage(history, peerId); + console.log("Handling peer click for peerHash: " + peerHash); + goToPeerPage(history, peerHash); } const onLightningNodeClick = (event) => { @@ -58,12 +58,12 @@ export default function BuyOfferDetailItem({ ) } - const getPeerId = () => { + const getPeerHash = () => { if (!offer.getHasPeer()) { return null; } const peer = offer.getPeer(); - return peer.getPeerId(); + return peer.getPeerHash(); } @@ -96,9 +96,9 @@ export default function BuyOfferDetailItem({ } function HasPeerDisplay(peer) { - const peerId = peer.getPeerId(); + const peerHash = peer.getPeerHash(); const peerName = peer.getPeerName(); - const peerDisplayName = peerName ? peerName : peerId; + const peerDisplayName = peerName ? peerName : peerHash; return ( { createPeerRequest(peerName, host, port, (response) => { - goToPeerPage(history, response.getPeerId()); + goToPeerPage(history, response.getPeerHash()); }); }; diff --git a/frontend/src/components/DeletePeerDialog/DeletePeerDialog.js b/frontend/src/components/DeletePeerDialog/DeletePeerDialog.js index 64b0c629..96f364c0 100644 --- a/frontend/src/components/DeletePeerDialog/DeletePeerDialog.js +++ b/frontend/src/components/DeletePeerDialog/DeletePeerDialog.js @@ -45,8 +45,8 @@ export default function DeletePeerDialog({ var classes = useStyles(); const history = useHistory(); - const deletePeer = (peerId) => { - deletePeerRequest(peerId, (response) => { + const deletePeer = (peerHash) => { + deletePeerRequest(peerHash, (response) => { reloadRoute(history); }); }; @@ -54,9 +54,9 @@ export default function DeletePeerDialog({ function handleSubmit(event) { event.preventDefault(); console.log( 'peer:', peer); - var peerId = peer.getPeerId(); - console.log( 'peerId:', peerId); - deletePeer(peerId); + var peerHash = peer.getPeerHash(); + console.log( 'peerHash:', peerHash); + deletePeer(peerHash); handleClose(); } diff --git a/frontend/src/components/Layout/Layout.js b/frontend/src/components/Layout/Layout.js index 63c43f4d..98019024 100644 --- a/frontend/src/components/Layout/Layout.js +++ b/frontend/src/components/Layout/Layout.js @@ -70,7 +70,7 @@ function Layout(props) { - + { event.preventDefault(); - const peerId = getPeerId(); - if (peerId == null) { + const peerHash = getPeerHash(); + if (peerHash == null) { return; } - console.log("Handling peer click for peerId: " + peerId); - goToPeerPage(history, peerId); + console.log("Handling peer click for peerHash: " + peerHash); + goToPeerPage(history, peerHash); } const onLightningNodeClick = (event) => { @@ -62,12 +62,12 @@ export default function SentPayment({ goToLightningNodePage(history, nodePubkey); } - const getPeerId = () => { + const getPeerHash = () => { if (!sentPayment.getHasPeer()) { return null; } const peer = sentPayment.getPeer(); - return peer.getPeerId(); + return peer.getPeerHash(); } const getPeerDisplay = () => { @@ -76,8 +76,8 @@ export default function SentPayment({ } const peer = sentPayment.getPeer(); const peerName = peer.getPeerName(); - const peerId = peer.getPeerId(); - return peerName ? peerName : peerId; + const peerHash = peer.getPeerHash(); + return peerName ? peerName : peerHash; } function PeerDisplay() { @@ -89,9 +89,9 @@ export default function SentPayment({ } function HasPeerDisplay(peer) { - const peerId = peer.getPeerId(); + const peerHash = peer.getPeerHash(); const peerName = peer.getPeerName(); - const peerDisplayName = peerName ? peerName : peerId; + const peerDisplayName = peerName ? peerName : peerHash; return ( { history.go(0); }; -export const goToPeerPage = (history, peerId) => { - history.push("/app/peer/" + peerId); +export const goToPeerPage = (history, peerHash) => { + history.push("/app/peer/" + peerHash); }; export const goToLightningNodePage = (history, pubkey, host, port) => { diff --git a/frontend/src/pages/peer/Peer.js b/frontend/src/pages/peer/Peer.js index 18c8b070..c25fe3f1 100644 --- a/frontend/src/pages/peer/Peer.js +++ b/frontend/src/pages/peer/Peer.js @@ -29,27 +29,27 @@ import { export default function PeerPage() { var classes = useStyles(); - const { id } = useParams(); + const { hash } = useParams(); const [peer, setPeer] = useState(null); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); - const getSqueakPeer = (id) => { - getPeerRequest(id, setPeer); + const getSqueakPeer = (hash) => { + getPeerRequest(hash, setPeer); }; - const setDownloading = (id, downloading) => { - setPeerDownloadingRequest(id, downloading, () => { - getSqueakPeer(id); + const setDownloading = (hash, downloading) => { + setPeerDownloadingRequest(hash, downloading, () => { + getSqueakPeer(hash); }); }; - const setUploading = (id, uploading) => { - setPeerUploadingRequest(id, uploading, () => { - getSqueakPeer(id); + const setUploading = (hash, uploading) => { + setPeerUploadingRequest(hash, uploading, () => { + getSqueakPeer(hash); }); }; useEffect(()=>{ - getSqueakPeer(id) - },[id]); + getSqueakPeer(hash) + },[hash]); const handleClickOpenDeleteDialog = () => { setDeleteDialogOpen(true); @@ -61,15 +61,15 @@ export default function PeerPage() { }; const handleSettingsDownloadingChange = (event) => { - console.log("Downloading changed for peer id: " + id); + console.log("Downloading changed for peer hash: " + hash); console.log("Downloading changed to: " + event.target.checked); - setDownloading(id, event.target.checked); + setDownloading(hash, event.target.checked); }; const handleSettingsUploadingChange = (event) => { - console.log("Uploading changed for peer id: " + id); + console.log("Uploading changed for peer hash: " + hash); console.log("Uploading changed to: " + event.target.checked); - setUploading(id, event.target.checked); + setUploading(hash, event.target.checked); }; function NoPeerContent() { diff --git a/frontend/src/pages/peers/Peers.js b/frontend/src/pages/peers/Peers.js index 385ca52b..c86f3cf6 100644 --- a/frontend/src/pages/peers/Peers.js +++ b/frontend/src/pages/peers/Peers.js @@ -96,7 +96,7 @@ export default function Peers() { title="Peers" data={peers.map(s => [ - s.getPeerId(), + s.getPeerHash(), s.getPeerName(), s.getHost(), s.getPort(), diff --git a/frontend/src/squeakclient/requests.js b/frontend/src/squeakclient/requests.js index 131ab355..991bf95a 100644 --- a/frontend/src/squeakclient/requests.js +++ b/frontend/src/squeakclient/requests.js @@ -412,9 +412,9 @@ export function getBuyOfferRequest(offerId, handleResponse) { ); } -export function getPeerRequest(id, handleResponse) { +export function getPeerRequest(peerHash, handleResponse) { var request = new GetPeerRequest(); - request.setPeerId(id); + request.setPeerHash(peerHash); makeRequest( 'getpeer', request, @@ -425,9 +425,9 @@ export function getPeerRequest(id, handleResponse) { ); } -export function setPeerDownloadingRequest(id, downloading, handleResponse) { +export function setPeerDownloadingRequest(peerHash, downloading, handleResponse) { var request = new SetPeerDownloadingRequest(); - request.setPeerId(id); + request.setPeerHash(peerHash); request.setDownloading(downloading); makeRequest( 'setpeerdownloading', @@ -437,9 +437,9 @@ export function setPeerDownloadingRequest(id, downloading, handleResponse) { ); } -export function setPeerUploadingRequest(id, uploading, handleResponse) { +export function setPeerUploadingRequest(peerHash, uploading, handleResponse) { var request = new SetPeerUploadingRequest(); - request.setPeerId(id); + request.setPeerHash(peerHash); request.setUploading(uploading); makeRequest( 'setpeeruploading', @@ -590,9 +590,9 @@ export function createPeerRequest(peerName, host, port, handleResponse) { ); } -export function deletePeerRequest(peerId, handleResponse) { +export function deletePeerRequest(peerHash, handleResponse) { var request = new DeletePeerRequest(); - request.setPeerId(peerId); + request.setPeerHash(peerHash); makeRequest( 'deletepeer', request, diff --git a/itests/tests/conftest.py b/itests/tests/conftest.py index 762df8b4..bfc9b8f1 100644 --- a/itests/tests/conftest.py +++ b/itests/tests/conftest.py @@ -130,17 +130,49 @@ def saved_squeak_hash(server_stub, admin_stub, signing_profile_address): @pytest.fixture -def peer_id(server_stub, admin_stub): +def random_peer_host(): + yield "random_host_name_{}".format(uuid.uuid1()) + + +@pytest.fixture +def random_peer_hash(server_stub, admin_stub, random_peer_host): # Create a new peer create_peer_response = admin_stub.CreatePeer( squeak_admin_pb2.CreatePeerRequest( - peer_name="fake_peer_name", - host="fake_host", + peer_name=random_peer_host, + host=random_peer_host, port=1234, ) ) - peer_id = create_peer_response.peer_id - yield peer_id + peer_hash = create_peer_response.peer_hash + yield peer_hash + + +@pytest.fixture +def connected_peer_hash(other_admin_stub, admin_stub): + # Add the main node as a peer + create_peer_response = other_admin_stub.CreatePeer( + squeak_admin_pb2.CreatePeerRequest( + peer_name="test_peer", + host="squeaknode", + port=8774, + ) + ) + peer_hash = create_peer_response.peer_hash + # Set the peer to be downloading + other_admin_stub.SetPeerDownloading( + squeak_admin_pb2.SetPeerDownloadingRequest( + peer_hash=peer_hash, + downloading=True, + ) + ) + yield peer_hash + # Delete the peer + other_admin_stub.DeletePeer( + squeak_admin_pb2.DeletePeerRequest( + peer_hash=peer_hash, + ) + ) @pytest.fixture diff --git a/itests/tests/test_squeak_node.py b/itests/tests/test_squeak_node.py index 667185c9..f77bc79e 100644 --- a/itests/tests/test_squeak_node.py +++ b/itests/tests/test_squeak_node.py @@ -713,12 +713,12 @@ def test_create_peer(server_stub, admin_stub): port=1234, ) ) - peer_id = create_peer_response.peer_id + peer_hash = create_peer_response.peer_hash # Get the new peer get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=peer_hash, ) ) assert get_peer_response.squeak_peer.host == "fake_host" @@ -745,11 +745,11 @@ def test_create_peer_empty_name(server_stub, admin_stub): assert "Peer name cannot be empty." in str(excinfo.value) -def test_set_peer_downloading(server_stub, admin_stub, peer_id): +def test_set_peer_downloading(server_stub, admin_stub, random_peer_hash): # Get the peer get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert not get_peer_response.squeak_peer.downloading @@ -757,7 +757,7 @@ def test_set_peer_downloading(server_stub, admin_stub, peer_id): # Set the peer to be downloading admin_stub.SetPeerDownloading( squeak_admin_pb2.SetPeerDownloadingRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, downloading=True, ) ) @@ -765,17 +765,17 @@ def test_set_peer_downloading(server_stub, admin_stub, peer_id): # Get the peer again get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert get_peer_response.squeak_peer.downloading -def test_set_peer_uploading(server_stub, admin_stub, peer_id): +def test_set_peer_uploading(server_stub, admin_stub, random_peer_hash): # Get the peer get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert not get_peer_response.squeak_peer.uploading @@ -783,7 +783,7 @@ def test_set_peer_uploading(server_stub, admin_stub, peer_id): # Set the peer to be uploading admin_stub.SetPeerUploading( squeak_admin_pb2.SetPeerUploadingRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, uploading=True, ) ) @@ -791,17 +791,17 @@ def test_set_peer_uploading(server_stub, admin_stub, peer_id): # Get the peer again get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert get_peer_response.squeak_peer.uploading -def test_rename_peer(server_stub, admin_stub, peer_id, random_name): +def test_rename_peer(server_stub, admin_stub, random_peer_hash, random_name): # Rename the peer admin_stub.RenamePeer( squeak_admin_pb2.RenamePeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, peer_name=random_name, ) ) @@ -809,17 +809,17 @@ def test_rename_peer(server_stub, admin_stub, peer_id, random_name): # Get the peer again get_peer_response = admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert get_peer_response.squeak_peer.peer_name == random_name -def test_delete_peer(server_stub, admin_stub, peer_id): +def test_delete_peer(server_stub, admin_stub, random_peer_hash): # Delete the peer admin_stub.DeletePeer( squeak_admin_pb2.DeletePeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) @@ -827,7 +827,7 @@ def test_delete_peer(server_stub, admin_stub, peer_id): with pytest.raises(Exception) as excinfo: admin_stub.GetPeer( squeak_admin_pb2.GetPeerRequest( - peer_id=peer_id, + peer_hash=random_peer_hash, ) ) assert "Peer not found." in str(excinfo.value) @@ -1025,6 +1025,7 @@ def test_connect_other_node( admin_stub, other_server_stub, other_admin_stub, + connected_peer_hash, lightning_client, signing_profile_address, saved_squeak_hash, @@ -1035,24 +1036,6 @@ def test_connect_other_node( ) assert len(get_timeline_squeak_display_response.squeak_display_entries) == 0 - # Add the main node as a peer - create_peer_response = other_admin_stub.CreatePeer( - squeak_admin_pb2.CreatePeerRequest( - peer_name="test_peer", - host="squeaknode", - port=8774, - ) - ) - peer_id = create_peer_response.peer_id - - # Set the peer to be downloading - other_admin_stub.SetPeerDownloading( - squeak_admin_pb2.SetPeerDownloadingRequest( - peer_id=peer_id, - downloading=True, - ) - ) - # Get the squeak profile get_squeak_profile_response = admin_stub.GetSqueakProfile( squeak_admin_pb2.GetSqueakProfileRequest( @@ -1096,7 +1079,7 @@ def test_connect_other_node( ) time.sleep(5) # print(sync_squeaks_response) - # assert peer_id in sync_squeaks_response.sync_result.completed_peer_ids + # assert peer_hash in sync_squeaks_response.sync_result.completed_peer_hashs # Get the sent offers from the seller node get_sent_offers_response = admin_stub.GetSentOffers( @@ -1232,29 +1215,12 @@ def test_download_single_squeak( admin_stub, other_server_stub, other_admin_stub, + connected_peer_hash, lightning_client, signing_profile_address, saved_squeak_hash, ): - # Add the main node as a peer - create_peer_response = other_admin_stub.CreatePeer( - squeak_admin_pb2.CreatePeerRequest( - peer_name="test_peer", - host="squeaknode", - port=8774, - ) - ) - peer_id = create_peer_response.peer_id - - # Set the peer to be downloading - other_admin_stub.SetPeerDownloading( - squeak_admin_pb2.SetPeerDownloadingRequest( - peer_id=peer_id, - downloading=True, - ) - ) - # Get the squeak profile get_squeak_profile_response = admin_stub.GetSqueakProfile( squeak_admin_pb2.GetSqueakProfileRequest( @@ -1316,7 +1282,7 @@ def test_download_single_squeak( ) time.sleep(10) print(sync_squeak_response) - # assert peer_id in sync_squeak_response.sync_result.completed_peer_ids + # assert peer_hash in sync_squeak_response.sync_result.completed_peer_hashs # Get the squeak display item get_squeak_display_response = other_admin_stub.GetSqueakDisplay( diff --git a/proto/squeak_admin.proto b/proto/squeak_admin.proto index e23754a2..8de8ae38 100644 --- a/proto/squeak_admin.proto +++ b/proto/squeak_admin.proto @@ -514,13 +514,13 @@ message CreatePeerRequest { } message CreatePeerReply { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; } message GetPeerRequest { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; } message GetPeerReply { @@ -537,8 +537,8 @@ message GetPeersReply { } message SqueakPeer { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; /// The peer name string peer_name = 2; @@ -557,8 +557,8 @@ message SqueakPeer { } message SetPeerDownloadingRequest { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; /// Downloading bool downloading = 2; @@ -568,8 +568,8 @@ message SetPeerDownloadingReply { } message SetPeerUploadingRequest { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; /// Uploading bool uploading = 2; @@ -579,8 +579,8 @@ message SetPeerUploadingReply { } message RenamePeerRequest { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; /// Name of the peer string peer_name = 2; @@ -590,8 +590,8 @@ message RenamePeerReply { } message DeletePeerRequest { - /// The peer id - int32 peer_id = 1; + /// The peer hash + string peer_hash = 1; } message DeletePeerReply { @@ -700,7 +700,7 @@ message SentPayment { /// Has peer bool has_peer = 2; - /// The peer id + /// The peer hash SqueakPeer peer = 3; /// The squeak hash diff --git a/squeaknode/admin/messages.py b/squeaknode/admin/messages.py index a543c6fc..466486c4 100644 --- a/squeaknode/admin/messages.py +++ b/squeaknode/admin/messages.py @@ -68,10 +68,8 @@ def squeak_profile_to_message(squeak_profile: SqueakProfile) -> squeak_admin_pb2 def squeak_peer_to_message(squeak_peer: SqueakPeer) -> squeak_admin_pb2.SqueakPeer: - if squeak_peer.peer_id is None: - raise Exception("Peer id cannot be None.") return squeak_admin_pb2.SqueakPeer( - peer_id=squeak_peer.peer_id, + peer_hash=squeak_peer.peer_hash.hex(), peer_name=squeak_peer.peer_name, host=squeak_peer.host, port=squeak_peer.port, diff --git a/squeaknode/admin/squeak_admin_server_handler.py b/squeaknode/admin/squeak_admin_server_handler.py index 2cf73be3..c01ea614 100644 --- a/squeaknode/admin/squeak_admin_server_handler.py +++ b/squeaknode/admin/squeak_admin_server_handler.py @@ -387,19 +387,21 @@ class SqueakAdminServerHandler(object): port, ) ) - peer_id = self.squeak_controller.create_peer( + peer_hash = self.squeak_controller.create_peer( peer_name, host, port, ) return squeak_admin_pb2.CreatePeerReply( - peer_id=peer_id, + peer_hash=peer_hash.hex(), ) def handle_get_squeak_peer(self, request): - peer_id = request.peer_id - logger.info("Handle get squeak peer with id: {}".format(peer_id)) - squeak_peer = self.squeak_controller.get_peer(peer_id) + peer_hash_str = request.peer_hash + peer_hash = bytes.fromhex(peer_hash_str) + logger.info( + "Handle get squeak peer with hash: {}".format(peer_hash_str)) + squeak_peer = self.squeak_controller.get_peer(peer_hash) if squeak_peer is None: raise Exception("Peer not found.") squeak_peer_msg = squeak_peer_to_message(squeak_peer) @@ -418,45 +420,50 @@ class SqueakAdminServerHandler(object): ) def handle_set_squeak_peer_downloading(self, request): - peer_id = request.peer_id + peer_hash_str = request.peer_hash + peer_hash = bytes.fromhex(peer_hash_str) downloading = request.downloading logger.info( "Handle set peer downloading with peer id: {}, downloading: {}".format( - peer_id, + peer_hash, downloading, ) ) - self.squeak_controller.set_peer_downloading(peer_id, downloading) + self.squeak_controller.set_peer_downloading(peer_hash, downloading) return squeak_admin_pb2.SetPeerDownloadingReply() def handle_rename_squeak_peer(self, request): - peer_id = request.peer_id + peer_hash_str = request.peer_hash + peer_hash = bytes.fromhex(peer_hash_str) peer_name = request.peer_name logger.info( "Handle rename peer with peer id: {}, new name: {}".format( - peer_id, + peer_hash_str, peer_name, ) ) - self.squeak_controller.rename_peer(peer_id, peer_name) + self.squeak_controller.rename_peer(peer_hash, peer_name) return squeak_admin_pb2.RenamePeerReply() def handle_set_squeak_peer_uploading(self, request): - peer_id = request.peer_id + peer_hash_str = request.peer_hash + peer_hash = bytes.fromhex(peer_hash_str) uploading = request.uploading logger.info( "Handle set peer uploading with peer id: {}, uploading: {}".format( - peer_id, + peer_hash, uploading, ) ) - self.squeak_controller.set_peer_uploading(peer_id, uploading) + self.squeak_controller.set_peer_uploading(peer_hash, uploading) return squeak_admin_pb2.SetPeerUploadingReply() def handle_delete_squeak_peer(self, request): - peer_id = request.peer_id - logger.info("Handle delete squeak peer with id: {}".format(peer_id)) - self.squeak_controller.delete_peer(peer_id) + peer_hash_str = request.peer_hash + peer_hash = bytes.fromhex(peer_hash_str) + logger.info( + "Handle delete squeak peer with hash: {}".format(peer_hash_str)) + self.squeak_controller.delete_peer(peer_hash) return squeak_admin_pb2.DeletePeerReply() def handle_get_buy_offers(self, request): diff --git a/squeaknode/core/received_offer.py b/squeaknode/core/received_offer.py index 88bcb848..162886fc 100644 --- a/squeaknode/core/received_offer.py +++ b/squeaknode/core/received_offer.py @@ -16,4 +16,4 @@ class ReceivedOffer(NamedTuple): destination: str node_host: str node_port: int - peer_id: int + peer_hash: bytes diff --git a/squeaknode/core/sent_payment.py b/squeaknode/core/sent_payment.py index f16d659d..4b990ed6 100644 --- a/squeaknode/core/sent_payment.py +++ b/squeaknode/core/sent_payment.py @@ -7,7 +7,7 @@ class SentPayment(NamedTuple): """Represents a payment made by a buyer.""" sent_payment_id: Optional[int] created: Optional[datetime] - peer_id: int + peer_hash: bytes squeak_hash: bytes payment_hash: bytes secret_key: bytes diff --git a/squeaknode/core/squeak_controller.py b/squeaknode/core/squeak_controller.py index 071b648e..6122225f 100644 --- a/squeaknode/core/squeak_controller.py +++ b/squeaknode/core/squeak_controller.py @@ -13,6 +13,7 @@ from squeaknode.core.received_offer import ReceivedOffer from squeaknode.core.received_payment_summary import ReceivedPaymentSummary from squeaknode.core.sent_offer import SentOffer from squeaknode.core.sent_payment_summary import SentPaymentSummary +from squeaknode.core.squeak_peer import make_squeak_peer from squeaknode.core.squeak_peer import SqueakPeer from squeaknode.core.squeak_profile import SqueakProfile from squeaknode.core.util import get_hash @@ -236,8 +237,7 @@ class SqueakController: "Peer name cannot be empty.", ) port = port or self.config.core.default_peer_rpc_port - squeak_peer = SqueakPeer( - peer_id=None, + squeak_peer = make_squeak_peer( peer_name=peer_name, host=host, port=port, @@ -246,8 +246,8 @@ class SqueakController: ) return self.squeak_db.insert_peer(squeak_peer) - def get_peer(self, peer_id: int): - return self.squeak_db.get_peer(peer_id) + def get_peer(self, peer_hash: bytes): + return self.squeak_db.get_peer(peer_hash) def get_peers(self): return self.squeak_db.get_peers() @@ -258,17 +258,17 @@ class SqueakController: def get_uploading_peers(self): return self.squeak_db.get_uploading_peers() - def set_peer_downloading(self, peer_id: int, downloading: bool): - self.squeak_db.set_peer_downloading(peer_id, downloading) + def set_peer_downloading(self, peer_hash: bytes, downloading: bool): + self.squeak_db.set_peer_downloading(peer_hash, downloading) - def set_peer_uploading(self, peer_id: int, uploading: bool): - self.squeak_db.set_peer_uploading(peer_id, uploading) + def set_peer_uploading(self, peer_hash: bytes, uploading: bool): + self.squeak_db.set_peer_uploading(peer_hash, uploading) - def rename_peer(self, peer_id: int, peer_name: str): - self.squeak_db.set_peer_name(peer_id, peer_name) + def rename_peer(self, peer_hash: bytes, peer_name: str): + self.squeak_db.set_peer_name(peer_hash, peer_name) - def delete_peer(self, peer_id: int): - self.squeak_db.delete_peer(peer_id) + def delete_peer(self, peer_hash: bytes): + self.squeak_db.delete_peer(peer_hash) def get_buy_offers_with_peer(self, squeak_hash: bytes): return self.squeak_db.get_offers_with_peer(squeak_hash) @@ -422,12 +422,12 @@ class SqueakController: include_locked=True, ) - def lookup_squeaks_needing_offer(self, addresses: List[str], min_block, max_block, peer_id): + def lookup_squeaks_needing_offer(self, addresses: List[str], min_block, max_block, peer_hash: bytes): return self.squeak_db.lookup_squeaks_needing_offer( addresses, min_block, max_block, - peer_id, + peer_hash, ) def save_offer(self, received_offer: ReceivedOffer): diff --git a/squeaknode/core/squeak_core.py b/squeaknode/core/squeak_core.py index f23a14d5..87dc9fc3 100644 --- a/squeaknode/core/squeak_core.py +++ b/squeaknode/core/squeak_core.py @@ -186,8 +186,6 @@ class SqueakCore: Returns: ReceivedOffer: A record of the details of the offer for the buyer. """ - if peer.peer_id is None: - raise Exception("Peer must have a non-null peer_id.") # Get the squeak hash squeak_hash = get_hash(squeak) # TODO: check if squeak hash matches squeak_hash in buy_offer. @@ -224,7 +222,7 @@ class SqueakCore: destination=destination, node_host=node_host, node_port=node_port, - peer_id=peer.peer_id, + peer_hash=peer.peer_hash, ) def pay_offer(self, received_offer: ReceivedOffer) -> SentPayment: @@ -255,7 +253,7 @@ class SqueakCore: return SentPayment( sent_payment_id=None, created=None, - peer_id=received_offer.peer_id, + peer_hash=received_offer.peer_hash, squeak_hash=received_offer.squeak_hash, payment_hash=received_offer.payment_hash, secret_key=secret_key, diff --git a/squeaknode/core/squeak_peer.py b/squeaknode/core/squeak_peer.py index 96d8530b..33af5f81 100644 --- a/squeaknode/core/squeak_peer.py +++ b/squeaknode/core/squeak_peer.py @@ -1,12 +1,30 @@ from typing import NamedTuple -from typing import Optional + +from squeaknode.core.util import get_peer_hash class SqueakPeer(NamedTuple): """Represents another node in the network.""" - peer_id: Optional[int] + peer_hash: bytes peer_name: str host: str port: int uploading: bool downloading: bool + + +def make_squeak_peer( + peer_name: str, + host: str, + port: int, + uploading: bool, + downloading: bool, +): + return SqueakPeer( + get_peer_hash(host, port), + peer_name, + host, + port, + uploading, + downloading, + ) diff --git a/squeaknode/core/util.py b/squeaknode/core/util.py index 2e201fb8..5ef2506c 100644 --- a/squeaknode/core/util.py +++ b/squeaknode/core/util.py @@ -1,4 +1,5 @@ import os +from hashlib import sha256 from bitcoin.base58 import Base58ChecksumError from bitcoin.wallet import CBitcoinAddressError @@ -58,3 +59,8 @@ def is_address_valid(address: str) -> bool: except (Base58ChecksumError, CBitcoinAddressError): return False return True + + +def get_peer_hash(host: str, port: int) -> bytes: + host_port_str = "{}:{}".format(host, port) + return sha256(host_port_str.encode()).digest() diff --git a/squeaknode/db/alembic/versions/9eb4ba6da999_use_peer_hash_for_peer_primary_key.py b/squeaknode/db/alembic/versions/9eb4ba6da999_use_peer_hash_for_peer_primary_key.py new file mode 100644 index 00000000..4bc40894 --- /dev/null +++ b/squeaknode/db/alembic/versions/9eb4ba6da999_use_peer_hash_for_peer_primary_key.py @@ -0,0 +1,87 @@ +"""Use peer hash for peer primary key + +Revision ID: 9eb4ba6da999 +Revises: d1cf733279c4 +Create Date: 2021-02-02 22:14:57.682676 + +""" +import sqlalchemy as sa +from alembic import op +from sqlalchemy import Integer +from sqlalchemy import String +from sqlalchemy.sql import column +from sqlalchemy.sql import table + +from squeaknode.core.util import get_peer_hash + + +# revision identifiers, used by Alembic. +revision = '9eb4ba6da999' +down_revision = 'd1cf733279c4' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + + # Create the peer_hash column + with op.batch_alter_table('peer', schema=None) as batch_op: + batch_op.add_column( + sa.Column('peer_hash', sa.String(length=64), nullable=False, server_default='')) + with op.batch_alter_table('received_offer', schema=None) as batch_op: + batch_op.add_column( + sa.Column('peer_hash', sa.String(length=64), nullable=False, server_default='')) + with op.batch_alter_table('sent_payment', schema=None) as batch_op: + batch_op.add_column( + sa.Column('peer_hash', sa.String(length=64), nullable=False, server_default='')) + + peers = table( + "peer", + column("peer_hash", String(64)), + column("server_host", String), + column("server_port", Integer), + ) + + # Set the peer_hash column in the peers table. + op.execute( + peers.update(). + values( + peer_hash=get_peer_hash( + peers.c.server_host, + peers.c.server_port, + ).hex(), + ) + ) + + # Delete peer_id and create the primary key on peer_hash + with op.batch_alter_table('peer', schema=None) as batch_op: + batch_op.drop_column('peer_id') + batch_op.create_primary_key( + "pk_peer", ["peer_hash"] + ) + with op.batch_alter_table('received_offer', schema=None) as batch_op: + batch_op.drop_column('peer_id') + with op.batch_alter_table('sent_payment', schema=None) as batch_op: + batch_op.drop_column('peer_id') + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('peer', schema=None) as batch_op: + batch_op.drop_constraint("pk_peer") + batch_op.add_column(sa.Column('peer_id', sa.INTEGER(), + nullable=False, server_default='0')) + batch_op.drop_column('peer_hash') + with op.batch_alter_table('received_offer', schema=None) as batch_op: + batch_op.add_column(sa.Column('peer_id', sa.INTEGER(), + nullable=False, server_default='0')) + batch_op.drop_column('peer_hash') + with op.batch_alter_table('sent_payment', schema=None) as batch_op: + batch_op.add_column(sa.Column('peer_id', sa.INTEGER(), + nullable=False, server_default='0')) + batch_op.drop_column('peer_hash') + + # ### end Alembic commands ### diff --git a/squeaknode/db/models.py b/squeaknode/db/models.py index e658b985..c1f8a9bb 100644 --- a/squeaknode/db/models.py +++ b/squeaknode/db/models.py @@ -71,7 +71,7 @@ class Models: self.peers = Table( "peer", self.metadata, - Column("peer_id", Integer, primary_key=True), + Column("peer_hash", String(64), primary_key=True), Column("created", TZDateTime, server_default=func.now(), nullable=False), Column("peer_name", String), @@ -98,7 +98,7 @@ class Models: Column("destination", String(66), nullable=False), Column("node_host", String, nullable=False), Column("node_port", Integer, nullable=False), - Column("peer_id", Integer, nullable=False), + Column("peer_hash", String(64), nullable=False), ) self.sent_payments = Table( @@ -107,7 +107,7 @@ class Models: Column("sent_payment_id", Integer, primary_key=True), Column("created", TZDateTime, server_default=func.now(), nullable=False), - Column("peer_id", Integer, nullable=False), + Column("peer_hash", String(64), nullable=False), Column("squeak_hash", String(64), nullable=False), Column("payment_hash", String(64), nullable=False), Column("secret_key", String(64), nullable=False), diff --git a/squeaknode/db/squeak_db.py b/squeaknode/db/squeak_db.py index cbeda013..603b5d28 100644 --- a/squeaknode/db/squeak_db.py +++ b/squeaknode/db/squeak_db.py @@ -395,7 +395,7 @@ class SqueakDb: addresses: List[str], min_block: int, max_block: int, - peer_id: int, + peer_hash: bytes, include_unverified: bool = False ) -> List[bytes]: """ Lookup squeaks that are locked and don't have an offer. """ @@ -409,7 +409,7 @@ class SqueakDb: self.received_offers, and_( self.received_offers.c.squeak_hash == self.squeaks.c.hash, - self.received_offers.c.peer_id == peer_id, + self.received_offers.c.peer_hash == peer_hash.hex(), ), ) ) @@ -435,7 +435,7 @@ class SqueakDb: # SELECT hash FROM squeak # LEFT JOIN offer # ON squeak.hash=offer.squeak_hash - # AND offer.peer_id=%s + # AND offer.peer_hash=%s # WHERE author_address IN %s # AND n_block_height >= %s # AND n_block_height <= %s @@ -452,7 +452,7 @@ class SqueakDb: # # mogrify to debug. # # logger.info(curs.mogrify(sql, (addresses_tuple, min_block, max_block))) # curs.execute( - # sql, (peer_id, addresses_tuple, min_block, max_block, include_unverified) + # sql, (peer_hash, addresses_tuple, min_block, max_block, include_unverified) # ) # rows = curs.fetchall() # hashes = [bytes.fromhex(row["hash"]) for row in rows] @@ -683,9 +683,10 @@ class SqueakDb: # with self.get_cursor() as curs: # curs.execute(sql, (squeak_hash_str,)) - def insert_peer(self, squeak_peer: SqueakPeer) -> int: + def insert_peer(self, squeak_peer: SqueakPeer) -> bytes: """ Insert a new squeak peer. """ ins = self.peers.insert().values( + peer_hash=squeak_peer.peer_hash.hex(), peer_name=squeak_peer.peer_name, server_host=squeak_peer.host, server_port=squeak_peer.port, @@ -694,12 +695,14 @@ class SqueakDb: ) with self.get_connection() as connection: res = connection.execute(ins) - id = res.inserted_primary_key[0] - return id + peer_hash_str = res.inserted_primary_key[0] + return bytes.fromhex(peer_hash_str) - def get_peer(self, peer_id: int) -> Optional[SqueakPeer]: + def get_peer(self, peer_hash: bytes) -> Optional[SqueakPeer]: """ Get a peer. """ - s = select([self.peers]).where(self.peers.c.peer_id == peer_id) + s = select([self.peers]).where( + self.peers.c.peer_hash == peer_hash.hex() + ) with self.get_connection() as connection: result = connection.execute(s) row = result.fetchone() @@ -734,39 +737,40 @@ class SqueakDb: peers = [self._parse_squeak_peer(row) for row in rows] return peers - def set_peer_downloading(self, peer_id: int, downloading: bool): + def set_peer_downloading(self, peer_hash: bytes, downloading: bool): """ Set a peer is downloading. """ stmt = ( self.peers.update() - .where(self.peers.c.peer_id == peer_id) + .where(self.peers.c.peer_hash == peer_hash.hex()) .values(downloading=downloading) ) with self.get_connection() as connection: connection.execute(stmt) - def set_peer_uploading(self, peer_id: int, uploading: bool): + def set_peer_uploading(self, peer_hash: bytes, uploading: bool): """ Set a peer is uploading. """ stmt = ( self.peers.update() - .where(self.peers.c.peer_id == peer_id) + .where(self.peers.c.peer_hash == peer_hash.hex()) .values(uploading=uploading) ) with self.get_connection() as connection: connection.execute(stmt) - def set_peer_name(self, peer_id: int, peer_name: str): + def set_peer_name(self, peer_hash: bytes, peer_name: str): """ Set a peer name. """ stmt = ( self.peers.update() - .where(self.peers.c.peer_id == peer_id) + .where(self.peers.c.peer_hash == peer_hash.hex()) .values(peer_name=peer_name) ) with self.get_connection() as connection: connection.execute(stmt) - def delete_peer(self, peer_id: int): + def delete_peer(self, peer_hash: bytes): """ Delete a peer. """ - delete_peer_stmt = self.peers.delete().where(self.peers.c.peer_id == peer_id) + delete_peer_stmt = self.peers.delete().where( + self.peers.c.peer_hash == peer_hash.hex()) with self.get_connection() as connection: connection.execute(delete_peer_stmt) @@ -784,7 +788,7 @@ class SqueakDb: destination=received_offer.destination, node_host=received_offer.node_host, node_port=received_offer.node_port, - peer_id=received_offer.peer_id, + peer_hash=received_offer.peer_hash.hex(), ) with self.get_connection() as connection: res = connection.execute(ins) @@ -808,7 +812,7 @@ class SqueakDb: .select_from( self.received_offers.outerjoin( self.peers, - self.peers.c.peer_id == self.received_offers.c.peer_id, + self.peers.c.peer_hash == self.received_offers.c.peer_hash, ) ) .where(self.received_offers.c.squeak_hash == squeak_hash.hex()) @@ -827,7 +831,7 @@ class SqueakDb: .select_from( self.received_offers.outerjoin( self.peers, - self.peers.c.peer_id == self.received_offers.c.peer_id, + self.peers.c.peer_hash == self.received_offers.c.peer_hash, ) ) .where(self.received_offers.c.received_offer_id == received_offer_id) @@ -881,7 +885,7 @@ class SqueakDb: def insert_sent_payment(self, sent_payment: SentPayment): """ Insert a new sent payment. """ ins = self.sent_payments.insert().values( - peer_id=sent_payment.peer_id, + peer_hash=sent_payment.peer_hash.hex(), squeak_hash=sent_payment.squeak_hash.hex(), payment_hash=sent_payment.payment_hash.hex(), secret_key=sent_payment.secret_key.hex(), @@ -901,7 +905,7 @@ class SqueakDb: .select_from( self.sent_payments.outerjoin( self.peers, - self.peers.c.peer_id == self.sent_payments.c.peer_id, + self.peers.c.peer_hash == self.sent_payments.c.peer_hash, ) ) .order_by( @@ -922,7 +926,7 @@ class SqueakDb: .select_from( self.sent_payments.outerjoin( self.peers, - self.peers.c.peer_id == self.sent_payments.c.peer_id, + self.peers.c.peer_hash == self.sent_payments.c.peer_hash, ) ) .where(self.sent_payments.c.sent_payment_id == sent_payment_id) @@ -1128,7 +1132,7 @@ class SqueakDb: def _parse_squeak_peer(self, row) -> SqueakPeer: return SqueakPeer( - peer_id=row[self.peers.c.peer_id], + peer_hash=bytes.fromhex(row[self.peers.c.peer_hash]), peer_name=row["peer_name"], host=row["server_host"], port=row["server_port"], @@ -1150,12 +1154,12 @@ class SqueakDb: destination=row["destination"], node_host=row["node_host"], node_port=row["node_port"], - peer_id=row[self.peers.c.peer_id], + peer_hash=bytes.fromhex(row[self.received_offers.c.peer_hash]), ) def _parse_received_offer_with_peer(self, row) -> ReceivedOfferWithPeer: offer = self._parse_received_offer(row) - if row[self.peers.c.peer_id] is None: + if row[self.peers.c.peer_hash] is None: peer = None else: peer = self._parse_squeak_peer(row) @@ -1168,7 +1172,7 @@ class SqueakDb: return SentPayment( sent_payment_id=row["sent_payment_id"], created=row[self.sent_payments.c.created], - peer_id=row[self.sent_payments.c.peer_id], + peer_hash=bytes.fromhex(row[self.sent_payments.c.peer_hash]), squeak_hash=bytes.fromhex(row["squeak_hash"]), payment_hash=bytes.fromhex(row["payment_hash"]), secret_key=bytes.fromhex(row["secret_key"]), @@ -1179,7 +1183,7 @@ class SqueakDb: def _parse_sent_payment_with_peer(self, row) -> SentPaymentWithPeer: sent_payment = self._parse_sent_payment(row) - if row[self.peers.c.peer_id] is None: + if row[self.peers.c.peer_hash] is None: peer = None else: peer = self._parse_squeak_peer(row) diff --git a/squeaknode/sync/peer_connection.py b/squeaknode/sync/peer_connection.py index 5f8e5792..ca73bdf0 100644 --- a/squeaknode/sync/peer_connection.py +++ b/squeaknode/sync/peer_connection.py @@ -66,7 +66,7 @@ class PeerConnection: followed_addresses, min_block, max_block, - self.peer.peer_id, + self.peer.peer_hash, ) # Get hashes to get offer hashes_to_get_offer = set(remote_hashes) & set(locked_hashes) @@ -124,7 +124,7 @@ class PeerConnection: def _get_saved_offer(self, squeak_hash: bytes) -> Optional[ReceivedOfferWithPeer]: offers = self.squeak_controller.get_buy_offers_with_peer(squeak_hash) for offer_with_peer in offers: - if offer_with_peer.received_offer.peer_id == self.peer.peer_id: + if offer_with_peer.received_offer.peer_hash == self.peer.peer_hash: return offer_with_peer return None diff --git a/tests/core/test_squeak_controller.py b/tests/core/test_squeak_controller.py index 519c9782..54cc5b7d 100644 --- a/tests/core/test_squeak_controller.py +++ b/tests/core/test_squeak_controller.py @@ -6,6 +6,7 @@ from squeaknode.core.lightning_address import LightningAddressHostPort from squeaknode.core.squeak_controller import SqueakController from squeaknode.core.squeak_core import SqueakCore from squeaknode.core.squeak_peer import SqueakPeer +from squeaknode.core.util import get_peer_hash from squeaknode.db.squeak_db import SqueakDb from squeaknode.node.squeak_rate_limiter import SqueakRateLimiter from squeaknode.node.squeak_whitelist import SqueakWhitelist @@ -131,7 +132,7 @@ def test_create_peer(squeak_db, squeak_controller): squeak_db.insert_peer.assert_called_with( SqueakPeer( - peer_id=None, + peer_hash=get_peer_hash("fake_host", 5678), peer_name="fake_peer_name", host="fake_host", port=5678, @@ -150,7 +151,10 @@ def test_create_peer_default_port(config, squeak_db, squeak_controller): squeak_db.insert_peer.assert_called_with( SqueakPeer( - peer_id=None, + peer_hash=get_peer_hash( + "fake_host", + config.core.default_peer_rpc_port, + ), peer_name="fake_peer_name", host="fake_host", port=config.core.default_peer_rpc_port,