From a8ef9bc8b4851deb17d076163e2e231e5b28df56 Mon Sep 17 00:00:00 2001 From: Jonathan Zernik Date: Sun, 18 Oct 2020 01:42:07 -0400 Subject: [PATCH] Check preimage hash (#298) * Check preimage hash after pay offer * Only try to unlock squeak when preimage hash is correct --- squeakserver/node/squeak_node.py | 41 +++++++++++++++++++------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/squeakserver/node/squeak_node.py b/squeakserver/node/squeak_node.py index 7422f3f3..a5236ef9 100644 --- a/squeakserver/node/squeak_node.py +++ b/squeakserver/node/squeak_node.py @@ -1,4 +1,5 @@ import logging +from hashlib import sha256 from squeak.core.encryption import ( CEncryptedDecryptionKey, @@ -273,10 +274,30 @@ class SqueakNode: payment = self.lightning_client.pay_invoice_sync(offer.payment_request) preimage = payment.payment_preimage - # TODO: Check if preimage is valid - is_valid = True + # Check if preimage is valid + preimage_hash = sha256(preimage).hexdigest() + is_valid_preimage = (preimage_hash == offer.payment_hash) - # Unlock the squeak + # Save the preimage of the sent payment + sent_payment = SentPayment( + sent_payment_id=None, + offer_id=offer_id, + peer_id=offer.peer_id, + squeak_hash=offer.squeak_hash, + preimage_hash=offer.payment_hash, + preimage=preimage, + amount=offer.price_msat, + node_pubkey=offer.destination, + preimage_is_valid=is_valid_preimage, + ) + sent_payment_id = self.postgres_db.insert_sent_payment(sent_payment) + + if is_valid_preimage: + self.unlock_squeak(offer, preimage) + + return sent_payment_id + + def unlock_squeak(self, offer, preimage): squeak_entry = self.postgres_db.get_squeak_entry(bytes.fromhex(offer.squeak_hash)) squeak = squeak_entry.squeak @@ -301,20 +322,6 @@ class SqueakNode: serialized_decryption_key, ) - # Save the preimage of the sent payment - sent_payment = SentPayment( - sent_payment_id=None, - offer_id=offer_id, - peer_id=offer.peer_id, - squeak_hash=offer.squeak_hash, - preimage_hash=offer.payment_hash, - preimage=preimage, - amount=offer.price_msat, - node_pubkey=offer.destination, - preimage_is_valid=is_valid, - ) - sent_payment_id = self.postgres_db.insert_sent_payment(sent_payment) - return sent_payment_id def sync_squeaks(self): self.squeak_peer_sync_worker.sync_peers()