Skip to main content

stellar_vrf_sdk/
lib.rs

1//! stellar-vrf-sdk — Rust SDK for the Stellar VRF Oracle
2//!
3//! Provides a high-level async client for interacting with the Stellar VRF
4//! Oracle contract via the Soroban JSON-RPC API.
5//!
6//! # Example
7//! ```rust,no_run
8//! use stellar_vrf_sdk::{VrfClient, VrfClientConfig, Network};
9//!
10//! #[tokio::main]
11//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
12//!     let client = VrfClient::new(VrfClientConfig {
13//!         contract_id: "CD5K4NNYNG3ZFCET24F3SL6MSYYRD5I2BSWW5K3LFQVIKYHRY2ICVIVX".into(),
14//!         network: Network::Testnet,
15//!         secret_key: String::new(), // unused: read-only client
16//!     });
17//!
18//!     // Check if request #1 is fulfilled
19//!     let fulfilled = client.is_fulfilled(1).await?;
20//!     println!("Fulfilled: {}", fulfilled);
21//!
22//!     // Derive a uniform roll in [1, 100] (exact, no modulo bias)
23//!     let roll = client.derive_random_in_range(1, 1, 100).await?;
24//!     println!("Roll: {}", roll);
25//!
26//!     // Or reproduce it offline from the verified beta:
27//!     let beta = client.get_beta(1).await?;
28//!     let span = 100;
29//!     assert_eq!(roll, 1 + stellar_vrf_sdk::derive_range_from_beta(&beta, 1, span)?);
30//!
31//!     Ok(())
32//! }
33//! ```
34
35use serde::{Deserialize, Serialize};
36use thiserror::Error;
37
38// ── Network ──────────────────────────────────────────────────────────────────
39
40/// Network selection for the VRF client.
41#[derive(Debug, Clone)]
42pub enum Network {
43    Testnet,
44    Mainnet,
45    Custom { rpc_url: String, passphrase: String },
46}
47
48impl Network {
49    pub fn rpc_url(&self) -> &str {
50        match self {
51            Network::Testnet => "https://soroban-testnet.stellar.org",
52            Network::Mainnet => "https://soroban.stellar.org",
53            Network::Custom { rpc_url, .. } => rpc_url,
54        }
55    }
56
57    pub fn passphrase(&self) -> &str {
58        match self {
59            Network::Testnet => "Test SDF Network ; September 2015",
60            Network::Mainnet => "Public Global Stellar Network ; September 2015",
61            Network::Custom { passphrase, .. } => passphrase,
62        }
63    }
64}
65
66// ── Config ───────────────────────────────────────────────────────────────────
67
68/// Configuration for the VRF client.
69#[derive(Debug, Clone)]
70pub struct VrfClientConfig {
71    /// The Soroban contract ID (C...)
72    pub contract_id: String,
73    /// Network to connect to
74    pub network: Network,
75    /// Stellar secret key (S...).
76    ///
77    /// **Currently unused.** This SDK is read-only: every call is an unsigned
78    /// `simulateTransaction`, and nothing is signed or submitted. The field is
79    /// kept for 2.x API compatibility. An empty string is fine, and you don't
80    /// need to give this client a real key.
81    pub secret_key: String,
82}
83
84// ── VRF Proof ────────────────────────────────────────────────────────────────
85
86/// A fulfilled VRF proof retrieved from the contract.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct VrfProof {
89    pub request_id: u64,
90    pub alpha_seed: Vec<u8>,
91    pub gamma_point: Vec<u8>,
92    pub beta_output: Vec<u8>,
93    pub public_key: Vec<u8>,
94    pub drand_round: u64,
95    pub drand_signature: Vec<u8>,
96}
97
98/// A VRF request event from the contract.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct VrfRequestEvent {
101    pub request_id: u64,
102    pub requester: String,
103    pub required_round: u64,
104    pub ledger: u64,
105}
106
107// ── Errors ───────────────────────────────────────────────────────────────────
108
109#[derive(Debug, Error)]
110pub enum VrfError {
111    #[error("HTTP error: {0}")]
112    Http(#[from] reqwest::Error),
113    #[error("JSON error: {0}")]
114    Json(#[from] serde_json::Error),
115    #[error("RPC error: {0}")]
116    Rpc(String),
117    #[error("Transaction failed: {0}")]
118    TxFailed(String),
119    #[error("Timeout waiting for fulfillment of request {0}")]
120    Timeout(u64),
121    #[error("Request {0} not fulfilled")]
122    NotFulfilled(u64),
123    #[error("Simulation failed: {0}")]
124    SimulationFailed(String),
125}
126
127// ── JSON-RPC types ───────────────────────────────────────────────────────────
128
129#[derive(Serialize)]
130struct JsonRpcRequest {
131    jsonrpc: String,
132    id: u64,
133    method: String,
134    params: serde_json::Value,
135}
136
137#[derive(Deserialize)]
138struct JsonRpcResponse {
139    result: Option<serde_json::Value>,
140    error: Option<serde_json::Value>,
141}
142
143#[derive(Deserialize)]
144struct SimulateResult {
145    results: Option<Vec<SimulateEntry>>,
146    error: Option<String>,
147}
148
149#[derive(Deserialize)]
150struct SimulateEntry {
151    xdr: Option<String>,
152}
153
154#[derive(Deserialize)]
155struct EventsResult {
156    events: Option<Vec<EventEntry>>,
157}
158
159#[derive(Deserialize)]
160#[serde(rename_all = "camelCase")]
161struct EventEntry {
162    ledger: Option<u64>,
163    value: Option<serde_json::Value>,
164}
165
166#[derive(Deserialize)]
167struct HealthResult {
168    #[serde(rename = "latestLedger")]
169    latest_ledger: Option<u64>,
170}
171
172// ── XDR ScVal encoding helpers ───────────────────────────────────────────────
173// These encode minimal ScVal structures for Soroban contract invocations.
174// Using raw XDR bytes avoids pulling in the full stellar-xdr crate, so every
175// layout here is pinned by golden vectors from the official encoder
176// (`@stellar/stellar-sdk`) and from Mainnet in the tests below.
177
178/// `SCValType` discriminants (Stellar-contract.x). Releases up to 2.0.0 used
179/// 9/10/13/14 for bytes/symbol/vec/map. Those values are wrong, and the RPC
180/// rejected every request built with them.
181mod scv {
182    pub const BOOL: u32 = 0;
183    pub const VOID: u32 = 1;
184    pub const U32: u32 = 3;
185    pub const U64: u32 = 5;
186    pub const BYTES: u32 = 13;
187    pub const SYMBOL: u32 = 15;
188    pub const VEC: u32 = 16;
189    pub const MAP: u32 = 17;
190    pub const ADDRESS: u32 = 18;
191}
192
193fn put_u32(buf: &mut Vec<u8>, v: u32) {
194    buf.extend_from_slice(&v.to_be_bytes());
195}
196
197/// XDR variable-length opaque/string: 4-byte length, data, zero padding to 4.
198fn put_var_opaque(buf: &mut Vec<u8>, data: &[u8]) {
199    put_u32(buf, data.len() as u32);
200    buf.extend_from_slice(data);
201    buf.resize(buf.len() + (4 - data.len() % 4) % 4, 0);
202}
203
204/// Encode a u64 as ScVal (scvU64): discriminant 5 + 8-byte BE value.
205fn encode_scval_u64(val: u64) -> Vec<u8> {
206    let mut buf = Vec::with_capacity(12);
207    put_u32(&mut buf, scv::U64);
208    buf.extend_from_slice(&val.to_be_bytes());
209    buf
210}
211
212/// Encode a byte slice as ScVal (scvBytes): discriminant 13 + var opaque.
213fn encode_scval_bytes(data: &[u8]) -> Vec<u8> {
214    let mut buf = Vec::with_capacity(8 + data.len() + 3);
215    put_u32(&mut buf, scv::BYTES);
216    put_var_opaque(&mut buf, data);
217    buf
218}
219
220/// Encode a symbol as ScVal (scvSymbol): discriminant 15 + var string.
221fn encode_scval_symbol(sym: &str) -> Vec<u8> {
222    let mut buf = Vec::with_capacity(8 + sym.len() + 3);
223    put_u32(&mut buf, scv::SYMBOL);
224    put_var_opaque(&mut buf, sym.as_bytes());
225    buf
226}
227
228// ── XDR ScVal decoding ───────────────────────────────────────────────────────
229
230/// The subset of `ScVal` this SDK reads (contract return values and events).
231#[doc(hidden)]
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub enum ScVal {
234    Bool(bool),
235    Void,
236    U32(u32),
237    U64(u64),
238    Bytes(Vec<u8>),
239    Symbol(String),
240    Vec(Vec<ScVal>),
241    Map(Vec<(ScVal, ScVal)>),
242    /// StrKey form: `G...` (account) or `C...` (contract).
243    Address(String),
244}
245
246fn xdr_err(msg: impl std::fmt::Display) -> VrfError {
247    VrfError::Rpc(format!("XDR decode error: {msg}"))
248}
249
250/// Decode one base64 ScVal, rejecting trailing bytes.
251#[doc(hidden)]
252pub fn decode_scval_b64(b64: &str) -> Result<ScVal, VrfError> {
253    let bytes = base64_decode(b64)?;
254    let mut r = XdrReader::new(&bytes);
255    let val = r.scval(0)?;
256    if r.pos != bytes.len() {
257        return Err(xdr_err(format!("{} trailing bytes", bytes.len() - r.pos)));
258    }
259    Ok(val)
260}
261
262/// Bounds-checked XDR reader. Every read fails cleanly on truncated input;
263/// nothing is silently defaulted.
264#[doc(hidden)]
265pub struct XdrReader<'a> {
266    pub data: &'a [u8],
267    pub pos: usize,
268}
269
270impl<'a> XdrReader<'a> {
271    pub fn new(data: &'a [u8]) -> Self {
272        Self { data, pos: 0 }
273    }
274
275    fn take(&mut self, n: usize) -> Result<&'a [u8], VrfError> {
276        let end = self
277            .pos
278            .checked_add(n)
279            .filter(|&e| e <= self.data.len())
280            .ok_or_else(|| xdr_err("unexpected end of input"))?;
281        let out = &self.data[self.pos..end];
282        self.pos = end;
283        Ok(out)
284    }
285
286    fn u32(&mut self) -> Result<u32, VrfError> {
287        Ok(u32::from_be_bytes(self.take(4)?.try_into().unwrap()))
288    }
289
290    fn u64(&mut self) -> Result<u64, VrfError> {
291        Ok(u64::from_be_bytes(self.take(8)?.try_into().unwrap()))
292    }
293
294    fn hash32(&mut self) -> Result<[u8; 32], VrfError> {
295        Ok(self.take(32)?.try_into().unwrap())
296    }
297
298    fn var_opaque(&mut self, max_len: usize) -> Result<&'a [u8], VrfError> {
299        let len = self.u32()? as usize;
300        if len > max_len {
301            return Err(xdr_err(format!("length {len} exceeds {max_len}")));
302        }
303        let data = self.take(len)?;
304        if self.take((4 - len % 4) % 4)?.iter().any(|&b| b != 0) {
305            return Err(xdr_err("non-zero padding"));
306        }
307        Ok(data)
308    }
309
310    /// Element count of an XDR array. Bounded by the bytes left (every element
311    /// takes at least 4 bytes), so a corrupt count can't force a huge allocation.
312    fn count(&mut self) -> Result<usize, VrfError> {
313        let n = self.u32()? as usize;
314        if n > (self.data.len() - self.pos) / 4 {
315            return Err(xdr_err(format!("element count {n} exceeds input")));
316        }
317        Ok(n)
318    }
319
320    pub fn scval(&mut self, depth: u32) -> Result<ScVal, VrfError> {
321        if depth > 8 {
322            return Err(xdr_err("ScVal nesting too deep"));
323        }
324        match self.u32()? {
325            scv::BOOL => match self.u32()? {
326                0 => Ok(ScVal::Bool(false)),
327                1 => Ok(ScVal::Bool(true)),
328                b => Err(xdr_err(format!("invalid bool {b}"))),
329            },
330            scv::VOID => Ok(ScVal::Void),
331            scv::U32 => Ok(ScVal::U32(self.u32()?)),
332            scv::U64 => Ok(ScVal::U64(self.u64()?)),
333            scv::BYTES => Ok(ScVal::Bytes(self.var_opaque(usize::MAX)?.to_vec())),
334            scv::SYMBOL => {
335                let s = self.var_opaque(32)?;
336                String::from_utf8(s.to_vec())
337                    .map(ScVal::Symbol)
338                    .map_err(|_| xdr_err("symbol is not UTF-8"))
339            }
340            // `SCVec *vec` / `SCMap *map` are XDR optionals: 0 = absent.
341            scv::VEC => {
342                if self.u32()? == 0 {
343                    return Ok(ScVal::Vec(Vec::new()));
344                }
345                let n = self.count()?;
346                let mut items = Vec::with_capacity(n);
347                for _ in 0..n {
348                    items.push(self.scval(depth + 1)?);
349                }
350                Ok(ScVal::Vec(items))
351            }
352            scv::MAP => {
353                if self.u32()? == 0 {
354                    return Ok(ScVal::Map(Vec::new()));
355                }
356                let n = self.count()?;
357                let mut entries = Vec::with_capacity(n);
358                for _ in 0..n {
359                    let k = self.scval(depth + 1)?;
360                    let v = self.scval(depth + 1)?;
361                    entries.push((k, v));
362                }
363                Ok(ScVal::Map(entries))
364            }
365            scv::ADDRESS => match self.u32()? {
366                // SC_ADDRESS_TYPE_ACCOUNT: AccountID is a PublicKey union whose
367                // own tag (0 = ed25519) precedes the 32-byte key.
368                0 => match self.u32()? {
369                    0 => Ok(ScVal::Address(strkey_encode_ed25519(&self.hash32()?))),
370                    t => Err(xdr_err(format!("unsupported public key type {t}"))),
371                },
372                // SC_ADDRESS_TYPE_CONTRACT: 32-byte contract hash.
373                1 => Ok(ScVal::Address(strkey_encode_contract(&self.hash32()?))),
374                t => Err(xdr_err(format!("unsupported address type {t}"))),
375            },
376            t => Err(xdr_err(format!("unsupported ScVal type {t}"))),
377        }
378    }
379}
380
381/// Base64-encode bytes.
382fn to_base64(data: &[u8]) -> String {
383    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
384    let mut out = String::new();
385    for chunk in data.chunks(3) {
386        let b0 = chunk[0] as u32;
387        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
388        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
389        let triple = (b0 << 16) | (b1 << 8) | b2;
390        out.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
391        out.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
392        if chunk.len() > 1 {
393            out.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
394        } else {
395            out.push('=');
396        }
397        if chunk.len() > 2 {
398            out.push(CHARS[(triple & 0x3F) as usize] as char);
399        } else {
400            out.push('=');
401        }
402    }
403    out
404}
405
406// ── VRF Client ───────────────────────────────────────────────────────────────
407
408/// High-level async client for the Stellar VRF Oracle.
409///
410/// All read operations use `simulateTransaction` (free, no signing needed).
411/// Write operations (request, etc.) require a funded keypair.
412pub struct VrfClient {
413    config: VrfClientConfig,
414    http: reqwest::Client,
415}
416
417impl VrfClient {
418    /// Create a new VRF client.
419    pub fn new(config: VrfClientConfig) -> Self {
420        Self {
421            config,
422            http: reqwest::Client::new(),
423        }
424    }
425
426    // ── Read-only queries (via simulateTransaction) ──────────────────────────
427
428    /// Check if a request has been fulfilled.
429    pub async fn is_fulfilled(&self, request_id: u64) -> Result<bool, VrfError> {
430        let result = self
431            .simulate_call("is_fulfilled", &[encode_scval_u64(request_id)])
432            .await?;
433        decode_bool_result(result)
434    }
435
436    /// Check if a request has been refunded.
437    pub async fn is_refunded(&self, request_id: u64) -> Result<bool, VrfError> {
438        let result = self
439            .simulate_call("is_refunded", &[encode_scval_u64(request_id)])
440            .await?;
441        decode_bool_result(result)
442    }
443
444    /// Derive a random number in the inclusive range `[min, max]` from a
445    /// fulfilled request.
446    ///
447    /// The on-chain `derive_random_in_range(request_id, max)` returns a value
448    /// in `[0, max)` that is **exactly** uniform (rejection sampling, no modulo
449    /// bias). This helper requests a span of `max - min + 1` and shifts the
450    /// result by `min` to cover the inclusive range. The result equals
451    /// `min + `[`derive_range_from_beta`]`(beta, request_id, span)`.
452    ///
453    /// There is no caller-chosen context: a value picked after the result is
454    /// known would allow grinding. Bind application data at `request()` time,
455    /// or use [`Self::derive_range_for_domain`] with a **fixed** domain.
456    ///
457    /// This calls the contract via simulation, so no transaction fee is charged.
458    ///
459    /// # Range limit
460    /// The contract takes an exclusive `u64` upper bound, so the widest inclusive
461    /// range it can serve has `2^64 - 1` values. The single range it can't
462    /// express, `[0, u64::MAX]`, returns an error instead of overflowing. For
463    /// full-width randomness use [`derive_random_from_beta`] or the raw beta.
464    pub async fn derive_random_in_range(
465        &self,
466        request_id: u64,
467        min: u64,
468        max: u64,
469    ) -> Result<u64, VrfError> {
470        let span = inclusive_span(min, max)?;
471        let result = self
472            .simulate_call(
473                "derive_random_in_range",
474                &[encode_scval_u64(request_id), encode_scval_u64(span)],
475            )
476            .await?;
477        Ok(decode_u64_result(result, request_id)? + min)
478    }
479
480    /// Like [`Self::derive_random_in_range`], with a short domain separator so
481    /// one request can feed several independent draws.
482    ///
483    /// # The domain MUST be fixed before fulfillment
484    /// If anyone can choose `domain` after the randomness is public, they can
485    /// try many domains and keep the result they like. Only use constants or
486    /// values committed before `request()`. At most
487    /// [`MAX_DERIVE_DOMAIN_LEN`] bytes.
488    pub async fn derive_range_for_domain(
489        &self,
490        request_id: u64,
491        domain: &[u8],
492        min: u64,
493        max: u64,
494    ) -> Result<u64, VrfError> {
495        if domain.len() > MAX_DERIVE_DOMAIN_LEN {
496            return Err(VrfError::Rpc(format!(
497                "domain is {} bytes; the contract accepts at most {MAX_DERIVE_DOMAIN_LEN}",
498                domain.len()
499            )));
500        }
501        let span = inclusive_span(min, max)?;
502        let result = self
503            .simulate_call(
504                "derive_range_for_domain",
505                &[
506                    encode_scval_u64(request_id),
507                    encode_scval_bytes(domain),
508                    encode_scval_u64(span),
509                ],
510            )
511            .await?;
512        Ok(decode_u64_result(result, request_id)? + min)
513    }
514
515    /// The verified 32-byte beta of a fulfilled request (`get_beta`). Kept by
516    /// the contract after `cleanup_proof()`.
517    pub async fn get_beta(&self, request_id: u64) -> Result<[u8; 32], VrfError> {
518        let result = self
519            .simulate_call("get_beta", &[encode_scval_u64(request_id)])
520            .await?;
521        decode_beta_result(result, request_id)
522    }
523}
524
525/// Decode a simulated `bool` return value. A missing value is an error rather
526/// than `false`, so an RPC problem can't pass for "not fulfilled".
527fn decode_bool_result(result: Option<String>) -> Result<bool, VrfError> {
528    let xdr_b64 = result.ok_or_else(|| VrfError::Rpc("simulation returned no value".into()))?;
529    match decode_scval_b64(&xdr_b64)? {
530        ScVal::Bool(b) => Ok(b),
531        other => Err(VrfError::Rpc(format!("expected bool ScVal, got {other:?}"))),
532    }
533}
534
535/// Decode a simulated `BytesN<32>` return value.
536fn decode_beta_result(result: Option<String>, request_id: u64) -> Result<[u8; 32], VrfError> {
537    let xdr_b64 = result.ok_or(VrfError::NotFulfilled(request_id))?;
538    match decode_scval_b64(&xdr_b64)? {
539        ScVal::Bytes(b) => b
540            .try_into()
541            .map_err(|b: Vec<u8>| VrfError::Rpc(format!("expected 32-byte beta, got {}", b.len()))),
542        other => Err(VrfError::Rpc(format!(
543            "expected BytesN<32> ScVal, got {other:?}"
544        ))),
545    }
546}
547
548/// Decode a simulated `u64` ScVal return value.
549fn decode_u64_result(result: Option<String>, request_id: u64) -> Result<u64, VrfError> {
550    let xdr_b64 = result.ok_or(VrfError::NotFulfilled(request_id))?;
551    match decode_scval_b64(&xdr_b64)? {
552        ScVal::U64(v) => Ok(v),
553        other => Err(VrfError::Rpc(format!("expected u64 ScVal, got {other:?}"))),
554    }
555}
556
557impl VrfClient {
558    /// Wait until a request is fulfilled, polling every 3 seconds.
559    ///
560    /// Each RPC call is given a 10-second per-call deadline via
561    /// `tokio::time::timeout`. Transient errors (RPC failures, timeouts) are
562    /// treated as retryable: they are logged and the loop continues. Only when
563    /// the outer `timeout_secs` deadline expires does this return `Err(Timeout)`.
564    pub async fn wait_for_fulfillment(
565        &self,
566        request_id: u64,
567        timeout_secs: u64,
568    ) -> Result<(), VrfError> {
569        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
570        const RPC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
571
572        while std::time::Instant::now() < deadline {
573            // Wrap the RPC call in a per-call timeout so a stalled connection
574            // cannot block the loop past the outer deadline.
575            match tokio::time::timeout(RPC_TIMEOUT, self.is_fulfilled(request_id)).await {
576                Ok(Ok(true)) => return Ok(()),
577                Ok(Ok(false)) => {
578                    // Not yet fulfilled — sleep and retry.
579                }
580                Ok(Err(err)) => {
581                    // Transient RPC/network error. Log and retry rather than
582                    // returning immediately, because the deadline is the correct
583                    // termination condition.
584                    eprintln!(
585                        "[stellar-vrf-sdk] wait_for_fulfillment: transient error for request {}: {}. Retrying…",
586                        request_id, err
587                    );
588                }
589                Err(_elapsed) => {
590                    // Per-call timeout fired. Log and retry.
591                    eprintln!(
592                        "[stellar-vrf-sdk] wait_for_fulfillment: RPC call timed out for request {} ({}s limit). Retrying…",
593                        request_id, RPC_TIMEOUT.as_secs()
594                    );
595                }
596            }
597            tokio::time::sleep(std::time::Duration::from_secs(3)).await;
598        }
599
600        Err(VrfError::Timeout(request_id))
601    }
602
603    /// Get the latest ledger sequence number from the Soroban RPC.
604    pub async fn get_latest_ledger(&self) -> Result<u64, VrfError> {
605        let resp = self.rpc_call("getHealth", serde_json::json!({})).await?;
606        let health: HealthResult = serde_json::from_value(resp)?;
607        health
608            .latest_ledger
609            .ok_or_else(|| VrfError::Rpc("No latestLedger in health response".into()))
610    }
611
612    /// Get recent VRF request events from the contract.
613    pub async fn get_request_events(
614        &self,
615        start_ledger: u64,
616        limit: u64,
617    ) -> Result<Vec<VrfRequestEvent>, VrfError> {
618        let topic_xdr = to_base64(&encode_scval_symbol("request"));
619        let resp = self
620            .rpc_call(
621                "getEvents",
622                serde_json::json!({
623                    "filters": [{
624                        "type": "contract",
625                        "contractIds": [self.config.contract_id],
626                        "topics": [[topic_xdr]]
627                    }],
628                    "startLedger": start_ledger,
629                    "pagination": { "limit": limit }
630                }),
631            )
632            .await?;
633
634        let events_result: EventsResult = serde_json::from_value(resp)?;
635        events_result
636            .events
637            .unwrap_or_default()
638            .iter()
639            .map(|evt| {
640                let (request_id, requester, required_round) =
641                    parse_request_event_value(event_value_b64(evt)?)?;
642                Ok(VrfRequestEvent {
643                    request_id,
644                    requester,
645                    required_round,
646                    ledger: evt.ledger.unwrap_or(0),
647                })
648            })
649            .collect()
650    }
651
652    /// Get recent fulfill events from the contract.
653    pub async fn get_fulfill_events(
654        &self,
655        start_ledger: u64,
656        limit: u64,
657    ) -> Result<Vec<(u64, u64)>, VrfError> {
658        // Returns (request_id, ledger) pairs
659        let topic_xdr = to_base64(&encode_scval_symbol("fulfill"));
660        let resp = self
661            .rpc_call(
662                "getEvents",
663                serde_json::json!({
664                    "filters": [{
665                        "type": "contract",
666                        "contractIds": [self.config.contract_id],
667                        "topics": [[topic_xdr]]
668                    }],
669                    "startLedger": start_ledger,
670                    "pagination": { "limit": limit }
671                }),
672            )
673            .await?;
674
675        let events_result: EventsResult = serde_json::from_value(resp)?;
676        events_result
677            .events
678            .unwrap_or_default()
679            .iter()
680            .map(|evt| {
681                let (request_id, _beta) = parse_fulfill_event_value(event_value_b64(evt)?)?;
682                Ok((request_id, evt.ledger.unwrap_or(0)))
683            })
684            .collect()
685    }
686
687    // ── Private helpers ──────────────────────────────────────────────────────
688
689    /// Make a JSON-RPC call to the Soroban RPC endpoint.
690    async fn rpc_call(
691        &self,
692        method: &str,
693        params: serde_json::Value,
694    ) -> Result<serde_json::Value, VrfError> {
695        let req = JsonRpcRequest {
696            jsonrpc: "2.0".into(),
697            id: 1,
698            method: method.into(),
699            params,
700        };
701
702        let resp: JsonRpcResponse = self
703            .http
704            .post(self.config.network.rpc_url())
705            .json(&req)
706            .send()
707            .await?
708            .json()
709            .await?;
710
711        if let Some(err) = resp.error {
712            return Err(VrfError::Rpc(format!("{}", err)));
713        }
714
715        resp.result
716            .ok_or_else(|| VrfError::Rpc("No result in RPC response".into()))
717    }
718
719    /// Simulate a contract call and return the result XDR (base64).
720    ///
721    /// This builds a minimal invokeHostFunction XDR envelope, sends it to
722    /// `simulateTransaction`, and extracts the return value.
723    async fn simulate_call(
724        &self,
725        fn_name: &str,
726        args: &[Vec<u8>],
727    ) -> Result<Option<String>, VrfError> {
728        let contract = strkey_decode_contract(&self.config.contract_id)?;
729        let envelope = build_simulation_envelope(&contract, fn_name, args);
730        let resp = self
731            .rpc_call(
732                "simulateTransaction",
733                serde_json::json!({ "transaction": to_base64(&envelope) }),
734            )
735            .await?;
736
737        let sim: SimulateResult = serde_json::from_value(resp)?;
738
739        if let Some(err) = sim.error {
740            return Err(VrfError::SimulationFailed(err));
741        }
742
743        if let Some(results) = sim.results {
744            if let Some(first) = results.first() {
745                return Ok(first.xdr.clone());
746            }
747        }
748
749        Ok(None)
750    }
751}
752
753// ── StrKey decoding ──────────────────────────────────────────────────────────
754
755// ── StrKey encoding ──────────────────────────────────────────────────────────
756
757/// CRC16-XModem, the checksum StrKey uses (SEP-0023).
758fn crc16_xmodem(data: &[u8]) -> u16 {
759    let mut crc: u16 = 0x0000;
760    for &byte in data {
761        crc ^= (byte as u16) << 8;
762        for _ in 0..8 {
763            if crc & 0x8000 != 0 {
764                crc = (crc << 1) ^ 0x1021;
765            } else {
766                crc <<= 1;
767            }
768        }
769    }
770    crc
771}
772
773/// RFC 4648 base32 (no padding), the alphabet StrKey uses.
774fn base32_encode(data: &[u8]) -> String {
775    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
776    let mut out = String::new();
777    let mut buffer: u32 = 0;
778    let mut bits: u32 = 0;
779    for &b in data {
780        buffer = (buffer << 8) | b as u32;
781        bits += 8;
782        while bits >= 5 {
783            bits -= 5;
784            out.push(ALPHABET[((buffer >> bits) & 0x1F) as usize] as char);
785        }
786    }
787    if bits > 0 {
788        out.push(ALPHABET[((buffer << (5 - bits)) & 0x1F) as usize] as char);
789    }
790    out
791}
792
793/// Encode a 32-byte payload as StrKey with the given version byte.
794///
795/// Layout: `base32(version_byte ‖ payload ‖ crc16_xmodem_le)`.
796fn strkey_encode(version_byte: u8, payload: &[u8]) -> String {
797    let mut buf = Vec::with_capacity(1 + payload.len() + 2);
798    buf.push(version_byte);
799    buf.extend_from_slice(payload);
800    let crc = crc16_xmodem(&buf);
801    buf.extend_from_slice(&crc.to_le_bytes()); // StrKey checksum is little-endian
802    base32_encode(&buf)
803}
804
805/// Encode an ed25519 public key as a `G...` account address.
806///
807/// Version byte 6 << 3 = 0x30. Previously this code emitted `format!("G{hex}")`,
808/// which merely *looks* like an address: it is not base32, carries no checksum
809/// and is rejected by every Stellar tool. Event consumers received unusable
810/// requester values.
811pub fn strkey_encode_ed25519(key: &[u8]) -> String {
812    strkey_encode(6 << 3, key)
813}
814
815/// Encode a 32-byte contract hash as a `C...` contract address (version byte 2 << 3).
816pub fn strkey_encode_contract(hash: &[u8]) -> String {
817    strkey_encode(2 << 3, hash)
818}
819
820/// Decode a Stellar StrKey contract ID (C...) to its 32-byte hash.
821///
822/// Layout: `base32(version_byte ‖ 32-byte payload ‖ crc16_xmodem_le)`, 56 chars.
823/// The length, the contract version byte (`2 << 3`) and the CRC16 checksum are
824/// all checked, so a typo or a `G...` account address is rejected instead of
825/// being silently turned into a different contract hash.
826#[doc(hidden)]
827pub fn strkey_decode_contract(contract_id: &str) -> Result<[u8; 32], VrfError> {
828    let bad = |m: &str| VrfError::Rpc(format!("Invalid contract ID: {}", m));
829    if contract_id.len() != 56 {
830        return Err(bad("expected 56 characters"));
831    }
832    let decoded = base32_decode(contract_id).map_err(|e| bad(&e))?;
833    if decoded.len() != 35 {
834        return Err(bad("wrong decoded length"));
835    }
836    if decoded[0] != 2 << 3 {
837        return Err(bad("not a contract (C...) address"));
838    }
839    let expected = crc16_xmodem(&decoded[..33]);
840    let actual = u16::from_le_bytes([decoded[33], decoded[34]]);
841    if expected != actual {
842        return Err(bad("checksum mismatch"));
843    }
844    // Re-encoding must reproduce the input exactly (rejects non-canonical
845    // trailing bits in the last base32 character).
846    if strkey_encode(2 << 3, &decoded[1..33]) != contract_id {
847        return Err(bad("non-canonical encoding"));
848    }
849
850    let mut hash = [0u8; 32];
851    hash.copy_from_slice(&decoded[1..33]);
852    Ok(hash)
853}
854
855/// Simple base32 decoder (RFC 4648, no padding required).
856#[doc(hidden)]
857pub fn base32_decode(input: &str) -> Result<Vec<u8>, String> {
858    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
859    let input = input.trim_end_matches('=');
860    let mut bits = 0u64;
861    let mut bit_count = 0u32;
862    let mut out = Vec::new();
863
864    for ch in input.bytes() {
865        let val = ALPHABET
866            .iter()
867            .position(|&c| c == ch)
868            .ok_or_else(|| format!("Invalid base32 character: {}", ch as char))?
869            as u64;
870        bits = (bits << 5) | val;
871        bit_count += 5;
872        if bit_count >= 8 {
873            bit_count -= 8;
874            out.push((bits >> bit_count) as u8);
875            bits &= (1 << bit_count) - 1;
876        }
877    }
878
879    Ok(out)
880}
881
882/// Decode base64 to bytes.
883#[doc(hidden)]
884pub fn base64_decode(input: &str) -> Result<Vec<u8>, VrfError> {
885    const TABLE: [u8; 128] = {
886        let mut t = [0xFF; 128];
887        let chars = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
888        let mut i = 0;
889        while i < 64 {
890            t[chars[i] as usize] = i as u8;
891            i += 1;
892        }
893        t
894    };
895
896    let input = input.trim_end_matches('=');
897    let mut out = Vec::new();
898    let bytes: Vec<u8> = input
899        .bytes()
900        .filter(|b| *b != b'\n' && *b != b'\r')
901        .collect();
902
903    // Bit accumulator: 6 bits per base64 symbol, emit a byte per 8 buffered bits.
904    let mut buffer: u32 = 0;
905    let mut bits: u32 = 0;
906    for &b in &bytes {
907        if (b as usize) >= 128 || TABLE[b as usize] == 0xFF {
908            return Err(VrfError::Rpc(format!(
909                "invalid base64 character: {:?}",
910                b as char
911            )));
912        }
913        buffer = (buffer << 6) | TABLE[b as usize] as u32;
914        bits += 6;
915        if bits >= 8 {
916            bits -= 8;
917            out.push(((buffer >> bits) & 0xFF) as u8);
918        }
919    }
920
921    Ok(out)
922}
923
924#[doc(hidden)]
925pub mod internal {
926    pub use super::{
927        base32_decode, base64_decode, decode_scval_b64, strkey_decode_contract, ScVal, XdrReader,
928    };
929}
930
931/// Build an unsigned `TransactionEnvelope` (v1) that invokes
932/// `contract.fn_name(args)`, for `simulateTransaction` only.
933///
934/// `simulateTransaction` needs a well-formed envelope, but it doesn't check
935/// signatures or sequence numbers, and it doesn't require the source account
936/// to exist. So this uses the all-zero ed25519 source
937/// (`GAAAA…WHF`), sequence 1 and no signatures. It is the same envelope
938/// `@stellar/stellar-sdk` builds for read-only calls (see the golden test).
939/// This envelope can't be submitted. Writes are out of scope for this SDK.
940///
941/// Releases up to 2.0.0 sent only the bare `InvokeContractArgs` bytes here, and
942/// the RPC rejected them with "Could not unmarshal transaction".
943fn build_simulation_envelope(contract: &[u8; 32], fn_name: &str, args: &[Vec<u8>]) -> Vec<u8> {
944    let mut b = Vec::with_capacity(160 + args.iter().map(Vec::len).sum::<usize>());
945    put_u32(&mut b, 2); // EnvelopeType::ENVELOPE_TYPE_TX
946                        // Transaction.sourceAccount: MuxedAccount KEY_TYPE_ED25519 + 32-byte key.
947    put_u32(&mut b, 0);
948    b.extend_from_slice(&[0u8; 32]);
949    put_u32(&mut b, 100); // fee (stroops); simulation ignores it
950    b.extend_from_slice(&1u64.to_be_bytes()); // seqNum
951                                              // cond: PRECOND_TIME with TimeBounds { min: 0, max: 0 } (no bounds).
952    put_u32(&mut b, 1);
953    b.extend_from_slice(&[0u8; 16]);
954    put_u32(&mut b, 0); // memo: MEMO_NONE
955    put_u32(&mut b, 1); // operations.len()
956    put_u32(&mut b, 0); // Operation.sourceAccount: absent
957    put_u32(&mut b, 24); // OperationType::INVOKE_HOST_FUNCTION
958    put_u32(&mut b, 0); // HostFunctionType::INVOKE_CONTRACT
959                        // InvokeContractArgs { contractAddress, functionName, args }
960    put_u32(&mut b, 1); // ScAddressType::CONTRACT
961    b.extend_from_slice(contract);
962    put_var_opaque(&mut b, fn_name.as_bytes());
963    put_u32(&mut b, args.len() as u32);
964    for a in args {
965        b.extend_from_slice(a);
966    }
967    put_u32(&mut b, 0); // InvokeHostFunctionOp.auth.len()
968    put_u32(&mut b, 0); // Transaction.ext: v0
969    put_u32(&mut b, 0); // signatures.len()
970    b
971}
972
973// ── Client-side utilities ────────────────────────────────────────────────────
974
975/// Number of values in the inclusive range `[min, max]`, as the contract's
976/// exclusive `u64` bound.
977///
978/// `max - min + 1` overflows `u64` for exactly one input, `[0, u64::MAX]`
979/// (`2^64` values). That range can't be expressed to the contract, so it's
980/// rejected with an explicit error instead of panicking in debug builds or
981/// silently wrapping to `0` in release builds.
982fn inclusive_span(min: u64, max: u64) -> Result<u64, VrfError> {
983    if max < min {
984        return Err(VrfError::Rpc("max must be >= min".into()));
985    }
986    (max - min).checked_add(1).ok_or_else(|| {
987        VrfError::Rpc(
988            "range [0, u64::MAX] has 2^64 values and cannot be expressed as the contract's \
989             exclusive u64 bound; use derive_random_from_beta() or the raw beta instead"
990                .into(),
991        )
992    })
993}
994
995// ── Offline derivation (byte-for-byte identical to the contract) ─────────────
996
997/// Domain prefix of every contract derivation (`DERIVE_DOMAIN`).
998pub const DERIVE_DOMAIN: &[u8] = b"VREP_DERIVE_V2";
999const DERIVE_TAG_U64: u8 = 0x01;
1000const DERIVE_TAG_RANGE: u8 = 0x02;
1001const DERIVE_TAG_RANGE_DOMAIN: u8 = 0x03;
1002/// Longest domain accepted by `derive_range_for_domain` (`MAX_DERIVE_DOMAIN_LEN`).
1003pub const MAX_DERIVE_DOMAIN_LEN: usize = 64;
1004
1005fn derive_hash(tag: u8, request_id: u64, parts: &[&[u8]], beta: &[u8; 32]) -> [u8; 32] {
1006    use sha2::{Digest, Sha256};
1007    let mut h = Sha256::new();
1008    h.update(DERIVE_DOMAIN);
1009    h.update([tag]);
1010    h.update(request_id.to_be_bytes());
1011    for p in parts {
1012        h.update(p);
1013    }
1014    h.update(beta);
1015    h.finalize().into()
1016}
1017
1018/// Exact-uniform reduction of a 32-byte hash into `[0, max)`, identical to the
1019/// contract's `reduce_uniform()`.
1020///
1021/// The hash is split into two 128-bit big-endian candidates. A candidate `c` is
1022/// accepted iff `c < limit`, where `limit = 2^128 - (2^128 mod max)` is the
1023/// largest multiple of `max` that fits. The result `c mod max` is then exactly
1024/// uniform. If both are rejected (probability < 2^-128) this returns an error,
1025/// just like the contract panics. There is no biased fallback.
1026pub fn reduce_uniform(hash: &[u8; 32], max: u64) -> Result<u64, VrfError> {
1027    if max == 0 {
1028        return Err(VrfError::Rpc("max must be > 0".into()));
1029    }
1030    let m = max as u128;
1031    let rem = 0u128.wrapping_sub(m) % m; // 2^128 mod max
1032    for half in [&hash[0..16], &hash[16..32]] {
1033        let c = u128::from_be_bytes(half.try_into().unwrap());
1034        if c <= u128::MAX - rem {
1035            return Ok((c % m) as u64);
1036        }
1037    }
1038    Err(VrfError::Rpc(
1039        "range derivation failed: both candidates rejected".into(),
1040    ))
1041}
1042
1043/// Offline equivalent of the contract's `derive_random(request_id)`.
1044pub fn derive_u64_from_beta(beta: &[u8; 32], request_id: u64) -> u64 {
1045    let h = derive_hash(DERIVE_TAG_U64, request_id, &[], beta);
1046    u64::from_be_bytes(h[0..8].try_into().unwrap())
1047}
1048
1049/// Offline equivalent of the contract's `derive_random_in_range(request_id, max)`:
1050/// an exactly uniform value in `[0, max)`.
1051pub fn derive_range_from_beta(beta: &[u8; 32], request_id: u64, max: u64) -> Result<u64, VrfError> {
1052    if max == 0 {
1053        return Err(VrfError::Rpc("max must be > 0".into()));
1054    }
1055    if max == 1 {
1056        return Ok(0);
1057    }
1058    let h = derive_hash(DERIVE_TAG_RANGE, request_id, &[&max.to_be_bytes()], beta);
1059    reduce_uniform(&h, max)
1060}
1061
1062/// Offline equivalent of the contract's
1063/// `derive_range_for_domain(request_id, domain, max)`.
1064///
1065/// **The domain must be fixed before fulfillment** (a constant, or a value
1066/// committed before `request()`); otherwise whoever picks it can grind.
1067pub fn derive_range_for_domain_from_beta(
1068    beta: &[u8; 32],
1069    request_id: u64,
1070    domain: &[u8],
1071    max: u64,
1072) -> Result<u64, VrfError> {
1073    if max == 0 {
1074        return Err(VrfError::Rpc("max must be > 0".into()));
1075    }
1076    if domain.len() > MAX_DERIVE_DOMAIN_LEN {
1077        return Err(VrfError::Rpc("domain exceeds maximum length".into()));
1078    }
1079    if max == 1 {
1080        return Ok(0);
1081    }
1082    let len = (domain.len() as u32).to_be_bytes();
1083    let h = derive_hash(
1084        DERIVE_TAG_RANGE_DOMAIN,
1085        request_id,
1086        &[&len, domain, &max.to_be_bytes()],
1087        beta,
1088    );
1089    reduce_uniform(&h, max)
1090}
1091
1092/// Derive a random number in the inclusive range `[min, max]` client-side from a
1093/// beta output, without a contract call.
1094///
1095/// **Deprecated:** not the contract's function, and only negligibly (≤ 2^-64)
1096/// rather than exactly uniform. Use [`derive_range_from_beta`], which matches
1097/// the contract's `derive_random_in_range` exactly.
1098///
1099/// This is a pure, deterministic function of `beta`, so anyone holding the
1100/// verified beta can reproduce it. It is **not** the same function as the
1101/// contract's `derive_random_in_range(request_id, context, max)`, which first
1102/// hashes `domain ‖ beta ‖ context`. Don't mix the two for the same purpose. Use
1103/// one consistently and document which one your application uses.
1104///
1105/// The full range `[0, u64::MAX]` is supported.
1106///
1107/// # Bias
1108/// Consumes **128 bits** of `beta` and reduces modulo the range. For a uniform
1109/// `x` in `[0, 2^128)` and any range `<= 2^64`, the deviation between residue
1110/// classes is bounded by `range / 2^128 <= 2^-64`, which is cryptographically
1111/// negligible.
1112///
1113/// An earlier version used only the first 64 bits, giving a bias of up to
1114/// `range / 2^64`, which becomes significant for very large ranges (approaching
1115/// a 50% skew as the range approaches `2^63`).
1116#[deprecated(
1117    since = "2.0.0",
1118    note = "use derive_range_from_beta(), which matches the contract and is exactly uniform"
1119)]
1120pub fn derive_random_from_beta(beta: &[u8], min: u64, max: u64) -> Result<u64, VrfError> {
1121    if max <= min {
1122        return Err(VrfError::Rpc("max must be greater than min".into()));
1123    }
1124    if beta.len() < 16 {
1125        return Err(VrfError::Rpc("beta must be at least 16 bytes".into()));
1126    }
1127    // Widen BEFORE adding 1: `(max - min + 1)` in u64 overflows for [0, u64::MAX].
1128    let range = (max - min) as u128 + 1;
1129    let beta_val = u128::from_be_bytes(beta[0..16].try_into().unwrap());
1130    // beta_val % range <= max - min, so the u64 cast and the addition can't overflow.
1131    Ok(min + (beta_val % range) as u64)
1132}
1133
1134/// Convert bytes to hex string.
1135pub fn to_hex(bytes: &[u8]) -> String {
1136    bytes.iter().map(|b| format!("{:02x}", b)).collect()
1137}
1138
1139// ── Event value parsing ──────────────────────────────────────────────────────
1140
1141/// The base64 `value` of a getEvents entry.
1142fn event_value_b64(evt: &EventEntry) -> Result<&str, VrfError> {
1143    match &evt.value {
1144        Some(serde_json::Value::String(s)) => Ok(s),
1145        other => Err(VrfError::Rpc(format!(
1146            "event has no base64 value: {other:?}"
1147        ))),
1148    }
1149}
1150
1151/// Parse the value of a `request` event.
1152///
1153/// The contract publishes a tuple, i.e. an `ScVec`:
1154/// `(request_id: u64, requester: Address, required_round: u64)`.
1155/// Early deployments emitted `(request_id, requester)` without the round. That
1156/// form is accepted with `required_round = 0`. Anything else is an error:
1157/// earlier releases silently returned `(0, "", 0)`, which callers couldn't tell
1158/// apart from a real request #0.
1159fn parse_request_event_value(value_b64: &str) -> Result<(u64, String, u64), VrfError> {
1160    let bad = |v: &ScVal| VrfError::Rpc(format!("unexpected request event value: {v:?}"));
1161    let val = decode_scval_b64(value_b64)?;
1162    match &val {
1163        ScVal::Vec(items) => match items.as_slice() {
1164            [ScVal::U64(id), ScVal::Address(who), ScVal::U64(round)] => {
1165                Ok((*id, who.clone(), *round))
1166            }
1167            [ScVal::U64(id), ScVal::Address(who)] => Ok((*id, who.clone(), 0)),
1168            _ => Err(bad(&val)),
1169        },
1170        _ => Err(bad(&val)),
1171    }
1172}
1173
1174/// Parse the value of a `fulfill` event: an `ScVec`
1175/// `(request_id: u64, beta: BytesN<32>)`.
1176fn parse_fulfill_event_value(value_b64: &str) -> Result<(u64, [u8; 32]), VrfError> {
1177    let bad = |v: &ScVal| VrfError::Rpc(format!("unexpected fulfill event value: {v:?}"));
1178    let val = decode_scval_b64(value_b64)?;
1179    match &val {
1180        ScVal::Vec(items) => match items.as_slice() {
1181            [ScVal::U64(id), ScVal::Bytes(beta)] => {
1182                let beta: [u8; 32] = beta.as_slice().try_into().map_err(|_| bad(&val))?;
1183                Ok((*id, beta))
1184            }
1185            _ => Err(bad(&val)),
1186        },
1187        _ => Err(bad(&val)),
1188    }
1189}
1190
1191// ── Tests ────────────────────────────────────────────────────────────────────
1192
1193#[cfg(test)]
1194#[allow(deprecated)] // the legacy derive_random_from_beta keeps its regression tests
1195mod tests {
1196    use super::*;
1197
1198    /// Shared cross-implementation vectors: beta = 0x00..0x1f, request_id = 7.
1199    /// Identical constants are asserted by the contract's
1200    /// `test_derive_vectors_shared_with_sdks` and the JS SDK.
1201    fn vec_beta() -> [u8; 32] {
1202        let mut b = [0u8; 32];
1203        for (i, x) in b.iter_mut().enumerate() {
1204            *x = i as u8;
1205        }
1206        b
1207    }
1208
1209    #[test]
1210    fn test_derive_vectors_match_contract() {
1211        let beta = vec_beta();
1212        assert_eq!(derive_u64_from_beta(&beta, 7), 17_155_214_937_666_214_782);
1213        assert_eq!(derive_range_from_beta(&beta, 7, 6).unwrap(), 4);
1214        assert_eq!(
1215            derive_range_from_beta(&beta, 7, 1_000_000).unwrap(),
1216            889_164
1217        );
1218        assert_eq!(
1219            derive_range_from_beta(&beta, 7, u64::MAX).unwrap(),
1220            11_798_261_183_955_500_607
1221        );
1222        assert_eq!(
1223            derive_range_for_domain_from_beta(&beta, 7, b"card-1", 1000).unwrap(),
1224            595
1225        );
1226    }
1227
1228    fn halves(c1: u128, c2: u128) -> [u8; 32] {
1229        let mut h = [0u8; 32];
1230        h[..16].copy_from_slice(&c1.to_be_bytes());
1231        h[16..].copy_from_slice(&c2.to_be_bytes());
1232        h
1233    }
1234
1235    #[test]
1236    fn test_reduce_uniform_matches_contract_rules() {
1237        // First candidate accepted.
1238        assert_eq!(
1239            reduce_uniform(&halves(123_456_789, 42), 1_000_003).unwrap(),
1240            123_456_789 % 1_000_003
1241        );
1242        // max = 3: 2^128 mod 3 = 1, so u128::MAX is the single rejected value.
1243        assert_eq!(
1244            reduce_uniform(&halves(u128::MAX - 1, 0), 3).unwrap(),
1245            ((u128::MAX - 1) % 3) as u64
1246        );
1247        assert_eq!(reduce_uniform(&halves(u128::MAX, 5), 3).unwrap(), 2);
1248        // Both rejected: explicit error, no biased fallback.
1249        let err = reduce_uniform(&halves(u128::MAX, u128::MAX), (1 << 63) + 1).unwrap_err();
1250        assert!(err.to_string().contains("both candidates rejected"));
1251        // Powers of two never reject.
1252        assert_eq!(
1253            reduce_uniform(&halves(u128::MAX, u128::MAX), 1 << 32).unwrap(),
1254            u32::MAX as u64
1255        );
1256        assert!(reduce_uniform(&halves(0, 0), 0).is_err());
1257    }
1258
1259    #[test]
1260    fn test_derive_range_edge_cases() {
1261        let beta = vec_beta();
1262        assert_eq!(derive_range_from_beta(&beta, 7, 1).unwrap(), 0);
1263        assert!(derive_range_from_beta(&beta, 7, 0).is_err());
1264        assert!(derive_range_for_domain_from_beta(&beta, 7, &[0u8; 65], 10).is_err());
1265        assert!(derive_range_for_domain_from_beta(&beta, 7, &[0u8; 64], 10).unwrap() < 10);
1266        // Domains and request ids separate outputs.
1267        let a = derive_range_for_domain_from_beta(&beta, 7, b"card-1", u64::MAX).unwrap();
1268        let b = derive_range_for_domain_from_beta(&beta, 7, b"card-2", u64::MAX).unwrap();
1269        let c = derive_range_from_beta(&beta, 8, u64::MAX).unwrap();
1270        assert_ne!(a, b);
1271        assert_ne!(c, derive_range_from_beta(&beta, 7, u64::MAX).unwrap());
1272    }
1273
1274    #[test]
1275    fn test_network_urls() {
1276        assert_eq!(
1277            Network::Testnet.rpc_url(),
1278            "https://soroban-testnet.stellar.org"
1279        );
1280        assert_eq!(Network::Mainnet.rpc_url(), "https://soroban.stellar.org");
1281        assert_eq!(
1282            Network::Testnet.passphrase(),
1283            "Test SDF Network ; September 2015"
1284        );
1285    }
1286
1287    #[test]
1288    fn test_derive_random_from_beta() {
1289        let beta = vec![
1290            0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1291            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1292        ];
1293        let result = derive_random_from_beta(&beta, 1, 100).unwrap();
1294        assert!((1..=100).contains(&result));
1295
1296        // Same input always produces same output (deterministic)
1297        let result2 = derive_random_from_beta(&beta, 1, 100).unwrap();
1298        assert_eq!(result, result2);
1299    }
1300
1301    #[test]
1302    fn test_derive_random_invalid_range() {
1303        let beta = vec![0u8; 32];
1304        assert!(derive_random_from_beta(&beta, 100, 1).is_err());
1305    }
1306
1307    #[test]
1308    fn test_derive_random_short_beta() {
1309        let beta = vec![0u8; 4]; // too short
1310        assert!(derive_random_from_beta(&beta, 1, 100).is_err());
1311    }
1312
1313    #[test]
1314    fn test_encode_scval_u64() {
1315        let encoded = encode_scval_u64(42);
1316        assert_eq!(encoded.len(), 12);
1317        // Discriminant 5
1318        assert_eq!(&encoded[0..4], &5u32.to_be_bytes());
1319        // Value 42
1320        assert_eq!(&encoded[4..12], &42u64.to_be_bytes());
1321    }
1322
1323    // ── Wire-format golden vectors (audit round 7) ──────────────────────────
1324    // Every expected byte string below came from the official encoder
1325    // (`@stellar/stellar-sdk` `xdr.ScVal` / `TransactionBuilder`) or from live
1326    // Mainnet `getEvents` output for CBTCC5QL…SUHU, not from this crate.
1327
1328    fn unhex(s: &str) -> Vec<u8> {
1329        (0..s.len())
1330            .step_by(2)
1331            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
1332            .collect()
1333    }
1334
1335    /// Topic filters. With the old discriminant (10 = scvI128) the RPC answered
1336    /// "decoding Int128Parts: unexpected EOF" and no events were ever returned.
1337    #[test]
1338    fn test_encode_scval_symbol_matches_stellar_sdk() {
1339        assert_eq!(
1340            to_base64(&encode_scval_symbol("request")),
1341            "AAAADwAAAAdyZXF1ZXN0AA=="
1342        );
1343        assert_eq!(
1344            to_base64(&encode_scval_symbol("fulfill")),
1345            "AAAADwAAAAdmdWxmaWxsAA=="
1346        );
1347        assert_eq!(
1348            encode_scval_symbol("test"),
1349            unhex("0000000f0000000474657374")
1350        );
1351    }
1352
1353    #[test]
1354    fn test_encode_scval_bytes_matches_stellar_sdk() {
1355        assert_eq!(
1356            encode_scval_bytes(&[0xab]),
1357            unhex("0000000d00000001ab000000")
1358        );
1359        assert_eq!(encode_scval_bytes(b""), unhex("0000000d00000000"));
1360    }
1361
1362    /// The simulation envelope must be byte-identical to what
1363    /// `TransactionBuilder` (source GAAAA…WHF, seq 1, fee 100, timeout 0)
1364    /// produces. Mainnet RPC accepted that envelope (`is_fulfilled(1)` →
1365    /// `AAAAAAAAAAE=`). The old bare `InvokeContractArgs` bytes got
1366    /// "Could not unmarshal transaction".
1367    #[test]
1368    fn test_simulation_envelope_matches_stellar_sdk() {
1369        let contract =
1370            strkey_decode_contract("CBTCC5QL5T3JSLEZO4PH6LSJYEQF6GEFDCAO67OXI4DTM5NXMK6TSUHU")
1371                .unwrap();
1372        let env = build_simulation_envelope(&contract, "is_fulfilled", &[encode_scval_u64(1)]);
1373        assert_eq!(
1374            to_base64(&env),
1375            "AAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGAAAAAAAAAABZiF2C+z2mSyZdx5/LknBIF8YhRiA733XRwc2dbdivTkAAAAMaXNfZnVsZmlsbGVkAAAAAQAAAAUAAAAAAAAAAQAAAAAAAAAAAAAAAA=="
1376        );
1377        let env = build_simulation_envelope(
1378            &contract,
1379            "derive_range_for_domain",
1380            &[
1381                encode_scval_u64(7),
1382                encode_scval_bytes(b"card-1"),
1383                encode_scval_u64(1000),
1384            ],
1385        );
1386        assert_eq!(
1387            to_base64(&env),
1388            "AAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAAAAAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGAAAAAAAAAABZiF2C+z2mSyZdx5/LknBIF8YhRiA733XRwc2dbdivTkAAAAXZGVyaXZlX3JhbmdlX2Zvcl9kb21haW4AAAAAAwAAAAUAAAAAAAAABwAAAA0AAAAGY2FyZC0xAAAAAAAFAAAAAAAAA+gAAAAAAAAAAAAAAAA="
1389        );
1390    }
1391
1392    /// Byte-for-byte what the contract emits: the same hex strings are asserted
1393    /// against the contract's real event XDR in `soroban-contract/src/test.rs`
1394    /// (`test_request_event_wire_format_matches_sdk_vector` /
1395    /// `test_fulfill_event_wire_format_matches_sdk_vector`).
1396    #[test]
1397    fn test_parse_contract_event_vectors() {
1398        let req = unhex(
1399            "00000010000000010000000300000005000000000000000100000012000000000000000011111111\
1400             11111111111111111111111111111111111111111111111111111111000000050000000001eecec8",
1401        );
1402        assert_eq!(
1403            parse_request_event_value(&to_base64(&req)).unwrap(),
1404            (
1405                1,
1406                "GAIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCF6M".to_string(),
1407                32_427_720
1408            )
1409        );
1410        let ful = unhex(
1411            "0000001000000001000000020000000500000000000000010000000d0000002098c612abed131631\
1412             47239f4323d4973cb68df7302564fc791e17c1aae95a6c9d",
1413        );
1414        let (id, beta) = parse_fulfill_event_value(&to_base64(&ful)).unwrap();
1415        assert_eq!(id, 1);
1416        assert_eq!(
1417            to_hex(&beta),
1418            "98c612abed13163147239f4323d4973cb68df7302564fc791e17c1aae95a6c9d"
1419        );
1420    }
1421
1422    /// Real `getEvents` values from Mainnet (CBTCC5QL…SUHU, ledgers 64559682 /
1423    /// 64559684), cross-checked with `scValToNative`.
1424    #[test]
1425    fn test_parse_mainnet_event_values() {
1426        let (id, who, round) = parse_request_event_value(
1427            "AAAAEAAAAAEAAAADAAAABQAAAAAAAAADAAAAEgAAAAAAAAAAmZz3cVG/1r8BH4AiQrWoVKqmI5dAl2N2ybrtTq7t8VgAAAAFAAAAAAHuy74=",
1428        )
1429        .unwrap();
1430        assert_eq!(id, 3);
1431        assert_eq!(
1432            who,
1433            "GCMZZ53RKG75NPYBD6ACEQVVVBKKVJRDS5AJOY3WZG5O2TVO5XYVR4DY"
1434        );
1435        assert_eq!(round, 32_426_942);
1436
1437        let (id, beta) = parse_fulfill_event_value(
1438            "AAAAEAAAAAEAAAACAAAABQAAAAAAAAADAAAADQAAACBDasoG50C2Z6upEOd08wHZIggLpOtuNTci6ogl5o1nkA==",
1439        )
1440        .unwrap();
1441        assert_eq!(id, 3);
1442        assert_eq!(
1443            to_hex(&beta),
1444            "436aca06e740b667aba910e774f301d922080ba4eb6e353722ea8825e68d6790"
1445        );
1446    }
1447
1448    #[test]
1449    fn test_parse_request_event_contract_requester_and_legacy_shape() {
1450        // Contract requester (callback consumers), from stellar-sdk.
1451        let (id, who, round) = parse_request_event_value(
1452            "AAAAEAAAAAEAAAADAAAABQAAAAAAAAAHAAAAEgAAAAEHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwAAAAUAAAAAAe7Oyg==",
1453        )
1454        .unwrap();
1455        assert_eq!((id, round), (7, 32_427_722));
1456        assert_eq!(
1457            who,
1458            "CADQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQOBYHA4DQP5KR"
1459        );
1460        // Early deployments: (id, requester) without the round.
1461        let (id, who, round) = parse_request_event_value(
1462            "AAAAEAAAAAEAAAACAAAABQAAAAAAAAAFAAAAEgAAAAAAAAAAERERERERERERERERERERERERERERERERERERERERERE=",
1463        )
1464        .unwrap();
1465        assert_eq!((id, round), (5, 0));
1466        assert_eq!(
1467            who,
1468            "GAIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCEIRCF6M"
1469        );
1470    }
1471
1472    /// Wrong shapes are errors. Earlier releases returned `(0, "", 0)`, which
1473    /// looked like a real request #0.
1474    #[test]
1475    fn test_parse_event_rejects_unexpected_shapes() {
1476        // Map form, from stellar-sdk: { request_id: 1 }.
1477        let map = "AAAAEQAAAAEAAAABAAAADwAAAApyZXF1ZXN0X2lkAAAAAAAFAAAAAAAAAAE=";
1478        assert!(decode_scval_b64(map).is_ok());
1479        assert!(parse_request_event_value(map).is_err());
1480        assert!(parse_fulfill_event_value(map).is_err());
1481        let bare_u64 = to_base64(&encode_scval_u64(9));
1482        assert!(parse_request_event_value(&bare_u64).is_err());
1483        assert!(parse_fulfill_event_value(&bare_u64).is_err());
1484        // A request value is not a fulfill value.
1485        let legacy_req =
1486            "AAAAEAAAAAEAAAACAAAABQAAAAAAAAAFAAAAEgAAAAAAAAAAERERERERERERERERERERERERERERERERERERERERERE=";
1487        assert!(parse_fulfill_event_value(legacy_req).is_err());
1488        // Beta must be exactly 32 bytes.
1489        let short_beta =
1490            unhex("0000001000000001000000020000000500000000000000010000000d00000001ab000000");
1491        assert!(parse_fulfill_event_value(&to_base64(&short_beta)).is_err());
1492    }
1493
1494    #[test]
1495    fn test_decoder_rejects_malformed_xdr() {
1496        let full = unhex(
1497            "0000001000000001000000020000000500000000000000010000000d0000002098c612abed131631\
1498             47239f4323d4973cb68df7302564fc791e17c1aae95a6c9d",
1499        );
1500        assert!(decode_scval_b64(&to_base64(&full)).is_ok());
1501        // Every truncation fails cleanly (no panic, no default value).
1502        for n in 0..full.len() {
1503            assert!(
1504                decode_scval_b64(&to_base64(&full[..n])).is_err(),
1505                "prefix {n}"
1506            );
1507        }
1508        // Trailing bytes.
1509        let mut extra = full.clone();
1510        extra.extend_from_slice(&[0, 0, 0, 0]);
1511        assert!(decode_scval_b64(&to_base64(&extra)).is_err());
1512        // A huge element count can't trigger a huge allocation.
1513        assert!(decode_scval_b64(&to_base64(&unhex("0000001000000001ffffffff"))).is_err());
1514        assert!(decode_scval_b64(&to_base64(&unhex("0000000dffffffff"))).is_err());
1515        // Non-zero XDR padding.
1516        assert!(decode_scval_b64(&to_base64(&unhex("0000000d00000001ab000001"))).is_err());
1517        // Invalid bool, unknown discriminant, not base64.
1518        assert!(decode_scval_b64(&to_base64(&unhex("0000000000000002"))).is_err());
1519        assert!(decode_scval_b64(&to_base64(&unhex("00000063"))).is_err());
1520        assert!(decode_scval_b64("!!!!").is_err());
1521        // Deep nesting: 64 × Vec[..] wrapping.
1522        let mut deep = Vec::new();
1523        for _ in 0..64 {
1524            deep.extend_from_slice(&unhex("000000100000000100000001"));
1525        }
1526        deep.extend_from_slice(&unhex("00000001"));
1527        assert!(decode_scval_b64(&to_base64(&deep)).is_err());
1528        // An absent optional vec decodes to empty.
1529        assert_eq!(
1530            decode_scval_b64(&to_base64(&unhex("0000001000000000"))).unwrap(),
1531            ScVal::Vec(vec![])
1532        );
1533    }
1534
1535    /// Simulation return values, as the RPC returns them in `results[0].xdr`.
1536    #[test]
1537    fn test_decode_simulation_results() {
1538        // Mainnet `is_fulfilled(1)` on CBTCC5QL…SUHU returned "AAAAAAAAAAE=".
1539        assert!(decode_bool_result(Some("AAAAAAAAAAE=".into())).unwrap());
1540        assert!(!decode_bool_result(Some("AAAAAAAAAAA=".into())).unwrap());
1541        // A missing value is an error, not `false`.
1542        assert!(decode_bool_result(None).is_err());
1543        // The old substring check (`contains("AAAAAQ")`) read this u64 as `true`.
1544        let u64_val = to_base64(&encode_scval_u64(1 << 16)); // "AAAABQAAAAAAAQAA"
1545        assert!(u64_val.contains("AAAAAQ"));
1546        assert!(decode_bool_result(Some(u64_val)).is_err());
1547
1548        assert_eq!(
1549            decode_u64_result(Some(to_base64(&encode_scval_u64(889_164))), 7).unwrap(),
1550            889_164
1551        );
1552        assert!(matches!(
1553            decode_u64_result(None, 7),
1554            Err(VrfError::NotFulfilled(7))
1555        ));
1556        assert!(decode_u64_result(Some("AAAAAAAAAAE=".into()), 7).is_err());
1557
1558        let beta: Vec<u8> = (0u8..32).collect();
1559        assert_eq!(
1560            decode_beta_result(Some(to_base64(&encode_scval_bytes(&beta))), 1)
1561                .unwrap()
1562                .to_vec(),
1563            beta
1564        );
1565        assert!(decode_beta_result(Some(to_base64(&encode_scval_bytes(&beta[..31]))), 1).is_err());
1566    }
1567
1568    #[test]
1569    fn test_base32_decode() {
1570        // "AAAA" in base32 = [0, 0, 0] (approximately)
1571        let result = base32_decode("ME");
1572        assert!(result.is_ok());
1573        assert_eq!(result.unwrap(), vec![0x61]); // 'a'
1574    }
1575
1576    #[test]
1577    fn test_to_hex() {
1578        assert_eq!(to_hex(&[0xDE, 0xAD, 0xBE, 0xEF]), "deadbeef");
1579    }
1580
1581    #[test]
1582    fn test_to_base64() {
1583        assert_eq!(to_base64(b"Hello"), "SGVsbG8=");
1584    }
1585
1586    /// StrKey encoding must match the canonical SEP-0023 vector.
1587    /// This is the published example: an all-zero-ish ed25519 key whose G-address
1588    /// is widely used in Stellar test fixtures.
1589    #[test]
1590    fn test_strkey_encode_ed25519_known_vector() {
1591        // SEP-0023 test vector.
1592        let raw: [u8; 32] = [
1593            0x6d, 0xb3, 0x7d, 0x0d, 0xa1, 0x5a, 0x1a, 0x1e, 0x7c, 0x1a, 0x1a, 0x45, 0x9a, 0x3f,
1594            0x63, 0x19, 0x0b, 0x34, 0x63, 0x0c, 0x1e, 0x1a, 0x1e, 0x1a, 0x1e, 0x1a, 0x1e, 0x1a,
1595            0x1e, 0x1a, 0x1e, 0x1a,
1596        ];
1597        let encoded = strkey_encode_ed25519(&raw);
1598
1599        // Shape checks that the old `format!("G{hex}")` could never satisfy.
1600        assert!(encoded.starts_with('G'), "account StrKey must start with G");
1601        assert_eq!(encoded.len(), 56, "StrKey addresses are 56 characters");
1602        assert!(
1603            encoded
1604                .chars()
1605                .all(|c| c.is_ascii_uppercase() || ('2'..='7').contains(&c)),
1606            "must use the RFC4648 base32 alphabet, got {encoded}"
1607        );
1608
1609        // Round-trip through the decoder: payload must survive unchanged.
1610        let decoded = base32_decode(&encoded).expect("must decode");
1611        assert_eq!(&decoded[1..33], &raw[..], "payload must round-trip");
1612    }
1613
1614    /// Contract addresses must round-trip through encode -> decode.
1615    #[test]
1616    fn test_strkey_contract_round_trip() {
1617        let hash: [u8; 32] = [7u8; 32];
1618        let encoded = strkey_encode_contract(&hash);
1619        assert!(
1620            encoded.starts_with('C'),
1621            "contract StrKey must start with C"
1622        );
1623        assert_eq!(encoded.len(), 56);
1624        let back = strkey_decode_contract(&encoded).expect("must decode");
1625        assert_eq!(back, hash);
1626    }
1627
1628    /// CRC16-XModem reference vector: "123456789" -> 0x31C3.
1629    #[test]
1630    fn test_crc16_xmodem_known_vector() {
1631        assert_eq!(crc16_xmodem(b"123456789"), 0x31C3);
1632    }
1633
1634    /// The 128-bit reduction must stay in range and be deterministic, including
1635    /// for the modulus that was the worst case for the old 64-bit modulo.
1636    #[test]
1637    fn test_derive_random_from_beta_range_and_determinism() {
1638        let beta = [0xABu8; 32];
1639
1640        for (min, max) in [
1641            (1u64, 6u64),
1642            (1, 100),
1643            (0, u64::MAX / 2),
1644            (5, 5 + (1 << 62)),
1645        ] {
1646            let a = derive_random_from_beta(&beta, min, max).unwrap();
1647            let b = derive_random_from_beta(&beta, min, max).unwrap();
1648            assert_eq!(a, b, "must be deterministic");
1649            assert!(a >= min && a <= max, "{a} outside [{min}, {max}]");
1650        }
1651
1652        // Needs 16 bytes now, not 8 — short input must be rejected rather than
1653        // silently producing a biased value.
1654        assert!(derive_random_from_beta(&[0u8; 8], 1, 10).is_err());
1655        assert!(derive_random_from_beta(&beta, 10, 10).is_err());
1656    }
1657
1658    /// Regression: `max - min + 1` overflowed u64 for the full range, which
1659    /// panics in debug builds and wraps to a modulus of 0 in release builds.
1660    #[test]
1661    fn test_derive_random_from_beta_full_u64_range() {
1662        // The whole domain must be reachable, including both ends.
1663        let lo = derive_random_from_beta(&[0x00u8; 16], 0, u64::MAX).unwrap();
1664        let hi = derive_random_from_beta(&[0xFFu8; 16], 0, u64::MAX).unwrap();
1665        assert_eq!(lo, 0);
1666        assert_eq!(hi, u64::MAX, "2^128-1 mod 2^64 = 2^64-1");
1667
1668        // Near-full ranges at either edge stay in bounds.
1669        let beta = [0xABu8; 32];
1670        for (min, max) in [
1671            (1u64, u64::MAX),
1672            (0, u64::MAX - 1),
1673            (u64::MAX - 1, u64::MAX),
1674        ] {
1675            let v = derive_random_from_beta(&beta, min, max).unwrap();
1676            assert!(v >= min && v <= max, "{v} outside [{min}, {max}]");
1677        }
1678    }
1679
1680    /// The on-chain span sent to `derive_random_in_range` must never overflow.
1681    #[test]
1682    fn test_inclusive_span_boundaries() {
1683        assert_eq!(inclusive_span(1, 100).unwrap(), 100);
1684        assert_eq!(inclusive_span(7, 7).unwrap(), 1);
1685        assert_eq!(inclusive_span(1, u64::MAX).unwrap(), u64::MAX);
1686        assert_eq!(inclusive_span(0, u64::MAX - 1).unwrap(), u64::MAX);
1687        // The one range the contract's exclusive u64 bound cannot express.
1688        let err = inclusive_span(0, u64::MAX).unwrap_err().to_string();
1689        assert!(err.contains("2^64"), "unexpected error: {err}");
1690        assert!(inclusive_span(10, 9).is_err());
1691    }
1692
1693    #[tokio::test]
1694    async fn test_client_creation() {
1695        let client = VrfClient::new(VrfClientConfig {
1696            contract_id: "CD5K4NNYNG3ZFCET24F3SL6MSYYRD5I2BSWW5K3LFQVIKYHRY2ICVIVX".into(),
1697            network: Network::Testnet,
1698            secret_key: String::new(),
1699        });
1700        // Client creation should not fail
1701        assert_eq!(
1702            client.config.contract_id,
1703            "CD5K4NNYNG3ZFCET24F3SL6MSYYRD5I2BSWW5K3LFQVIKYHRY2ICVIVX"
1704        );
1705    }
1706
1707    #[test]
1708    fn test_strkey_decode_contract() {
1709        // Valid contract ID should decode to 32 bytes
1710        let result =
1711            strkey_decode_contract("CD5K4NNYNG3ZFCET24F3SL6MSYYRD5I2BSWW5K3LFQVIKYHRY2ICVIVX");
1712        assert!(result.is_ok());
1713        assert_eq!(result.unwrap().len(), 32);
1714    }
1715
1716    #[test]
1717    fn test_strkey_decode_contract_rejects_bad_ids() {
1718        let good = "CAW6KECQMHRTX2GS3JVHWBMOB5JNNOHNOCE635RQS4SWJ72YF56EUPRX";
1719        assert!(strkey_decode_contract(good).is_ok());
1720
1721        // One changed character → checksum mismatch.
1722        let mut typo = good.to_string();
1723        typo.replace_range(10..11, if &good[10..11] == "A" { "B" } else { "A" });
1724        assert!(
1725            strkey_decode_contract(&typo).is_err(),
1726            "typo must fail the CRC"
1727        );
1728
1729        // Right length, wrong version byte: an account (G...) address.
1730        let account = strkey_encode_ed25519(&[7u8; 32]);
1731        assert_eq!(account.len(), 56);
1732        assert!(
1733            strkey_decode_contract(&account).is_err(),
1734            "G... must be rejected"
1735        );
1736
1737        // Wrong lengths.
1738        assert!(strkey_decode_contract(&good[..55]).is_err());
1739        assert!(strkey_decode_contract(&format!("{good}A")).is_err());
1740        assert!(strkey_decode_contract("").is_err());
1741
1742        // Invalid base32 characters.
1743        let lower = good.to_lowercase();
1744        assert!(strkey_decode_contract(&lower).is_err());
1745    }
1746}