Skip to main content

thru_base/
ratelimit.rs

1//! Client helpers for the rate limiter program (`tn_ratelimit_program`).
2//!
3//! Mirrors `programs/c/examples/tn_ratelimit_program.h`: account seeds,
4//! the packed policy/bucket layouts and the CALL instruction encoding.
5
6use anyhow::{bail, Result};
7use sha2::{Digest, Sha256};
8
9use crate::tn_public_address::create_program_defined_account_address;
10
11pub const INSTRUCTION_CREATE_POLICY: u32 = 0;
12pub const INSTRUCTION_UPDATE_POLICY: u32 = 1;
13pub const INSTRUCTION_SET_ADMIN: u32 = 2;
14pub const INSTRUCTION_CREATE_AUTHORITY: u32 = 3;
15pub const INSTRUCTION_CALL: u32 = 4;
16
17/// Sentinel account index meaning "no account" (e.g. no authority PDA).
18pub const NO_ACCOUNT: u16 = 0xFFFF;
19
20pub const RULE_MAX: usize = 4;
21pub const CONSTRAINT_MAX: usize = 4;
22
23pub const POLICY_MAGIC: u64 = 0x7261746C706F6C31;
24pub const BUCKET_MAGIC: u64 = 0x7261746C62636B31;
25
26pub const POLICY_FLAG_PAUSED: u8 = 0x01;
27pub const POLICY_FLAG_VERIFIED: u8 = 0x80;
28
29const POLICY_SEED_TAG: &[u8] = b"tn_ratelimit_policy_v1";
30const VERIFIED_POLICY_SEED_TAG: &[u8] = b"tn_ratelimit_verified_policy_v1";
31const BUCKET_SEED_TAG: &[u8] = b"tn_ratelimit_bucket_v1";
32const AUTHORITY_SEED_TAG: &[u8] = b"tn_ratelimit_authority_v1";
33
34/// Packed sizes, checked against the C structs in the runtime test.
35pub const RULE_SIZE: usize = 28;
36pub const CONSTRAINT_SIZE: usize = 34;
37pub const CONFIG_SIZE: usize = 309;
38pub const POLICY_SIZE: usize = 390;
39pub const BUCKET_SIZE: usize = 113;
40pub const CALL_ARGS_SIZE: usize = 8;
41pub const CALL_BUCKET_SIZE: usize = 36;
42
43const POLICY_CONFIG_OFFSET: usize = 81;
44const CONFIG_ATTESTER_OFFSET: usize = 29;
45const CONFIG_RULES_OFFSET: usize = 197;
46
47/// Rate limiter error codes (`TN_RATELIMIT_ERR_*`).
48pub const ERR_INVALID_INSTRUCTION: u64 = 0x5201;
49pub const ERR_INVALID_ACCOUNT: u64 = 0x5202;
50pub const ERR_INVALID_CONFIG: u64 = 0x5203;
51pub const ERR_UNAUTHORIZED: u64 = 0x5204;
52pub const ERR_CREATE_FAILED: u64 = 0x5205;
53pub const ERR_WRITE_FAILED: u64 = 0x5206;
54pub const ERR_PAUSED: u64 = 0x5207;
55pub const ERR_TARGET_MISMATCH: u64 = 0x5208;
56pub const ERR_INSTRUCTION_REJECTED: u64 = 0x5209;
57pub const ERR_AMOUNT_PER_CALL_EXCEEDED: u64 = 0x520A;
58pub const ERR_BUCKET_MISMATCH: u64 = 0x520B;
59pub const ERR_ATTESTER_REQUIRED: u64 = 0x520C;
60pub const ERR_CALL_LIMIT_EXCEEDED: u64 = 0x520D;
61pub const ERR_AMOUNT_LIMIT_EXCEEDED: u64 = 0x520E;
62pub const ERR_TARGET_FAILED: u64 = 0x520F;
63/// Gate error a rate limited target returns when not invoked through the
64/// rate limiter (`TN_RATELIMIT_GATE_ERR_NOT_RATE_LIMITED`).
65pub const GATE_ERR_NOT_RATE_LIMITED: u64 = 0x52A1;
66
67/// How a rule derives its bucket key.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum KeyKind {
70    /// One bucket shared by every caller.
71    Global,
72    /// The transaction fee payer.
73    FeePayer,
74    /// The account named by the u16 account index at `key_offset` in the
75    /// forwarded instruction.
76    InstrAccount,
77    /// A 32-byte key supplied by the caller; requires the policy attester.
78    Attested,
79}
80
81impl KeyKind {
82    fn from_u8(v: u8) -> Result<Self> {
83        Ok(match v {
84            0 => KeyKind::Global,
85            1 => KeyKind::FeePayer,
86            2 => KeyKind::InstrAccount,
87            3 => KeyKind::Attested,
88            _ => bail!("unknown rate limit key kind {}", v),
89        })
90    }
91}
92
93/// Window clock of a rule.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum Clock {
96    Slot,
97    UnixSeconds,
98}
99
100impl Clock {
101    fn from_u8(v: u8) -> Result<Self> {
102        Ok(match v {
103            0 => Clock::Slot,
104            1 => Clock::UnixSeconds,
105            _ => bail!("unknown rate limit clock {}", v),
106        })
107    }
108}
109
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct Rule {
112    pub key_kind: KeyKind,
113    pub clock: Clock,
114    pub key_offset: u16,
115    pub window: u64,
116    pub max_calls: u64,
117    pub max_amount: u64,
118}
119
120/// The parts of a policy account a client needs to build a CALL.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct Policy {
123    pub admin: [u8; 32],
124    pub target: [u8; 32],
125    pub policy_id: u64,
126    pub state_flags: u8,
127    pub config_flags: u8,
128    pub attester: [u8; 32],
129    pub rules: Vec<Rule>,
130}
131
132impl Policy {
133    pub fn is_verified(&self) -> bool {
134        self.state_flags & POLICY_FLAG_VERIFIED != 0
135    }
136
137    pub fn is_paused(&self) -> bool {
138        self.config_flags & POLICY_FLAG_PAUSED != 0
139    }
140
141    /// Parses policy account data.
142    pub fn parse(data: &[u8]) -> Result<Self> {
143        if data.len() != POLICY_SIZE {
144            bail!("rate limit policy has {} bytes, expected {}", data.len(), POLICY_SIZE);
145        }
146        if u64_at(data, 0) != POLICY_MAGIC {
147            bail!("account is not a rate limit policy");
148        }
149        let cfg = &data[POLICY_CONFIG_OFFSET..];
150        let rule_cnt = cfg[1] as usize;
151        if rule_cnt == 0 || rule_cnt > RULE_MAX {
152            bail!("rate limit policy has invalid rule count {}", rule_cnt);
153        }
154        let mut rules = Vec::with_capacity(rule_cnt);
155        for i in 0..rule_cnt {
156            let r = &cfg[CONFIG_RULES_OFFSET + i * RULE_SIZE..];
157            rules.push(Rule {
158                key_kind: KeyKind::from_u8(r[0])?,
159                clock: Clock::from_u8(r[1])?,
160                key_offset: u16::from_le_bytes([r[2], r[3]]),
161                window: u64_at(r, 4),
162                max_calls: u64_at(r, 12),
163                max_amount: u64_at(r, 20),
164            });
165        }
166        Ok(Policy {
167            admin: data[8..40].try_into().unwrap(),
168            target: data[40..72].try_into().unwrap(),
169            policy_id: u64_at(data, 72),
170            state_flags: data[80],
171            config_flags: cfg[0],
172            attester: cfg[CONFIG_ATTESTER_OFFSET..CONFIG_ATTESTER_OFFSET + 32].try_into().unwrap(),
173            rules,
174        })
175    }
176}
177
178/// Counters of one bucket account.
179#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct Bucket {
181    pub policy: [u8; 32],
182    pub key: [u8; 32],
183    pub rule_idx: u8,
184    /// Start of the counted window, in the rule's clock.
185    pub window_start: u64,
186    pub calls: u64,
187    pub amount: u64,
188}
189
190impl Bucket {
191    pub fn parse(data: &[u8]) -> Result<Self> {
192        if data.len() != BUCKET_SIZE || u64_at(data, 0) != BUCKET_MAGIC {
193            bail!("account is not a rate limit bucket");
194        }
195        Ok(Bucket {
196            policy: data[8..40].try_into().unwrap(),
197            key: data[40..72].try_into().unwrap(),
198            rule_idx: data[72],
199            window_start: u64_at(data, 73),
200            calls: u64_at(data, 81),
201            amount: u64_at(data, 89),
202        })
203    }
204
205    /// Calls and amount the program would count against `rule` at `now`
206    /// (in the rule's clock): zero once the window has rolled forward, the
207    /// stored counters otherwise. Mirrors `charge_bucket`.
208    pub fn usage_at(&self, rule: &Rule, now: u64) -> (u64, u64) {
209        if window_start(now, rule.window) > self.window_start || other_clock(rule, now, self.window_start) {
210            (0, 0)
211        } else {
212            (self.calls, self.amount)
213        }
214    }
215}
216
217/// When (in `rule`'s clock) counters seen at `now` reset: the first window
218/// boundary after both `now` and the bucket's stored window start (0 for a
219/// bucket that doesn't exist yet).
220pub fn resets_at(rule: &Rule, now: u64, stored_start: u64) -> u64 {
221    let start = if other_clock(rule, now, stored_start) { now } else { now.max(stored_start) };
222    window_start(start, rule.window).saturating_add(rule.window)
223}
224
225/// Whether a stored window start more than one window ahead of `now` was
226/// written under the rule's other clock; `charge_bucket` restarts such a
227/// bucket.
228fn other_clock(rule: &Rule, now: u64, stored_start: u64) -> bool {
229    stored_start > now && stored_start - now > rule.window
230}
231
232/// Start of the window of length `window` holding `now`.
233pub fn window_start(now: u64, window: u64) -> u64 {
234    now - now % window
235}
236
237fn u64_at(data: &[u8], off: usize) -> u64 {
238    u64::from_le_bytes(data[off..off + 8].try_into().unwrap())
239}
240
241/// PDA of the rate limiter whose seed is sha256 over `parts`.
242fn pda(ratelimit_program: &[u8; 32], parts: &[&[u8]]) -> [u8; 32] {
243    let mut h = Sha256::new();
244    for part in parts {
245        h.update(part);
246    }
247    let seed: [u8; 32] = h.finalize().into();
248    create_program_defined_account_address(ratelimit_program, false, &seed)
249}
250
251/// Address of the VERIFIED policy `policy_id` of `target`.
252pub fn verified_policy_address(ratelimit_program: &[u8; 32], target: &[u8; 32], policy_id: u64) -> [u8; 32] {
253    pda(ratelimit_program, &[VERIFIED_POLICY_SEED_TAG, target, &policy_id.to_le_bytes()])
254}
255
256/// Address of the unverified policy `policy_id` of `target` created by `admin`.
257pub fn policy_address(ratelimit_program: &[u8; 32], admin: &[u8; 32], target: &[u8; 32], policy_id: u64) -> [u8; 32] {
258    pda(ratelimit_program, &[POLICY_SEED_TAG, admin, target, &policy_id.to_le_bytes()])
259}
260
261/// Address of rule `rule_idx`'s bucket for `key` under `policy`.
262pub fn bucket_address(ratelimit_program: &[u8; 32], policy: &[u8; 32], rule_idx: u8, key: &[u8; 32]) -> [u8; 32] {
263    pda(ratelimit_program, &[BUCKET_SEED_TAG, policy, &[rule_idx], key])
264}
265
266/// Address of the authority PDA the rate limiter signs for under `policy`.
267pub fn authority_address(ratelimit_program: &[u8; 32], policy: &[u8; 32]) -> [u8; 32] {
268    pda(ratelimit_program, &[AUTHORITY_SEED_TAG, policy])
269}
270
271/// One rule's bucket in a CALL. `proof` is a creation state proof when the
272/// bucket doesn't exist yet, empty otherwise. `key` is only non-zero for
273/// ATTESTED rules.
274#[derive(Clone, Debug)]
275pub struct CallBucket {
276    pub account_idx: u16,
277    pub proof: Vec<u8>,
278    pub key: [u8; 32],
279}
280
281/// Encodes a CALL instruction forwarding `inner` to the target.
282pub fn build_call_instruction(
283    policy_idx: u16,
284    target_idx: u16,
285    authority_idx: u16,
286    buckets: &[CallBucket],
287    inner: &[u8],
288) -> Result<Vec<u8>> {
289    if buckets.is_empty() || buckets.len() > RULE_MAX {
290        bail!("rate limit CALL needs 1..={} buckets, got {}", RULE_MAX, buckets.len());
291    }
292    let inner_sz = u16::try_from(inner.len())?;
293    let proofs_sz: usize = buckets.iter().map(|b| b.proof.len()).sum();
294    let mut data =
295        Vec::with_capacity(4 + CALL_ARGS_SIZE + buckets.len() * CALL_BUCKET_SIZE + proofs_sz + inner.len());
296    data.extend_from_slice(&INSTRUCTION_CALL.to_le_bytes());
297    data.extend_from_slice(&policy_idx.to_le_bytes());
298    data.extend_from_slice(&target_idx.to_le_bytes());
299    data.extend_from_slice(&authority_idx.to_le_bytes());
300    data.extend_from_slice(&inner_sz.to_le_bytes());
301    for b in buckets {
302        data.extend_from_slice(&b.account_idx.to_le_bytes());
303        data.extend_from_slice(&u16::try_from(b.proof.len())?.to_le_bytes());
304        data.extend_from_slice(&b.key);
305    }
306    for b in buckets {
307        data.extend_from_slice(&b.proof);
308    }
309    data.extend_from_slice(inner);
310    Ok(data)
311}
312
313/// Human readable name of a rate limiter (or gate) error code.
314pub fn error_name(code: u64) -> Option<&'static str> {
315    Some(match code {
316        ERR_INVALID_INSTRUCTION => "invalid instruction",
317        ERR_INVALID_ACCOUNT => "invalid account",
318        ERR_INVALID_CONFIG => "invalid policy config",
319        ERR_UNAUTHORIZED => "unauthorized",
320        ERR_CREATE_FAILED => "account creation failed",
321        ERR_WRITE_FAILED => "account write failed",
322        ERR_PAUSED => "policy paused",
323        ERR_TARGET_MISMATCH => "target mismatch",
324        ERR_INSTRUCTION_REJECTED => "instruction rejected by policy",
325        ERR_AMOUNT_PER_CALL_EXCEEDED => "amount per call exceeded",
326        ERR_BUCKET_MISMATCH => "bucket mismatch",
327        ERR_ATTESTER_REQUIRED => "attester required",
328        ERR_CALL_LIMIT_EXCEEDED => "call limit reached for this window",
329        ERR_AMOUNT_LIMIT_EXCEEDED => "amount limit reached for this window",
330        ERR_TARGET_FAILED => "target failed",
331        GATE_ERR_NOT_RATE_LIMITED => "target requires the rate limiter",
332        _ => return None,
333    })
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    fn sample_policy() -> Vec<u8> {
341        let mut d = vec![0u8; POLICY_SIZE];
342        d[0..8].copy_from_slice(&POLICY_MAGIC.to_le_bytes());
343        d[8..40].copy_from_slice(&[1u8; 32]);
344        d[40..72].copy_from_slice(&[2u8; 32]);
345        d[72..80].copy_from_slice(&7u64.to_le_bytes());
346        d[80] = POLICY_FLAG_VERIFIED;
347        let cfg = POLICY_CONFIG_OFFSET;
348        d[cfg + 1] = 2;
349        d[cfg + CONFIG_ATTESTER_OFFSET..cfg + CONFIG_ATTESTER_OFFSET + 32].copy_from_slice(&[3u8; 32]);
350        let r1 = cfg + CONFIG_RULES_OFFSET + RULE_SIZE;
351        d[r1] = 2;
352        d[r1 + 1] = 1;
353        d[r1 + 2..r1 + 4].copy_from_slice(&6u16.to_le_bytes());
354        d[r1 + 4..r1 + 12].copy_from_slice(&86400u64.to_le_bytes());
355        d[r1 + 12..r1 + 20].copy_from_slice(&5u64.to_le_bytes());
356        d[r1 + 20..r1 + 28].copy_from_slice(&50000u64.to_le_bytes());
357        d
358    }
359
360    #[test]
361    fn layout_sizes_add_up() {
362        assert_eq!(CONFIG_SIZE, 1 + 1 + 1 + 1 + 2 + 8 + 2 + 2 + 1 + 2 + 8 + 32 + CONSTRAINT_MAX * CONSTRAINT_SIZE + RULE_MAX * RULE_SIZE);
363        assert_eq!(POLICY_SIZE, 8 + 32 + 32 + 8 + 1 + CONFIG_SIZE);
364        assert_eq!(CONFIG_RULES_OFFSET, CONFIG_ATTESTER_OFFSET + 32 + CONSTRAINT_MAX * CONSTRAINT_SIZE);
365        assert_eq!(BUCKET_SIZE, 8 + 32 + 32 + 1 + 8 * 5);
366    }
367
368    #[test]
369    fn parses_policy() {
370        let p = Policy::parse(&sample_policy()).unwrap();
371        assert!(p.is_verified());
372        assert!(!p.is_paused());
373        assert_eq!(p.policy_id, 7);
374        assert_eq!(p.attester, [3u8; 32]);
375        assert_eq!(p.rules.len(), 2);
376        assert_eq!(p.rules[0].key_kind, KeyKind::Global);
377        assert_eq!(
378            p.rules[1],
379            Rule { key_kind: KeyKind::InstrAccount, clock: Clock::UnixSeconds, key_offset: 6, window: 86400, max_calls: 5, max_amount: 50000 }
380        );
381        assert!(Policy::parse(&sample_policy()[1..]).is_err());
382    }
383
384    #[test]
385    fn encodes_call() {
386        let buckets = [
387            CallBucket { account_idx: 4, proof: vec![9, 9, 9], key: [0u8; 32] },
388            CallBucket { account_idx: 5, proof: vec![], key: [8u8; 32] },
389        ];
390        let data = build_call_instruction(3, 6, NO_ACCOUNT, &buckets, &[1, 2]).unwrap();
391        assert_eq!(data.len(), 4 + CALL_ARGS_SIZE + 2 * CALL_BUCKET_SIZE + 3 + 2);
392        assert_eq!(&data[0..4], &INSTRUCTION_CALL.to_le_bytes());
393        assert_eq!(&data[4..12], &[3, 0, 6, 0, 0xFF, 0xFF, 2, 0]);
394        assert_eq!(&data[12..16], &[4, 0, 3, 0]);
395        assert_eq!(&data[48 + 4..48 + 36], &[8u8; 32]);
396        assert_eq!(&data[84..87], &[9, 9, 9]);
397        assert_eq!(&data[87..], &[1, 2]);
398    }
399
400    /// Known answer shared with the C runtime test: the faucet's VERIFIED
401    /// policy 0 and its global bucket under the bootstrap addresses.
402    #[test]
403    fn faucet_policy_known_answer() {
404        use crate::bootstrap_addresses::{FAUCET_PROGRAM_BYTES, RATELIMIT_PROGRAM_BYTES};
405        let policy = verified_policy_address(&RATELIMIT_PROGRAM_BYTES, &FAUCET_PROGRAM_BYTES, 0);
406        assert_eq!(hex::encode(policy), "0ebbd33cb84c5ae46c0b20009f2366e69924ae599e82c1ebc18b094351a806f7");
407        assert_eq!(policy, crate::bootstrap_addresses::FAUCET_RATE_LIMIT_POLICY_BYTES);
408        let bucket = bucket_address(&RATELIMIT_PROGRAM_BYTES, &policy, 0, &[0u8; 32]);
409        assert_eq!(hex::encode(bucket), "a9dc2788f1685f9f4f1b8b243b5cc1744c36971698280ea851628163055a69de");
410    }
411
412    fn bucket(window_start: u64) -> Bucket {
413        Bucket { policy: [0u8; 32], key: [0u8; 32], rule_idx: 0, window_start, calls: 3, amount: 300 }
414    }
415
416    fn rule(clock: Clock, window: u64) -> Rule {
417        Rule { key_kind: KeyKind::Global, clock, key_offset: 0, window, max_calls: 3, max_amount: 0 }
418    }
419
420    #[test]
421    fn bucket_usage_follows_window_start() {
422        let hourly = rule(Clock::UnixSeconds, 3_600);
423        let now = 1_700_000_000;
424        let hour = window_start(now, 3_600);
425        assert_eq!(bucket(hour).usage_at(&hourly, now), (3, 300));
426        assert_eq!(bucket(hour - 3_600).usage_at(&hourly, now), (0, 0));
427        assert_eq!(resets_at(&hourly, now, hour), hour + 3_600);
428        /* A clock slightly behind keeps the newest window. */
429        assert_eq!(bucket(hour + 3_600).usage_at(&hourly, now), (3, 300));
430        assert_eq!(resets_at(&hourly, now, hour + 3_600), hour + 7_200);
431    }
432
433    /// UPDATE_POLICY grew the window from an hour to a day: the counters
434    /// last until the next day boundary rather than for 24x as many hours.
435    #[test]
436    fn bucket_usage_after_window_grows() {
437        let daily = rule(Clock::UnixSeconds, 86_400);
438        let now = 1_700_000_000;
439        let stored = bucket(window_start(now, 3_600));
440        let day_end = window_start(now, 86_400) + 86_400;
441        assert_eq!(stored.usage_at(&daily, now), (3, 300));
442        assert_eq!(resets_at(&daily, now, stored.window_start), day_end);
443        assert_eq!(stored.usage_at(&daily, day_end), (0, 0));
444    }
445
446    /// UPDATE_POLICY switched the rule from seconds to slots: the stored
447    /// block time start is far ahead of any slot, so the bucket restarts.
448    #[test]
449    fn bucket_usage_after_clock_switch() {
450        let slots = rule(Clock::Slot, 1_000);
451        let stored = bucket(window_start(1_700_000_000, 3_600));
452        assert_eq!(stored.usage_at(&slots, 5_000), (0, 0));
453        /* Retry estimates count from the slot window, not the old block time. */
454        assert_eq!(resets_at(&slots, 5_000, stored.window_start), 6_000);
455    }
456
457    #[test]
458    fn verified_and_admin_policies_differ() {
459        let rl = [0x44u8; 32];
460        let target = [0x14u8; 32];
461        assert_ne!(verified_policy_address(&rl, &target, 0), policy_address(&rl, &[0u8; 32], &target, 0));
462        assert_ne!(verified_policy_address(&rl, &target, 0), verified_policy_address(&rl, &target, 1));
463    }
464}