Skip to content

Commit 700c0a9

Browse files
committed
fix race condition in expire_envelopes causing over-crediting
1 parent 68a597b commit 700c0a9

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

tipbot.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -558,9 +558,8 @@ def expire_envelopes(self):
558558
if remains <= 0:
559559
continue
560560

561-
store_remains = decimal_to_store(remains)
562-
563561
# Atomically zero out the envelope remains and mark as expired
562+
# Use BEFORE to get the actual remains at update time (avoids race with catch_envelope)
564563
updated = self.col_envelopes.find_one_and_update(
565564
{
566565
"_id": envelope['_id'],
@@ -574,27 +573,33 @@ def expire_envelopes(self):
574573
"expired_at": int(datetime.datetime.now().timestamp())
575574
}
576575
},
577-
return_document=ReturnDocument.AFTER
576+
return_document=ReturnDocument.BEFORE
578577
)
579578
if not updated:
580579
continue
581580

581+
# Use the actual remains from the document at update time
582+
actual_remains = to_decimal(updated['remains'])
583+
if actual_remains <= 0:
584+
continue
585+
store_remains = decimal_to_store(actual_remains)
586+
582587
# Credit the creator
583588
self.col_users.update_one(
584589
{"_id": envelope['creator_id']},
585590
{"$inc": {"Balance": store_remains}}
586591
)
587592

588593
logger.info("Envelope %s expired: refunded %s FIRO to user %s",
589-
envelope['_id'], remains, envelope['creator_id'])
594+
envelope['_id'], actual_remains, envelope['creator_id'])
590595

591596
# Notify the creator
592597
try:
593598
self.bot.send_message(
594599
envelope['creator_id'],
595600
"<b>Your red envelope expired.</b>\n"
596601
"<b>%s FIRO</b> unclaimed funds have been returned to your balance." %
597-
"{0:.8f}".format(remains),
602+
"{0:.8f}".format(actual_remains),
598603
parse_mode='HTML'
599604
)
600605
except Exception as exc:

0 commit comments

Comments
 (0)