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()