Skip to content

solana: token pool rate limiter - prevent overflow #855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,9 @@ impl RateLimitTokenBucket {
// Consume is not guaranteed to succeed after wait time passes if there is competing traffic.
// This acts as a lower bound of wait time.
let min_wait_sec = (request_tokens
.checked_sub(self.tokens)
.unwrap()
.checked_add(rate.checked_sub(1).unwrap()))
.unwrap()
.checked_div(rate)
.unwrap();
.saturating_sub(self.tokens)
.saturating_add(rate.saturating_sub(1)))
.saturating_div(rate);

// print human readable message before reverting with total wait time
let msg = "min wait (s): ".to_owned() + &min_wait_sec.to_string();
Expand All @@ -72,7 +69,7 @@ impl RateLimitTokenBucket {
return Err(CcipTokenPoolError::RLRateLimitReached.into());
}

self.tokens = self.tokens.checked_sub(request_tokens).unwrap();
self.tokens = self.tokens.saturating_sub(request_tokens);
emit!(TokensConsumed {
tokens: request_tokens
});
Expand All @@ -82,9 +79,10 @@ impl RateLimitTokenBucket {

fn refill<C: Timestamper>(&mut self) -> Result<()> {
let current_timestamp = C::instance()?.unix_timestamp();
let time_diff = current_timestamp.checked_sub(self.last_updated).unwrap();
let increase = time_diff.checked_mul(self.cfg.rate).unwrap();
let refill = self.tokens.checked_add(increase).unwrap();
// use of saturating - prevent overflow
let time_diff = current_timestamp.saturating_sub(self.last_updated);
let increase = time_diff.saturating_mul(self.cfg.rate);
let refill = self.tokens.saturating_add(increase);

self.tokens = min(self.cfg.capacity, refill);
self.last_updated = current_timestamp;
Expand Down
Loading