From d10b253f6c5f99921d099e6fbbb2677252c45b45 Mon Sep 17 00:00:00 2001 From: nuvoraxis <358196463+nuvoraxis@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:29:52 +0000 Subject: [PATCH] feat(contracts): implement verifiable puzzle seed beacon (#404) --- Cargo.toml | 1 + contracts/seed_beacon/Cargo.toml | 13 ++ contracts/seed_beacon/README.md | 16 ++ contracts/seed_beacon/src/lib.rs | 250 ++++++++++++++++++++++++++++++ contracts/seed_beacon/src/test.rs | 116 ++++++++++++++ 5 files changed, 396 insertions(+) create mode 100644 contracts/seed_beacon/Cargo.toml create mode 100644 contracts/seed_beacon/README.md create mode 100644 contracts/seed_beacon/src/lib.rs create mode 100644 contracts/seed_beacon/src/test.rs diff --git a/Cargo.toml b/Cargo.toml index c6c06d9..bf74168 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "contracts/bridge", "contracts/crafting", "contracts/mystery_box", + "contracts/seed_beacon", "contracts/daily_rewards", "contracts/streak_counter", "contracts/energy", diff --git a/contracts/seed_beacon/Cargo.toml b/contracts/seed_beacon/Cargo.toml new file mode 100644 index 0000000..f16dde3 --- /dev/null +++ b/contracts/seed_beacon/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "seed-beacon" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +soroban-sdk = "21.7.7" + +[dev-dependencies] +soroban-sdk = { version = "21.7.7", features = ["testutils"] } diff --git a/contracts/seed_beacon/README.md b/contracts/seed_beacon/README.md new file mode 100644 index 0000000..1833d4e --- /dev/null +++ b/contracts/seed_beacon/README.md @@ -0,0 +1,16 @@ +# Verifiable Puzzle Seed Beacon Contract + +A modular Soroban smart contract for the Quest economy that implements unpredictable and publicly verifiable random seed generation for puzzle rounds: + +1. **Commit Phase:** + - Contract admin commits to a specific future ledger sequence and entropy salt. + - Target ledger sequence must be strictly greater than current ledger sequence (`TargetLedgerMustBeInFuture`). + - Seeds cannot be known in advance by players or malicious actors. + +2. **Reveal Phase:** + - Seed derivation is unlocked once the committed ledger sequence is reached (`CommittedLedgerNotReached` error if called early). + - Seed is deterministically derived: `sha256(round_id || committed_ledger_hash || entropy_salt)`. + - Exactly one seed is produced per round (idempotent reveals return existing seed). + +3. **Public Verification:** + - `verify_seed` function allows any player or third-party observer to independently verify that a puzzle was generated from the published rule and ledger hash. diff --git a/contracts/seed_beacon/src/lib.rs b/contracts/seed_beacon/src/lib.rs new file mode 100644 index 0000000..535fb53 --- /dev/null +++ b/contracts/seed_beacon/src/lib.rs @@ -0,0 +1,250 @@ +#![no_std] + +use soroban_sdk::{ + contract, contracterror, contractimpl, contractmeta, contracttype, symbol_short, + Address, Bytes, BytesN, Env, Symbol, +}; + +#[cfg(test)] +mod test; + +// Contract metadata +contractmeta!( + key = "Description", + val = "Verifiable Puzzle Seed Beacon contract for committing and revealing unpredictable puzzle round seeds" +); + +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RoundCommitment { + pub round_id: u64, + pub target_ledger_sequence: u32, + pub entropy_salt: BytesN<32>, + pub is_revealed: bool, + pub created_at_ledger: u32, +} + +#[contracterror] +#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] +#[repr(u32)] +pub enum BeaconError { + NotAuthorized = 1, + RoundNotFound = 2, + RoundAlreadyExists = 3, + TargetLedgerMustBeInFuture = 4, + CommittedLedgerNotReached = 5, + SeedNotRevealedYet = 6, + AdminNotFound = 7, + AlreadyInitialized = 8, +} + +// Storage keys +const ADMIN: Symbol = symbol_short!("ADMIN"); +const ROUND: Symbol = symbol_short!("ROUND"); +const SEED: Symbol = symbol_short!("SEED"); + +#[contract] +pub struct SeedBeaconContract; + +#[contractimpl] +impl SeedBeaconContract { + /// Initialize the contract with an admin address + pub fn initialize(env: Env, admin: Address) -> Result<(), BeaconError> { + admin.require_auth(); + if env.storage().instance().has(&ADMIN) { + return Err(BeaconError::AlreadyInitialized); + } + env.storage().instance().set(&ADMIN, &admin); + Ok(()) + } + + /// Commit to a future ledger sequence and salt for a puzzle round. + /// Admin only. Target ledger sequence must be strictly in the future. + pub fn commit_round( + env: Env, + admin: Address, + round_id: u64, + target_ledger_sequence: u32, + entropy_salt: BytesN<32>, + ) -> Result<(), BeaconError> { + Self::require_admin(&env, &admin)?; + + let current_ledger = env.ledger().sequence(); + if target_ledger_sequence <= current_ledger { + return Err(BeaconError::TargetLedgerMustBeInFuture); + } + + let key = (ROUND, round_id); + if env.storage().persistent().has(&key) { + return Err(BeaconError::RoundAlreadyExists); + } + + let commitment = RoundCommitment { + round_id, + target_ledger_sequence, + entropy_salt: entropy_salt.clone(), + is_revealed: false, + created_at_ledger: current_ledger, + }; + + env.storage().persistent().set(&key, &commitment); + + // Emit commitment event: (commit, round_id) -> (target_ledger, salt) + env.events().publish( + (symbol_short!("commit"), round_id), + (target_ledger_sequence, entropy_salt), + ); + + Ok(()) + } + + /// Reveal the deterministic seed once the committed ledger sequence has been reached. + /// Derives seed = sha256(round_id || committed_ledger_hash || entropy_salt). + /// Idempotent: once revealed, returns the existing single seed. + pub fn reveal_seed( + env: Env, + round_id: u64, + committed_ledger_hash: BytesN<32>, + ) -> Result, BeaconError> { + let key = (ROUND, round_id); + let mut round: RoundCommitment = match env.storage().persistent().get(&key) { + Some(r) => r, + None => return Err(BeaconError::RoundNotFound), + }; + + let seed_key = (SEED, round_id); + if round.is_revealed { + let existing_seed: BytesN<32> = env.storage().persistent().get(&seed_key).unwrap(); + return Ok(existing_seed); + } + + let current_ledger = env.ledger().sequence(); + if current_ledger < round.target_ledger_sequence { + return Err(BeaconError::CommittedLedgerNotReached); + } + + // Derive seed deterministically + let derived_seed = Self::compute_seed_hash( + &env, + round_id, + &committed_ledger_hash, + &round.entropy_salt, + ); + + env.storage().persistent().set(&seed_key, &derived_seed); + round.is_revealed = true; + env.storage().persistent().set(&key, &round); + + // Emit reveal event: (reveal, round_id) -> (derived_seed) + env.events().publish( + (symbol_short!("reveal"), round_id), + derived_seed.clone(), + ); + + Ok(derived_seed) + } + + /// Public verification function: anyone can verify that a candidate seed was + /// faithfully generated from the published round parameters and ledger hash. + pub fn verify_seed( + env: Env, + round_id: u64, + committed_ledger_hash: BytesN<32>, + candidate_seed: BytesN<32>, + ) -> Result { + let key = (ROUND, round_id); + let round: RoundCommitment = match env.storage().persistent().get(&key) { + Some(r) => r, + None => return Err(BeaconError::RoundNotFound), + }; + + let expected_seed = Self::compute_seed_hash( + &env, + round_id, + &committed_ledger_hash, + &round.entropy_salt, + ); + + Ok(candidate_seed == expected_seed) + } + + /// Retrieve round commitment details + pub fn get_round(env: Env, round_id: u64) -> Option { + let key = (ROUND, round_id); + env.storage().persistent().get(&key) + } + + /// Retrieve revealed seed for a round (fails if not revealed yet) + pub fn get_seed(env: Env, round_id: u64) -> Result, BeaconError> { + let key = (ROUND, round_id); + let round: RoundCommitment = match env.storage().persistent().get(&key) { + Some(r) => r, + None => return Err(BeaconError::RoundNotFound), + }; + + if !round.is_revealed { + return Err(BeaconError::SeedNotRevealedYet); + } + + let seed_key = (SEED, round_id); + match env.storage().persistent().get(&seed_key) { + Some(s) => Ok(s), + None => Err(BeaconError::SeedNotRevealedYet), + } + } + + /// Check if a round seed has been revealed + pub fn is_revealed(env: Env, round_id: u64) -> bool { + let key = (ROUND, round_id); + let round: Option = env.storage().persistent().get(&key); + match round { + Some(r) => r.is_revealed, + None => false, + } + } + + /// Transfer contract admin role. Admin only. + pub fn transfer_admin( + env: Env, + current_admin: Address, + new_admin: Address, + ) -> Result<(), BeaconError> { + Self::require_admin(&env, ¤t_admin)?; + new_admin.require_auth(); + + env.storage().instance().set(&ADMIN, &new_admin); + Ok(()) + } + + /// Get current admin + pub fn get_admin(env: Env) -> Option
{ + env.storage().instance().get(&ADMIN) + } + + // Helper functions + fn require_admin(env: &Env, admin: &Address) -> Result<(), BeaconError> { + admin.require_auth(); + + let stored_admin: Option
= env.storage().instance().get(&ADMIN); + + match stored_admin { + Some(stored) if stored == *admin => Ok(()), + Some(_) => Err(BeaconError::NotAuthorized), + None => Err(BeaconError::AdminNotFound), + } + } + + fn compute_seed_hash( + env: &Env, + round_id: u64, + ledger_hash: &BytesN<32>, + entropy_salt: &BytesN<32>, + ) -> BytesN<32> { + let mut preimage = Bytes::new(env); + preimage.append(&Bytes::from_array(env, &round_id.to_be_bytes())); + preimage.append(&Bytes::from_array(env, &ledger_hash.to_array())); + preimage.append(&Bytes::from_array(env, &entropy_salt.to_array())); + + env.crypto().sha256(&preimage).into() + } +} diff --git a/contracts/seed_beacon/src/test.rs b/contracts/seed_beacon/src/test.rs new file mode 100644 index 0000000..2175d66 --- /dev/null +++ b/contracts/seed_beacon/src/test.rs @@ -0,0 +1,116 @@ +use super::*; +use soroban_sdk::{ + testutils::{Address as _, Ledger}, + Env, +}; + +struct TestFixture { + env: Env, + admin: Address, + player: Address, +} + +impl TestFixture { + fn setup() -> (Self, SeedBeaconContractClient<'static>) { + let env = Env::default(); + env.mock_all_auths(); + + let admin = Address::generate(&env); + let player = Address::generate(&env); + + let contract_id = env.register_contract(None, SeedBeaconContract); + let client = SeedBeaconContractClient::new(&env, &contract_id); + + client.initialize(&admin); + + let fixture = Self { + env, + admin, + player, + }; + + (fixture, client) + } +} + +#[test] +fn test_commit_requires_future_ledger_and_admin() { + let (f, client) = TestFixture::setup(); + + let salt = BytesN::from_array(&f.env, &[42u8; 32]); + let current_seq = f.env.ledger().sequence(); + + // Past or present ledger must be rejected + let res_past = client.try_commit_round(&f.admin, &1, ¤t_seq, &salt); + assert_eq!(res_past, Err(Ok(BeaconError::TargetLedgerMustBeInFuture))); + + // Non-admin cannot commit + let res_unauth = client.try_commit_round(&f.player, &1, &(current_seq + 10), &salt); + assert_eq!(res_unauth, Err(Ok(BeaconError::NotAuthorized))); + + // Valid commit to future ledger (current + 10) + client.commit_round(&f.admin, &1, &(current_seq + 10), &salt); + + let round = client.get_round(&1).unwrap(); + assert_eq!(round.target_ledger_sequence, current_seq + 10); + assert_eq!(round.is_revealed, false); + assert_eq!(client.is_revealed(&1), false); + + // Duplicate round commit fails + let res_dup = client.try_commit_round(&f.admin, &1, &(current_seq + 20), &salt); + assert_eq!(res_dup, Err(Ok(BeaconError::RoundAlreadyExists))); +} + +#[test] +fn test_seed_cannot_be_revealed_before_target_ledger() { + let (f, client) = TestFixture::setup(); + + let salt = BytesN::from_array(&f.env, &[7u8; 32]); + let ledger_hash = BytesN::from_array(&f.env, &[99u8; 32]); + let current_seq = f.env.ledger().sequence(); + + // Commit to target ledger 50 + client.commit_round(&f.admin, &10, &(current_seq + 50), &salt); + + // Trying to get seed before reveal fails with SeedNotRevealedYet + let res_get = client.try_get_seed(&10); + assert_eq!(res_get, Err(Ok(BeaconError::SeedNotRevealedYet))); + + // Trying to reveal before reaching ledger 50 fails with CommittedLedgerNotReached + let res_reveal = client.try_reveal_seed(&10, &ledger_hash); + assert_eq!(res_reveal, Err(Ok(BeaconError::CommittedLedgerNotReached))); + assert_eq!(client.is_revealed(&10), false); +} + +#[test] +fn test_reveal_seed_and_deterministic_verification() { + let (f, client) = TestFixture::setup(); + + let salt = BytesN::from_array(&f.env, &[15u8; 32]); + let ledger_hash = BytesN::from_array(&f.env, &[88u8; 32]); + let current_seq = f.env.ledger().sequence(); + let target_seq = current_seq + 25; + + client.commit_round(&f.admin, &20, &target_seq, &salt); + + // Advance ledger sequence past target + f.env.ledger().with_mut(|l| l.sequence_number = target_seq); + + // Reveal seed + let seed = client.reveal_seed(&20, &ledger_hash); + assert_eq!(client.is_revealed(&20), true); + assert_eq!(client.get_seed(&20), seed); + + // Third party can verify seed + let is_valid = client.verify_seed(&20, &ledger_hash, &seed); + assert_eq!(is_valid, true); + + // Altered seed fails verification + let wrong_seed = BytesN::from_array(&f.env, &[0u8; 32]); + let is_valid_wrong = client.verify_seed(&20, &ledger_hash, &wrong_seed); + assert_eq!(is_valid_wrong, false); + + // Idempotent reveal: exactly one seed per round + let seed_again = client.reveal_seed(&20, &ledger_hash); + assert_eq!(seed, seed_again); +}