diff --git a/contracts/Cargo.lock b/contracts/Cargo.lock index 9404948b..ade27040 100644 --- a/contracts/Cargo.lock +++ b/contracts/Cargo.lock @@ -456,6 +456,7 @@ dependencies = [ name = "cross-chain-client" version = "0.1.0" dependencies = [ + "ed25519-dalek", "soroban-sdk", ] @@ -664,6 +665,7 @@ dependencies = [ name = "did_registry" version = "0.0.0" dependencies = [ + "ed25519-dalek", "soroban-sdk", ] diff --git a/contracts/continuous_bonding_curve/src/lib.rs b/contracts/continuous_bonding_curve/src/lib.rs index f0f750bf..72f1160f 100644 --- a/contracts/continuous_bonding_curve/src/lib.rs +++ b/contracts/continuous_bonding_curve/src/lib.rs @@ -100,16 +100,23 @@ pub mod fp18 { /// Checked multiply of two 18-decimal FP values. #[inline] pub fn mul(a: i128, b: i128) -> Option { - a.checked_mul(b)?.checked_div(SCALE18) + let rounding = if (a < 0) ^ (b < 0) { + math::Rounding::Up + } else { + math::Rounding::Down + }; + math::checked_mul_div_signed(a, b, SCALE18, rounding) } /// Checked divide of two 18-decimal FP values. #[inline] pub fn div(a: i128, b: i128) -> Option { - if b == 0 { - return None; - } - a.checked_mul(SCALE18)?.checked_div(b) + let rounding = if (a < 0) ^ (b < 0) { + math::Rounding::Up + } else { + math::Rounding::Down + }; + math::checked_mul_div_signed(a, SCALE18, b, rounding) } } @@ -636,6 +643,12 @@ mod tests { assert_eq!(pricing::curve_payout(5, 2, 2 * FP, FP), Some(12)); } + #[test] + fn fp18_helpers_accept_full_width_intermediates() { + assert_eq!(fp18::mul(i128::MAX, fp18::SCALE18), Some(i128::MAX)); + assert_eq!(fp18::div(i128::MAX, i128::MAX), Some(fp18::SCALE18)); + } + #[test] fn buys_mint_and_sells_burn_curve_tokens() { let (env, _admin, buyer, id, _reserve_token, curve_token) = setup_with_tokens(0); diff --git a/contracts/continuous_bonding_curve/src/math.rs b/contracts/continuous_bonding_curve/src/math.rs index 045c6354..1500420f 100644 --- a/contracts/continuous_bonding_curve/src/math.rs +++ b/contracts/continuous_bonding_curve/src/math.rs @@ -2,7 +2,7 @@ //! //! Provides a 128-bit fixed-point representation with 18 decimal places of precision (`WAD = 10^18`). //! Implements deterministic rounding modes (`Down` vs `Up`), full 256-bit intermediate arithmetic for -//! `mul_div`, `wad_mul`, `wad_div`, `sqrt`, and `pow`, with clean overflow and division-by-zero detection. +//! multiplication/division, and checked Taylor-series `ln`, `exp`, and fractional powers. pub const WAD: u128 = 1_000_000_000_000_000_000; // 10^18 pub const HALF_WAD: u128 = WAD / 2; @@ -154,6 +154,164 @@ pub fn wad_div(a: u128, b: u128, rounding: Rounding) -> u128 { mul_div(a, WAD, b, rounding) } +/// Computes `(a * b) / denominator` with full-width intermediates. +/// Returns `None` for division by zero or if the result exceeds `u128`. +pub fn checked_mul_div(a: u128, b: u128, denominator: u128, rounding: Rounding) -> Option { + if denominator == 0 { + return None; + } + + let (quotient, remainder) = div_rem_u256(mul_u128(a, b), denominator); + if quotient.hi > 0 { + return None; + } + + let mut result = quotient.lo; + if rounding == Rounding::Up && remainder > 0 { + result = result.checked_add(1)?; + } + Some(result) +} + +/// Computes signed `(a * b) / denominator` with full-width intermediates. +/// `Down` rounds toward negative infinity and `Up` toward positive infinity. +pub fn checked_mul_div_signed( + a: i128, + b: i128, + denominator: i128, + rounding: Rounding, +) -> Option { + if denominator == 0 { + return None; + } + + let negative = (a < 0) ^ (b < 0) ^ (denominator < 0); + let (quotient, remainder) = div_rem_u256( + mul_u128(a.unsigned_abs(), b.unsigned_abs()), + denominator.unsigned_abs(), + ); + if quotient.hi > 0 { + return None; + } + + let round_away_from_zero = remainder > 0 + && ((!negative && rounding == Rounding::Up) || (negative && rounding == Rounding::Down)); + let magnitude = if round_away_from_zero { + quotient.lo.checked_add(1)? + } else { + quotient.lo + }; + + if negative { + let min_magnitude = (i128::MAX as u128).checked_add(1)?; + if magnitude > min_magnitude { + return None; + } + if magnitude == min_magnitude { + Some(i128::MIN) + } else { + Some(-(magnitude as i128)) + } + } else { + i128::try_from(magnitude).ok() + } +} + +/// Computes the natural logarithm of a positive 18-decimal fixed-point value. +/// +/// The atanh series is evaluated after reducing the input to `[0.5, 2]`, +/// where it converges quickly. The result is in 18-decimal fixed-point units. +pub fn ln_wad(value: i128) -> Option { + const LN_2: i128 = 693_147_180_559_945_309; + const MAX_TERMS: u32 = 64; + + if value <= 0 { + return None; + } + + let mut normalized = value; + let mut powers_of_two = 0i128; + while normalized > 2 * WAD as i128 { + normalized /= 2; + powers_of_two = powers_of_two.checked_add(1)?; + } + while normalized < WAD as i128 / 2 { + normalized = normalized.checked_mul(2)?; + powers_of_two = powers_of_two.checked_sub(1)?; + } + + let wad = WAD as i128; + let z = normalized + .checked_sub(wad)? + .checked_mul(wad)? + .checked_div(normalized.checked_add(wad)?)?; + let z_squared = z.checked_mul(z)?.checked_div(wad)?; + let mut term = z; + let mut sum = z; + + for index in 1..=MAX_TERMS { + term = term.checked_mul(z_squared)?.checked_div(wad)?; + let divisor = (index as i128).checked_mul(2)?.checked_add(1)?; + let contribution = term / divisor; + if contribution == 0 { + break; + } + sum = sum.checked_add(contribution)?; + } + + sum.checked_mul(2)? + .checked_add(powers_of_two.checked_mul(LN_2)?) +} + +/// Computes `e^value` for an 18-decimal fixed-point exponent. +/// +/// Range reduction bounds the Taylor series argument to `[-0.5, 0.5]`. +/// Returns `None` if the result cannot be represented. +pub fn exp_wad(value: i128) -> Option { + const MAX_TERMS: u32 = 64; + + let wad = WAD as i128; + let mut reduced = value; + let mut squarings = 0u32; + while reduced > wad / 2 || reduced < -(wad / 2) { + reduced /= 2; + squarings = squarings.checked_add(1)?; + } + + let mut term = wad; + let mut sum = wad; + for index in 1..=MAX_TERMS { + term = term + .checked_mul(reduced)? + .checked_div(wad)? + .checked_div(index as i128)?; + if term == 0 { + break; + } + sum = sum.checked_add(term)?; + } + + for _ in 0..squarings { + sum = sum.checked_mul(sum)?.checked_div(wad)?; + } + Some(sum) +} + +/// Computes a fractional 18-decimal fixed-point power using `exp(ln(base)*exponent)`. +pub fn wad_pow_fractional(base: i128, exponent: i128, rounding: Rounding) -> Option { + let wad = WAD as i128; + if exponent == 0 { + return Some(wad); + } + if base == 0 { + return if exponent > 0 { Some(0) } else { None }; + } + + let log_base = ln_wad(base)?; + let power = checked_mul_div_signed(log_base, exponent, wad, rounding)?; + exp_wad(power) +} + /// Computes integer square root `floor(sqrt(x))` using the Babylonian method. pub fn sqrt(x: u128) -> u128 { if x == 0 { @@ -351,6 +509,48 @@ mod tests { assert_eq!(one.mul(one, Rounding::Down), one); } + #[test] + fn checked_mul_div_supports_full_width_intermediates_and_signed_rounding() { + assert_eq!( + checked_mul_div(u128::MAX, WAD, WAD, Rounding::Down), + Some(u128::MAX) + ); + assert_eq!( + checked_mul_div_signed(i128::MAX, 2, 2, Rounding::Down), + Some(i128::MAX) + ); + assert_eq!( + checked_mul_div_signed(i128::MIN, 1, 1, Rounding::Down), + Some(i128::MIN) + ); + assert_eq!(checked_mul_div_signed(-10, 1, 3, Rounding::Down), Some(-4)); + assert_eq!(checked_mul_div_signed(-10, 1, 3, Rounding::Up), Some(-3)); + assert_eq!(checked_mul_div(1, 1, 0, Rounding::Down), None); + assert_eq!(checked_mul_div_signed(1, 1, 0, Rounding::Down), None); + } + + #[test] + fn taylor_log_exp_and_fractional_power_match_reference_values() { + let wad = WAD as i128; + let ln_two_reference = 693_147_180_559_945_309i128; + let e_reference = 2_718_281_828_459_045_235i128; + + assert_eq!(ln_wad(wad), Some(0)); + assert!(ln_wad(2 * wad).unwrap().abs_diff(ln_two_reference) < 100); + assert_eq!(exp_wad(0), Some(wad)); + assert!(exp_wad(wad).unwrap().abs_diff(e_reference) < 1_000); + assert!(exp_wad(ln_two_reference).unwrap().abs_diff(2 * wad) < 100); + assert!( + wad_pow_fractional(4 * wad, wad / 2, Rounding::Down) + .unwrap() + .abs_diff(2 * wad) + < 100 + ); + assert_eq!(ln_wad(0), None); + assert_eq!(exp_wad(100 * wad), None); + assert_eq!(wad_pow_fractional(0, -wad, Rounding::Down), None); + } + #[test] fn test_wad_sqrt() { // sqrt(1) == 1 diff --git a/contracts/cross_chain_client/Cargo.toml b/contracts/cross_chain_client/Cargo.toml index f5e78a75..ca754b96 100644 --- a/contracts/cross_chain_client/Cargo.toml +++ b/contracts/cross_chain_client/Cargo.toml @@ -11,3 +11,4 @@ soroban-sdk = "28.0.0" [dev-dependencies] soroban-sdk = { version = "28.0.0", features = ["testutils"] } +ed25519-dalek = { version = "2", default-features = false, features = ["std"] } diff --git a/contracts/cross_chain_client/src/lib.rs b/contracts/cross_chain_client/src/lib.rs index ef4f2c37..0dde6400 100644 --- a/contracts/cross_chain_client/src/lib.rs +++ b/contracts/cross_chain_client/src/lib.rs @@ -78,7 +78,17 @@ pub enum ClientKey { Validator(BytesN<32>), /// Accepted bridge header by chain and block number. Header(ChainId, u64), - /// Used transaction root or hash for replay protection. + /// Accepted transaction roots by source chain. + TxRoot(ChainId, BytesN<32>), + /// Most recently accepted block number and hash for each source chain. + ChainHead(ChainId), + /// Number of active validators used to derive the quorum. + ValidatorCount, + /// Used transaction identifier scoped to its source chain. + ProcessedSourceTx(ChainId, BytesN<32>), + /// Unlock record scoped to its source chain. + SourceUnlock(ChainId, BytesN<32>), + /// Legacy replay storage retained for API compatibility. ProcessedTx(BytesN<32>), /// Persisted unlock record keyed by tx_hash. Unlock(BytesN<32>), @@ -107,12 +117,9 @@ pub enum ClientError { InvalidProof = 11, ReplayDetected = 12, EmptyProof = 13, - InvalidRlp = 14, - HeaderNotConfirmed = 15, - NonMonotonicReceiptIndex = 16, - InvalidReceipt = 17, - SourceBridgeNotConfigured = 18, - InvalidLockEvent = 19, + InvalidQuorum = 14, + InvalidTrieProof = 15, + InvalidTransaction = 16, } #[contract] @@ -170,6 +177,14 @@ impl CrossChainClient { pub fn register_validator(env: Env, caller: Address, validator: BytesN<32>) { caller.require_auth(); Self::assert_admin(&env, &caller); + if !Self::is_validator(env.clone(), validator.clone()) { + let count = Self::validator_count(env.clone()) + .checked_add(1) + .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidQuorum)); + env.storage() + .instance() + .set(&ClientKey::ValidatorCount, &count); + } env.storage() .persistent() .set(&ClientKey::Validator(validator.clone()), &true); @@ -181,6 +196,12 @@ impl CrossChainClient { pub fn unregister_validator(env: Env, caller: Address, validator: BytesN<32>) { caller.require_auth(); Self::assert_admin(&env, &caller); + if Self::is_validator(env.clone(), validator.clone()) { + let count = Self::validator_count(env.clone()).saturating_sub(1); + env.storage() + .instance() + .set(&ClientKey::ValidatorCount, &count); + } env.storage() .persistent() .set(&ClientKey::Validator(validator.clone()), &false); @@ -200,10 +221,14 @@ impl CrossChainClient { } pub fn get_threshold(env: Env) -> u32 { - env.storage() + let configured: u32 = env + .storage() .instance() .get(&ClientKey::Threshold) - .unwrap_or(1u32) + .unwrap_or(1u32); + let count = Self::validator_count(env); + let quorum = ((count as u64 * 2) / 3 + 1) as u32; + configured.max(quorum) } pub fn is_validator(env: Env, validator: BytesN<32>) -> bool { @@ -213,7 +238,7 @@ impl CrossChainClient { .unwrap_or(false) } - /// Validate consensus over a block hash using the configured validator set. + /// Validate distinct active-validator signatures over a signing digest. pub fn verify_block_header( env: Env, block_hash: BytesN<32>, @@ -229,8 +254,13 @@ impl CrossChainClient { let threshold: u32 = Self::get_threshold(env.clone()); let mut valid_sigs: u32 = 0; + let mut seen: Vec> = Vec::new(&env); for i in 0..signers.len() { let signer = signers.get(i).unwrap(); + if seen.contains(&signer) { + return false; + } + seen.push_back(signer.clone()); if !Self::is_validator(env.clone(), signer.clone()) { continue; } @@ -253,7 +283,30 @@ impl CrossChainClient { valid_sigs >= threshold } - /// Submit a block header and validate that enough validators signed the block hash. + /// Hash the complete header fields validators must authorize. + pub fn block_header_signing_hash( + env: Env, + chain_id: ChainId, + block_number: u64, + block_hash: BytesN<32>, + parent_hash: BytesN<32>, + state_root: BytesN<32>, + tx_root: BytesN<32>, + timestamp: u64, + ) -> BytesN<32> { + Self::header_digest( + &env, + chain_id, + block_number, + &block_hash, + &parent_hash, + &state_root, + &tx_root, + timestamp, + ) + } + + /// Accept a linked source-chain header only after quorum signatures. #[allow(clippy::too_many_arguments)] pub fn submit_block_header( env: Env, @@ -270,9 +323,30 @@ impl CrossChainClient { ) -> BytesN<32> { caller.require_auth(); Self::assert_admin(&env, &caller); - if !Self::verify_block_header(env.clone(), block_hash.clone(), signers, signatures) { + let signing_hash = Self::header_digest( + &env, + chain_id, + block_number, + &block_hash, + &parent_hash, + &state_root, + &tx_root, + timestamp, + ); + if timestamp > env.ledger().timestamp() + || !Self::verify_block_header(env.clone(), signing_hash, signers, signatures) + { panic_with_error!(&env, ClientError::InvalidHeader); } + if let Some((head_number, head_hash)) = env + .storage() + .persistent() + .get::)>(&ClientKey::ChainHead(chain_id)) + { + if block_number != head_number.saturating_add(1) || parent_hash != head_hash { + panic_with_error!(&env, ClientError::InvalidHeader); + } + } let header = BridgeHeader { chain_id, @@ -288,6 +362,13 @@ impl CrossChainClient { env.storage() .persistent() .set(&ClientKey::Header(chain_id, block_number), &header); + env.storage() + .persistent() + .set(&ClientKey::TxRoot(chain_id, tx_root.clone()), &true); + env.storage().persistent().set( + &ClientKey::ChainHead(chain_id), + &(block_number, block_hash.clone()), + ); block_hash } @@ -327,181 +408,32 @@ impl CrossChainClient { .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidHeader)) } - /// Verify an RLP-encoded Ethereum header, bind its hash to its roots, and - /// require a contiguous parent link from the previously accepted header. - pub fn submit_evm_header( - env: Env, - caller: Address, - chain_id: ChainId, - header_rlp: Bytes, - signers: Vec>, - signatures: Vec>, - ) -> BytesN<32> { - caller.require_auth(); - Self::assert_admin(&env, &caller); - let (state_root, tx_root, receipts_root, block_number, timestamp) = - rlp::evm_header_fields(&header_rlp) - .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidRlp)); - if block_number == 0 { - panic_with_error!(&env, ClientError::InvalidHeader); - } - let block_hash: BytesN<32> = env.crypto().keccak256(&header_rlp).into(); - if !Self::verify_block_header(env.clone(), block_hash.clone(), signers, signatures) { - panic_with_error!(&env, ClientError::InvalidHeader); - } - let header_item = rlp::decode(&header_rlp, 0) - .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidRlp)); - let parent_hash = rlp::list_item(&header_rlp, header_item, 0) - .and_then(|item| rlp::payload(&header_rlp, item)) - .and_then(|value| BytesN::<32>::try_from(value).ok()) - .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidRlp)); - - if let Some(latest_number) = env - .storage() - .instance() - .get::<_, u64>(&ClientKey::LatestHeader(chain_id)) - { - let expected_number = latest_number - .checked_add(1) - .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidHeader)); - if block_number != expected_number { - panic_with_error!(&env, ClientError::InvalidHeader); - } - let previous = Self::get_header(env.clone(), chain_id, latest_number); - if parent_hash != previous.block_hash { - panic_with_error!(&env, ClientError::InvalidHeader); - } - } - - let header = BridgeHeader { - chain_id, - block_number, - block_hash: block_hash.clone(), - parent_hash, - state_root, - tx_root, - receipts_root: receipts_root.clone(), - rlp_verified: true, - timestamp, - }; - env.storage() - .persistent() - .set(&ClientKey::Header(chain_id, block_number), &header); - env.storage() - .instance() - .set(&ClientKey::LatestHeader(chain_id), &block_number); - env.events().publish( - (symbol_short!("evm_hdr"), chain_id), - (block_number, block_hash.clone(), receipts_root), - ); - block_hash - } - - pub fn get_confirmation_depth(env: Env) -> u32 { + fn validator_count(env: Env) -> u32 { env.storage() .instance() - .get(&ClientKey::ConfirmationDepth) - .unwrap_or(12) - } - - /// Verify an RLP receipt against a finalized Ethereum receipts trie root. - /// For each source chain, receipt transaction indices must increase strictly. - pub fn verify_receipt_proof( - env: Env, - chain_id: ChainId, - block_number: u64, - transaction_index: u64, - receipt: Bytes, - proof_nodes: Vec, - ) -> bool { - Self::verify_receipt_internal( - &env, - chain_id, - block_number, - transaction_index, - &receipt, - &proof_nodes, - false, - ) + .get(&ClientKey::ValidatorCount) + .unwrap_or(0u32) } - /// Verify a finalized source-chain lock event before recording an unlock. - /// Lock event data is ABI-encoded as asset_id[32] || recipient[32] || amount[32]. - pub fn unlock_from_receipt( - env: Env, + fn header_digest( + env: &Env, chain_id: ChainId, block_number: u64, - transaction_index: u64, - tx_hash: BytesN<32>, - receipt: Bytes, - proof_nodes: Vec, - asset_id: BytesN<32>, - recipient: BytesN<32>, - amount: i128, - ) -> bool { - if env - .storage() - .persistent() - .get::(&ClientKey::ProcessedTx(tx_hash.clone())) - .unwrap_or(false) - { - panic_with_error!(&env, ClientError::ReplayDetected); - } - let source_bridge: SourceBridge = env - .storage() - .persistent() - .get(&ClientKey::SourceBridge(chain_id)) - .unwrap_or_else(|| panic_with_error!(&env, ClientError::SourceBridgeNotConfigured)); - if !rlp::receipt_has_lock( - &env, - &receipt, - &source_bridge.address, - &source_bridge.lock_topic, - &asset_id, - &recipient, - amount, - ) { - panic_with_error!(&env, ClientError::InvalidLockEvent); - } - Self::verify_receipt_internal( - &env, - chain_id, - block_number, - transaction_index, - &receipt, - &proof_nodes, - true, - ); - let header = Self::get_header(env.clone(), chain_id, block_number); - let recipient_bytes: Bytes = recipient.into(); - let record = UnlockRecord { - chain_id, - tx_hash: tx_hash.clone(), - asset_id: asset_id.clone(), - recipient: recipient_bytes.clone(), - amount, - block_number, - proof_root: header.receipts_root, - unlocked_at: env.ledger().timestamp(), - }; - env.storage() - .persistent() - .set(&ClientKey::Unlock(tx_hash.clone()), &record); - env.storage() - .persistent() - .set(&ClientKey::ProcessedTx(tx_hash.clone()), &true); - env.events().publish( - (symbol_short!("ast_unlk"), chain_id), - ( - tx_hash, - block_number, - transaction_index, - asset_id, - recipient_bytes, - amount, - ), - ); - true + block_hash: &BytesN<32>, + parent_hash: &BytesN<32>, + state_root: &BytesN<32>, + tx_root: &BytesN<32>, + timestamp: u64, + ) -> BytesN<32> { + let mut bytes = Bytes::from_slice(env, b"cross-chain-client:header:v1:"); + bytes.append(&Bytes::from_slice(env, &chain_id.to_be_bytes())); + bytes.append(&Bytes::from_slice(env, &block_number.to_be_bytes())); + bytes.append(&Bytes::from_slice(env, &block_hash.to_array())); + bytes.append(&Bytes::from_slice(env, &parent_hash.to_array())); + bytes.append(&Bytes::from_slice(env, &state_root.to_array())); + bytes.append(&Bytes::from_slice(env, &tx_root.to_array())); + bytes.append(&Bytes::from_slice(env, ×tamp.to_be_bytes())); + env.crypto().sha256(&bytes).into() } /// Lightweight proof verification for a Merkle inclusion path. @@ -571,10 +503,134 @@ impl CrossChainClient { _recipient: Bytes, _amount: i128, ) -> bool { - panic_with_error!(&env, ClientError::InvalidProof); + caller.require_auth(); + Self::assert_admin(&env, &caller); + + if amount <= 0 + || !env + .storage() + .persistent() + .get::(&ClientKey::TxRoot(chain_id, expected_root.clone())) + .unwrap_or(false) + { + panic_with_error!(&env, ClientError::InvalidProof); + } + if env + .storage() + .persistent() + .get::(&ClientKey::ProcessedSourceTx(chain_id, tx_hash.clone())) + .unwrap_or(false) + { + panic_with_error!(&env, ClientError::ReplayDetected); + } + + if !Self::verify_merkle_proof(env.clone(), leaf_hash, proof, path, expected_root.clone()) { + panic_with_error!(&env, ClientError::InvalidProof); + } + + let record = UnlockRecord { + chain_id, + tx_hash: tx_hash.clone(), + asset_id, + recipient: recipient.clone(), + amount, + block_number: 0, + proof_root: expected_root, + unlocked_at: env.ledger().timestamp(), + }; + + env.storage() + .persistent() + .set(&ClientKey::Unlock(tx_hash.clone()), &record); + env.storage() + .persistent() + .set(&ClientKey::SourceUnlock(chain_id, tx_hash.clone()), &record); + env.storage().persistent().set( + &ClientKey::ProcessedSourceTx(chain_id, tx_hash.clone()), + &true, + ); + env.storage() + .persistent() + .set(&ClientKey::ProcessedTx(tx_hash.clone()), &true); + + env.events().publish( + (symbol_short!("unlock"), chain_id), + (tx_hash.clone(), recipient, amount), + ); + true + } + + /// Verify a transaction-trie MPT proof against an accepted header and + /// record an unlock. `trie_key` is the canonical RLP transaction index, + /// and `transaction` is the exact serialized transaction value. + pub fn unlock_asset_from_header( + env: Env, + caller: Address, + chain_id: ChainId, + block_number: u64, + tx_hash: BytesN<32>, + trie_key: Bytes, + transaction: Bytes, + proof_nodes: Vec, + asset_id: BytesN<32>, + recipient: Bytes, + amount: i128, + ) -> bool { + caller.require_auth(); + Self::assert_admin(&env, &caller); + if amount <= 0 { + panic_with_error!(&env, ClientError::InvalidTransaction); + } + let header = env + .storage() + .persistent() + .get::(&ClientKey::Header(chain_id, block_number)) + .unwrap_or_else(|| panic_with_error!(&env, ClientError::InvalidHeader)); + if env.crypto().keccak256(&transaction).to_bytes() != tx_hash { + panic_with_error!(&env, ClientError::InvalidTransaction); + } + if env + .storage() + .persistent() + .get::(&ClientKey::ProcessedSourceTx(chain_id, tx_hash.clone())) + .unwrap_or(false) + { + panic_with_error!(&env, ClientError::ReplayDetected); + } + if !verify_mpt_inclusion(&env, &header.tx_root, &trie_key, &transaction, &proof_nodes) { + panic_with_error!(&env, ClientError::InvalidTrieProof); + } + + let record = UnlockRecord { + chain_id, + tx_hash: tx_hash.clone(), + asset_id, + recipient: recipient.clone(), + amount, + block_number, + proof_root: header.tx_root, + unlocked_at: env.ledger().timestamp(), + }; + env.storage() + .persistent() + .set(&ClientKey::Unlock(tx_hash.clone()), &record); + env.storage() + .persistent() + .set(&ClientKey::SourceUnlock(chain_id, tx_hash.clone()), &record); + env.storage().persistent().set( + &ClientKey::ProcessedSourceTx(chain_id, tx_hash.clone()), + &true, + ); + env.storage() + .persistent() + .set(&ClientKey::ProcessedTx(tx_hash.clone()), &true); + env.events().publish( + (symbol_short!("unlock"), chain_id), + (tx_hash, recipient, amount), + ); + true } - /// Legacy hash-chain unlock is disabled. Use `unlock_from_receipt`. pub fn unlock_wrapped_asset( env: Env, _caller: Address, @@ -598,6 +654,13 @@ impl CrossChainClient { .unwrap_or_else(|| panic_with_error!(&env, ClientError::MessageNotFound)) } + pub fn get_source_unlock(env: Env, chain_id: ChainId, tx_hash: BytesN<32>) -> UnlockRecord { + env.storage() + .persistent() + .get(&ClientKey::SourceUnlock(chain_id, tx_hash)) + .unwrap_or_else(|| panic_with_error!(&env, ClientError::MessageNotFound)) + } + pub fn get_processed_tx(env: Env, tx_hash: BytesN<32>) -> bool { env.storage() .persistent() @@ -605,18 +668,11 @@ impl CrossChainClient { .unwrap_or(false) } - pub fn get_last_receipt_index(env: Env, chain_id: ChainId, block_number: u64) -> Option { - if !env - .storage() - .persistent() - .get::<_, bool>(&ClientKey::HasReceiptIndex(chain_id, block_number)) - .unwrap_or(false) - { - return None; - } + pub fn is_source_tx_processed(env: Env, chain_id: ChainId, tx_hash: BytesN<32>) -> bool { env.storage() .persistent() - .get(&ClientKey::LastReceiptIndex(chain_id, block_number)) + .get::(&ClientKey::ProcessedSourceTx(chain_id, tx_hash)) + .unwrap_or(false) } // ----------------------------------------------------------------------- @@ -835,5 +891,283 @@ impl CrossChainClient { } } +#[derive(Clone, Copy)] +struct RlpItem { + is_list: bool, + start: u32, + payload_start: u32, + payload_len: u32, + total_len: u32, +} + +fn verify_mpt_inclusion( + env: &Env, + root: &BytesN<32>, + key: &Bytes, + expected_value: &Bytes, + proof_nodes: &Vec, +) -> bool { + if key.is_empty() || key.len() > 64 || proof_nodes.is_empty() || proof_nodes.len() > 64 { + return false; + } + + let mut expected_ref = Bytes::from_slice(env, &root.to_array()); + let mut key_nibble = 0u32; + + for node_index in 0..proof_nodes.len() { + let encoded_node = proof_nodes.get(node_index).unwrap(); + if encoded_node.is_empty() || encoded_node.len() > 4_096 { + return false; + } + let node_item = match parse_rlp_item(&encoded_node, 0) { + Some(item) if item.is_list && item.total_len == encoded_node.len() => item, + _ => return false, + }; + + if expected_ref.len() == 32 { + let actual_hash: Bytes = env.crypto().keccak256(&encoded_node).into(); + if actual_hash != expected_ref { + return false; + } + } else if encoded_node != expected_ref { + return false; + } + + let field_count = match rlp_list_count(&encoded_node, &node_item) { + Some(count) => count, + None => return false, + }; + + if field_count == 17 { + if key_nibble == key.len() * 2 { + let value_item = match rlp_list_item(&encoded_node, &node_item, 16) { + Some(item) if !item.is_list => item, + _ => return false, + }; + return node_index + 1 == proof_nodes.len() + && rlp_item_bytes(&encoded_node, &value_item) + .map(|value| value == *expected_value) + .unwrap_or(false); + } + + let next_nibble = key_nibble_at(key, key_nibble); + let child = match rlp_list_item(&encoded_node, &node_item, next_nibble as u32) { + Some(item) => item, + None => return false, + }; + expected_ref = match rlp_reference_bytes(&encoded_node, &child) { + Some(reference) if !reference.is_empty() => reference, + _ => return false, + }; + key_nibble += 1; + } else if field_count == 2 { + let compact_item = match rlp_list_item(&encoded_node, &node_item, 0) { + Some(item) if !item.is_list => item, + _ => return false, + }; + let (next_position, is_leaf) = + match match_compact_path(&encoded_node, &compact_item, key, key_nibble) { + Some(result) => result, + None => return false, + }; + let value_or_child = match rlp_list_item(&encoded_node, &node_item, 1) { + Some(item) => item, + None => return false, + }; + if is_leaf { + return node_index + 1 == proof_nodes.len() + && next_position == key.len() * 2 + && !value_or_child.is_list + && rlp_item_bytes(&encoded_node, &value_or_child) + .map(|value| value == *expected_value) + .unwrap_or(false); + } + + key_nibble = next_position; + expected_ref = match rlp_reference_bytes(&encoded_node, &value_or_child) { + Some(reference) if !reference.is_empty() => reference, + _ => return false, + }; + } else { + return false; + } + } + + false +} + +fn parse_rlp_item(bytes: &Bytes, offset: u32) -> Option { + let prefix = bytes.get(offset)?; + let (is_list, payload_start, payload_len) = match prefix { + 0x00..=0x7f => (false, offset, 1), + 0x80..=0xb7 => { + let len = (prefix - 0x80) as u32; + let payload_start = offset.checked_add(1)?; + if len == 1 && bytes.get(payload_start)? < 0x80 { + return None; + } + (false, payload_start, len) + } + 0xb8..=0xbf => { + let len_of_len = (prefix - 0xb7) as u32; + let (payload_start, len) = rlp_long_length(bytes, offset, len_of_len)?; + if len < 56 { + return None; + } + (false, payload_start, len) + } + 0xc0..=0xf7 => (true, offset.checked_add(1)?, (prefix - 0xc0) as u32), + 0xf8..=0xff => { + let len_of_len = (prefix - 0xf7) as u32; + let (payload_start, len) = rlp_long_length(bytes, offset, len_of_len)?; + if len < 56 { + return None; + } + (true, payload_start, len) + } + }; + let end = payload_start.checked_add(payload_len)?; + if end > bytes.len() { + return None; + } + Some(RlpItem { + is_list, + start: offset, + payload_start, + payload_len, + total_len: end.checked_sub(offset)?, + }) +} + +fn rlp_long_length(bytes: &Bytes, offset: u32, len_of_len: u32) -> Option<(u32, u32)> { + let payload_start = offset.checked_add(1)?.checked_add(len_of_len)?; + let mut length = 0u32; + for i in 0..len_of_len { + let byte = bytes.get(offset.checked_add(1)?.checked_add(i)?)? as u32; + if i == 0 && byte == 0 { + return None; + } + length = length.checked_mul(256)?.checked_add(byte)?; + } + Some((payload_start, length)) +} + +fn rlp_list_item(bytes: &Bytes, list: &RlpItem, wanted_index: u32) -> Option { + if !list.is_list { + return None; + } + let mut cursor = list.payload_start; + let end = cursor.checked_add(list.payload_len)?; + let mut index = 0u32; + while cursor < end { + let item = parse_rlp_item(bytes, cursor)?; + if item.start.checked_add(item.total_len)? > end { + return None; + } + if index == wanted_index { + return Some(item); + } + cursor = cursor.checked_add(item.total_len)?; + index += 1; + } + None +} + +fn rlp_list_count(bytes: &Bytes, list: &RlpItem) -> Option { + if !list.is_list { + return None; + } + let mut cursor = list.payload_start; + let end = cursor.checked_add(list.payload_len)?; + let mut count = 0u32; + while cursor < end { + let item = parse_rlp_item(bytes, cursor)?; + if item.start.checked_add(item.total_len)? > end { + return None; + } + cursor = cursor.checked_add(item.total_len)?; + count = count.checked_add(1)?; + } + if cursor == end { + Some(count) + } else { + None + } +} + +fn rlp_item_bytes(bytes: &Bytes, item: &RlpItem) -> Option { + if item.is_list { + return None; + } + Some(bytes.slice(item.payload_start..item.payload_start.checked_add(item.payload_len)?)) +} + +fn rlp_reference_bytes(bytes: &Bytes, item: &RlpItem) -> Option { + if item.is_list { + if item.total_len >= 32 { + return None; + } + return Some(bytes.slice(item.start..item.start.checked_add(item.total_len)?)); + } + let reference = rlp_item_bytes(bytes, item)?; + if !reference.is_empty() && reference.len() != 32 { + return None; + } + Some(reference) +} + +fn match_compact_path( + node: &Bytes, + compact: &RlpItem, + key: &Bytes, + key_nibble: u32, +) -> Option<(u32, bool)> { + let compact_bytes = rlp_item_bytes(node, compact)?; + if compact_bytes.is_empty() { + return None; + } + let first = compact_bytes.get(0)?; + let flag = first >> 4; + if flag > 3 { + return None; + } + let odd = flag & 1 == 1; + let is_leaf = flag & 2 == 2; + if !odd && first & 0x0f != 0 { + return None; + } + let path_len = compact_bytes + .len() + .checked_mul(2)? + .checked_sub(if odd { 1 } else { 2 })?; + if !is_leaf && path_len == 0 { + return None; + } + for i in 0..path_len { + let nibble_offset = i + if odd { 1 } else { 2 }; + let packed = compact_bytes.get(nibble_offset / 2)?; + let nibble = if nibble_offset % 2 == 0 { + packed >> 4 + } else { + packed & 0x0f + }; + if key_nibble.checked_add(i)? >= key.len() * 2 + || key_nibble_at(key, key_nibble + i) != nibble + { + return None; + } + } + Some((key_nibble.checked_add(path_len)?, is_leaf)) +} + +fn key_nibble_at(key: &Bytes, nibble_index: u32) -> u8 { + let byte = key.get(nibble_index / 2).unwrap_or(0); + if nibble_index % 2 == 0 { + byte >> 4 + } else { + byte & 0x0f + } +} + #[cfg(test)] mod test; diff --git a/contracts/cross_chain_client/src/test.rs b/contracts/cross_chain_client/src/test.rs index 1f7c9ea1..3a6a1edf 100644 --- a/contracts/cross_chain_client/src/test.rs +++ b/contracts/cross_chain_client/src/test.rs @@ -8,6 +8,7 @@ //! * gating which headers are accepted. use super::*; +use ed25519_dalek::{Signer, SigningKey}; use soroban_sdk::testutils::{Address as _, Ledger as _}; use soroban_sdk::Env; @@ -95,6 +96,46 @@ fn validator_registration_and_threshold() { assert!(!client.is_validator(&validator)); } +#[test] +fn validator_quorum_tracks_distinct_active_validators() { + let env = Env::default(); + env.mock_all_auths(); + let (client, admin) = setup(&env); + + for key in [[1u8; 32], [2u8; 32], [3u8; 32], [4u8; 32]] { + client.register_validator(&admin, &BytesN::from_array(&env, &key)); + } + assert_eq!(client.get_threshold(), 3); + + client.set_threshold(&admin, &1u32); + assert_eq!(client.get_threshold(), 3); + + client.unregister_validator(&admin, &BytesN::from_array(&env, &[4u8; 32])); + assert_eq!(client.get_threshold(), 3); + client.unregister_validator(&admin, &BytesN::from_array(&env, &[3u8; 32])); + assert_eq!(client.get_threshold(), 2); +} + +#[test] +fn verify_block_header_rejects_duplicate_signers() { + let env = Env::default(); + env.mock_all_auths(); + let (client, admin) = setup(&env); + let validator = BytesN::from_array(&env, &[9u8; 32]); + client.register_validator(&admin, &validator); + + let hash = BytesN::from_array(&env, &[1u8; 32]); + let signers: Vec> = Vec::from_array(&env, [validator.clone(), validator]); + let signatures: Vec> = Vec::from_array( + &env, + [ + BytesN::from_array(&env, &[0u8; 64]), + BytesN::from_array(&env, &[0u8; 64]), + ], + ); + assert!(!client.verify_block_header(&hash, &signers, &signatures)); +} + #[test] fn verify_block_header_rejects_unregistered_signer() { let env = Env::default(); @@ -186,47 +227,107 @@ fn ledger_timestamp_advances_for_header_accept_time() { } #[test] -fn rlp_receipt_parser_accepts_valid_receipt_and_rejects_malformed_data() { - let receipt = valid_empty_receipt(); - let receipt = Bytes::from_slice(&Env::default(), &receipt); - assert!(rlp::is_receipt(&receipt)); - assert!(!rlp::is_receipt(&Bytes::from_array( - &Env::default(), - &[0xf8, 0x01, 0xc0] - ))); - +fn mpt_leaf_inclusion_verifies_exact_transaction_value() { let env = Env::default(); - assert_eq!(rlp::encode_index(&env, 0), Bytes::from_array(&env, &[0x80])); - assert_eq!(rlp::encode_index(&env, 1), Bytes::from_array(&env, &[0x01])); - assert_eq!( - rlp::encode_index(&env, 128), - Bytes::from_array(&env, &[0x81, 0x80]) - ); + let node = Bytes::from_array(&env, &[0xc6, 0x82, 0x20, 0x80, 0x82, 0xaa, 0xbb]); + let root: BytesN<32> = env.crypto().keccak256(&node).into(); + let key = Bytes::from_array(&env, &[0x80]); + let transaction = Bytes::from_array(&env, &[0xaa, 0xbb]); + let proof = Vec::from_array(&env, [node]); + + assert!(verify_mpt_inclusion( + &env, + &root, + &key, + &transaction, + &proof + )); } #[test] -fn mpt_receipt_proof_validates_leaf_against_keccak_root() { +fn mpt_leaf_inclusion_rejects_wrong_key_and_value() { let env = Env::default(); - let receipt = valid_empty_receipt(); - let key = rlp::encode_index(&env, 0); - let compact_path = [0x20, 0x80]; - let encoded_path = rlp_string(&compact_path); - let encoded_receipt = rlp_string(&receipt); - let mut leaf_contents = encoded_path; - leaf_contents.extend_from_slice(&encoded_receipt); - let leaf_node = rlp_list(&leaf_contents); - let leaf_node_bytes = Bytes::from_slice(&env, &leaf_node); - let root: BytesN<32> = env.crypto().keccak256(&leaf_node_bytes).into(); - let proof = Vec::from_array(&env, [leaf_node_bytes]); - - assert!(mpt::verify_proof( + let node = Bytes::from_array(&env, &[0xc6, 0x82, 0x20, 0x80, 0x82, 0xaa, 0xbb]); + let root: BytesN<32> = env.crypto().keccak256(&node).into(); + let proof = Vec::from_array(&env, [node]); + + assert!(!verify_mpt_inclusion( &env, &root, - &key, - &Bytes::from_slice(&env, &receipt), + &Bytes::from_array(&env, &[0x81]), + &Bytes::from_array(&env, &[0xaa, 0xbb]), + &proof + )); + assert!(!verify_mpt_inclusion( + &env, + &root, + &Bytes::from_array(&env, &[0x80]), + &Bytes::from_array(&env, &[0xaa, 0xbc]), &proof )); +} - let wrong_value = Bytes::from_array(&env, &[0xc0]); - assert!(!mpt::verify_proof(&env, &root, &key, &wrong_value, &proof)); +#[test] +fn accepted_header_mpt_proof_unlocks_once() { + let env = Env::default(); + env.mock_all_auths(); + let (client, admin) = setup(&env); + env.ledger().with_mut(|li| li.timestamp = 1_000); + + let signing_key = SigningKey::from_bytes(&[42u8; 32]); + let validator = BytesN::from_array(&env, &signing_key.verifying_key().to_bytes()); + client.register_validator(&admin, &validator); + + let transaction = Bytes::from_array(&env, &[0xaa, 0xbb]); + let trie_key = Bytes::from_array(&env, &[0x80]); + let node = Bytes::from_array(&env, &[0xc6, 0x82, 0x20, 0x80, 0x82, 0xaa, 0xbb]); + let tx_root: BytesN<32> = env.crypto().keccak256(&node).into(); + let block_hash = BytesN::from_array(&env, &[3u8; 32]); + let parent_hash = BytesN::from_array(&env, &[0u8; 32]); + let state_root = BytesN::from_array(&env, &[4u8; 32]); + let signing_hash = client.block_header_signing_hash( + &7u32, + &1u64, + &block_hash, + &parent_hash, + &state_root, + &tx_root, + &1_000u64, + ); + let signature = signing_key.sign(&signing_hash.to_array()).to_bytes(); + let signers = Vec::from_array(&env, [validator]); + let signatures = Vec::from_array(&env, [BytesN::from_array(&env, &signature)]); + client.submit_block_header( + &admin, + &7u32, + &1u64, + &block_hash, + &parent_hash, + &state_root, + &tx_root, + &1_000u64, + &signers, + &signatures, + ); + + let tx_hash: BytesN<32> = env.crypto().keccak256(&transaction).into(); + let proof_nodes = Vec::from_array(&env, [node]); + let asset_id = BytesN::from_array(&env, &[5u8; 32]); + let recipient = Bytes::from_array(&env, &[6u8; 32]); + assert!(client.unlock_asset_from_header( + &admin, + &7u32, + &1u64, + &tx_hash, + &trie_key, + &transaction, + &proof_nodes, + &asset_id, + &recipient, + &25i128, + )); + assert!(client.is_source_tx_processed(&7u32, &tx_hash)); + assert!(client.get_processed_tx(&tx_hash)); + assert_eq!(client.get_source_unlock(&7u32, &tx_hash).block_number, 1); + assert!(!client.is_source_tx_processed(&8u32, &tx_hash)); } diff --git a/contracts/did_registry/Cargo.toml b/contracts/did_registry/Cargo.toml index 155c0d4a..519b5fd6 100644 --- a/contracts/did_registry/Cargo.toml +++ b/contracts/did_registry/Cargo.toml @@ -11,3 +11,4 @@ soroban-sdk = "28.0.0" [dev-dependencies] soroban-sdk = { version = "28.0.0", features = ["testutils"] } +ed25519-dalek = { version = "2", default-features = false, features = ["std"] } diff --git a/contracts/did_registry/src/lib.rs b/contracts/did_registry/src/lib.rs index 6cadaff7..d3f2c2b5 100644 --- a/contracts/did_registry/src/lib.rs +++ b/contracts/did_registry/src/lib.rs @@ -1,8 +1,8 @@ // Decentralized Identity (DID) Registry Contract — `did:stellar` method // Language: Rust (Soroban) // -// This contract is the on-chain anchor for the `did:stellar` DID method. It -// implements the W3C DID Core 1.0 write/control model: +// This contract is the on-chain anchor for the `did:stellar` and `did:soroban` +// DID method identifiers and returns DID Core-compatible resolution records: // // * The DID identifier is the 32-byte Stellar Ed25519 account id // (`did:stellar:`). @@ -13,27 +13,109 @@ // only canonical `did:stellar:<64 hex>` DIDs and reject malformed strings // with `DIDError::MalformedDID`; `validate_did` is a non-panicking view. // -// Cryptographic *verification* of Ed25519 signatures over contributor proofs -// is performed by the off-chain resolver (see backend `didResolver`), which -// reads this on-chain state. On-chain we only store the binding so the -// resolver can fetch the trusted public key. +// Contributor proof signatures are verified by the off-chain resolver. Key +// rotation signatures are verified on-chain against the separately configured +// recovery key. #![no_std] use soroban_sdk::{ - contract, contracterror, contractimpl, Address, Bytes, BytesN, Env, Map, String, Symbol, Vec, + contract, contracterror, contractimpl, contracttype, panic_with_error, Address, Bytes, BytesN, + Env, Map, String, Symbol, Vec, }; -pub mod types; -pub mod verification; - -pub use types::*; - -/// Contract-level errors. #[contracterror] #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum DIDError { - /// `1` — input was not a canonical `did:stellar:<64 hex>` string. - MalformedDID = 1, +#[repr(u32)] +pub enum DidError { + Unauthorized = 1, + NotFound = 2, + AlreadyRegistered = 3, + Revoked = 4, + InvalidInput = 5, + Overflow = 6, + RecoveryKeyNotSet = 7, +} + +/// A single signed contributor proof claim (PR or issue milestone). +#[derive(Clone)] +#[contracttype] +pub struct ContributorProof { + /// Kind of contribution: "pr" or "issue". + pub claim_type: String, + /// GitHub repository, e.g. "StellarDevHub/Web3-Student-Lab". + pub repo: String, + /// Identifier of the PR/issue (number or node id). + pub item_id: String, + /// GitHub handle of the contributor (must match the bound handle). + pub github_handle: String, + /// Unix timestamp (seconds) the claim was issued. + pub issued_at: u64, + /// Raw Ed25519 signature bytes over the canonical claim payload. + pub signature: Bytes, +} + +#[derive(Clone)] +#[contracttype] +pub struct DIDDocument { + pub owner: Address, + /// Off-chain GitHub handle bound to this DID. + pub github_handle: Option, + /// Social handles keyed by provider symbol (github or discord). + pub social_identities: Map, + /// Ed25519 verification key (32 bytes) used to sign contributor proofs. + pub verification_key: Option>, + /// Recovery key used to authorize verification-key rotations. + pub recovery_key: Option>, + /// Previously active Ed25519 verification keys, in rotation order. + pub historical_verification_keys: Vec>, + /// Monotonic nonce included in signed key-rotation payloads. + pub key_rotation_nonce: u32, + pub attributes: Map, + pub services: Vec, + pub controllers: Vec
, + pub revoked: bool, + /// Stored contributor proofs (mirror of on-chain claims). + pub proofs: Vec, +} + +/// W3C DID Core verification method using the Ed25519 2020 multibase encoding. +#[derive(Clone)] +#[contracttype] +pub struct VerificationMethod { + pub id: String, + pub r#type: String, + pub controller: String, + pub public_key_multibase: String, +} + +/// W3C DID Core service entry. +#[derive(Clone)] +#[contracttype] +pub struct ServiceEndpoint { + pub id: String, + pub r#type: String, + pub service_endpoint: String, +} + +/// DID Core representation returned by the method-specific resolution calls. +#[derive(Clone)] +#[contracttype] +pub struct W3CDIDDocument { + /// Serialized by resolvers as the DID Core `@context` property. + pub context: Vec, + pub id: String, + pub verification_method: Vec, + pub authentication: Vec, + pub assertion_method: Vec, + pub capability_invocation: Vec, + pub service: Vec, +} + +#[contracttype] +pub enum DataKey { + DIDs, + /// Map, Vec> — claims per DID. + Proofs, } #[contract] @@ -48,13 +130,19 @@ impl DIDRegistryContract { .persistent() .get(&DataKey::DIDs) .unwrap_or_else(|| Map::new(&env)); - assert!(!dids.contains_key(did.clone()), "DID already registered"); + if dids.contains_key(did.clone()) { + panic_with_error!(&env, DidError::AlreadyRegistered); + } let doc = DIDDocument { owner: owner.clone(), github_handle: None, social_identities: Map::new(&env), verification_key: None, + recovery_key: None, + historical_verification_keys: Vec::new(&env), + key_rotation_nonce: 0, attributes, + services: Vec::new(&env), controllers: Vec::new(&env), revoked: false, proofs: Vec::new(&env), @@ -73,11 +161,12 @@ impl DIDRegistryContract { /// Bind an off-chain GitHub handle to the DID. Only the owner may bind. pub fn bind_github(env: Env, sender: Address, did: BytesN<32>, handle: String) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!(doc.owner == sender, "Only owner can bind github handle"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } doc.github_handle = Some(handle); doc.social_identities.set( Symbol::new(&env, "github"), @@ -97,15 +186,15 @@ impl DIDRegistryContract { handle: String, ) { sender.require_auth(); - assert!( - provider == Symbol::new(&env, "github") || provider == Symbol::new(&env, "discord"), - "Unsupported social provider" - ); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!(doc.owner == sender, "Only owner can bind social identity"); + if provider != Symbol::new(&env, "github") && provider != Symbol::new(&env, "discord") { + panic_with_error!(&env, DidError::InvalidInput); + } + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } if provider == Symbol::new(&env, "github") { doc.github_handle = Some(handle.clone()); } @@ -117,29 +206,114 @@ impl DIDRegistryContract { /// Set the Ed25519 verification key used to sign contributor proofs. pub fn set_verification_key(env: Env, sender: Address, did: BytesN<32>, key: BytesN<32>) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!(doc.owner == sender, "Only owner can set verification key"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender || doc.verification_key.is_some() { + panic_with_error!(&env, DidError::Unauthorized); + } doc.verification_key = Some(key); dids.set(did.clone(), doc); env.storage().persistent().set(&DataKey::DIDs, &dids); } - /// Revoke the delegated Ed25519 verification (signing) key. Only the - /// owner may revoke it; a new key can be set afterwards. - pub fn revoke_verification_key(env: Env, sender: Address, did: BytesN<32>) { + /// Set or replace the recovery key. Replacing it requires owner auth. + pub fn set_recovery_key(env: Env, sender: Address, did: BytesN<32>, key: BytesN<32>) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!( - doc.owner == sender, - "Only owner can revoke verification key" - ); - doc.verification_key = None; + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } + doc.recovery_key = Some(key); + dids.set(did, doc); + env.storage().persistent().set(&DataKey::DIDs, &dids); + } + + /// Return the exact domain-separated payload that a recovery key must sign. + pub fn key_rotation_payload(env: Env, did: BytesN<32>, new_key: BytesN<32>) -> Bytes { + let dids = read_dids(&env); + let doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + rotation_payload(&env, &did, &doc, &new_key) + .unwrap_or_else(|| panic_with_error!(&env, DidError::RecoveryKeyNotSet)) + } + + /// Rotate the signing key with an Ed25519 signature from the recovery key. + pub fn rotate_verification_key( + env: Env, + did: BytesN<32>, + new_key: BytesN<32>, + signature: BytesN<64>, + ) { + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + let recovery_key = doc + .recovery_key + .clone() + .unwrap_or_else(|| panic_with_error!(&env, DidError::RecoveryKeyNotSet)); + if doc.verification_key.as_ref() == Some(&new_key) { + panic_with_error!(&env, DidError::InvalidInput); + } + let payload = rotation_payload(&env, &did, &doc, &new_key) + .unwrap_or_else(|| panic_with_error!(&env, DidError::RecoveryKeyNotSet)); + env.crypto() + .ed25519_verify(&recovery_key, &payload, &signature); + + if let Some(current_key) = doc.verification_key.replace(new_key) { + doc.historical_verification_keys.push_back(current_key); + } + doc.key_rotation_nonce = doc + .key_rotation_nonce + .checked_add(1) + .unwrap_or_else(|| panic_with_error!(&env, DidError::Overflow)); + dids.set(did, doc); + env.storage().persistent().set(&DataKey::DIDs, &dids); + } + + /// Add a service endpoint to the DID document (DID controller only). + pub fn add_service( + env: Env, + sender: Address, + did: BytesN<32>, + service_id: String, + service_type: String, + endpoint: String, + ) { + sender.require_auth(); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } + if service_id.len() < 2 + || service_id.len() > 64 + || service_type.len() == 0 + || endpoint.len() == 0 + { + panic_with_error!(&env, DidError::InvalidInput); + } + let service_id_bytes = service_id.to_bytes(); + if service_id_bytes.get(0) != Some(b'#') { + panic_with_error!(&env, DidError::InvalidInput); + } + for index in 1..service_id.len() { + let byte = service_id_bytes.get(index).unwrap_or(0); + if !byte.is_ascii_alphanumeric() && !matches!(byte, b'-' | b'.' | b'_' | b'~') { + panic_with_error!(&env, DidError::InvalidInput); + } + } + if doc.services.iter().any(|entry| entry.id == service_id) { + panic_with_error!(&env, DidError::InvalidInput); + } + doc.services.push_back(ServiceEndpoint { + id: service_id, + r#type: service_type, + service_endpoint: endpoint, + }); dids.set(did, doc); env.storage().persistent().set(&DataKey::DIDs, &dids); } @@ -153,14 +327,12 @@ impl DIDRegistryContract { proof: ContributorProof, ) { sender.require_auth(); - let dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!( - verification::is_owner_or_controller(&doc, &sender), - "Not authorized" - ); + let dids = read_dids(&env); + let doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender && !doc.controllers.contains(&sender) { + panic_with_error!(&env, DidError::Unauthorized); + } if let Some(handle) = doc.github_handle.clone() { assert!( handle == proof.github_handle, @@ -180,14 +352,12 @@ impl DIDRegistryContract { pub fn update(env: Env, sender: Address, did: BytesN<32>, attributes: Map) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!( - verification::is_owner_or_controller(&doc, &sender), - "Not authorized" - ); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender && !doc.controllers.contains(&sender) { + panic_with_error!(&env, DidError::Unauthorized); + } doc.attributes = attributes; dids.set(did, doc); env.storage().persistent().set(&DataKey::DIDs, &dids); @@ -195,11 +365,12 @@ impl DIDRegistryContract { pub fn rotate_key(env: Env, sender: Address, did: BytesN<32>, new_owner: Address) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(!doc.revoked, "DID revoked"); - assert!(doc.owner == sender, "Only owner can rotate key"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } doc.owner = new_owner; dids.set(did, doc); env.storage().persistent().set(&DataKey::DIDs, &dids); @@ -207,10 +378,11 @@ impl DIDRegistryContract { pub fn revoke(env: Env, sender: Address, did: BytesN<32>) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(doc.owner == sender, "Only owner can revoke"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } doc.revoked = true; dids.set(did, doc); env.storage().persistent().set(&DataKey::DIDs, &dids); @@ -218,10 +390,12 @@ impl DIDRegistryContract { pub fn add_controller(env: Env, sender: Address, did: BytesN<32>, controller: Address) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(doc.owner == sender, "Only owner can add controller"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } if !doc.controllers.contains(&controller) { doc.controllers.push_back(controller); } @@ -231,10 +405,12 @@ impl DIDRegistryContract { pub fn remove_controller(env: Env, sender: Address, did: BytesN<32>, controller: Address) { sender.require_auth(); - let mut dids: Map, DIDDocument> = - env.storage().persistent().get(&DataKey::DIDs).unwrap(); - let mut doc = dids.get(did.clone()).unwrap(); - assert!(doc.owner == sender, "Only owner can remove controller"); + let mut dids = read_dids(&env); + let mut doc = read_doc(&env, &dids, &did); + ensure_active(&env, &doc); + if doc.owner != sender { + panic_with_error!(&env, DidError::Unauthorized); + } let idx = doc.controllers.iter().position(|c| c == controller); if let Some(i) = idx { doc.controllers.remove(i as u32); @@ -244,11 +420,7 @@ impl DIDRegistryContract { } pub fn resolve(env: Env, did: BytesN<32>) -> Option { - let dids: Map, DIDDocument> = env - .storage() - .persistent() - .get(&DataKey::DIDs) - .unwrap_or_else(|| Map::new(&env)); + let dids = read_dids(&env); let mut doc = dids.get(did.clone())?; let proofs: Map, Vec> = env .storage() @@ -259,39 +431,26 @@ impl DIDRegistryContract { Some(doc) } - /// Pure structural check: is this a canonical `did:stellar:<64 hex>` - /// string? Never panics — safe to call on untrusted resolver input. - pub fn validate_did(_env: Env, did: String) -> bool { - verification::is_valid_did_string(&did) + /// Resolve a DID Core document using the `did:stellar` method identifier. + pub fn resolve_stellar(env: Env, did: BytesN<32>) -> Option { + let dids = read_dids(&env); + let doc = dids.get(did.clone())?; + Some(w3c_document(&env, &did, &doc, stellar_did(&env, &did))) } - /// Register a DID from its canonical string form. Malformed DID strings - /// are rejected with `DIDError::MalformedDID`. - pub fn register_string(env: Env, owner: Address, did: String, attributes: Map) { - // Parsing runs first so malformed input is rejected before anything - // else; `register` performs the `owner.require_auth()` itself (a - // second `require_auth` on the same frame is an auth error). - let key = match verification::parse_did_string(&env, &did) { - Some(key) => key, - None => soroban_sdk::panic_with_error!(&env, DIDError::MalformedDID), - }; - Self::register(env, owner, key, attributes); - } - - /// Resolve a DID document from its canonical string form. Malformed DID - /// strings are rejected with `DIDError::MalformedDID`. - pub fn resolve_string(env: Env, did: String) -> Option { - let key = match verification::parse_did_string(&env, &did) { - Some(key) => key, - None => soroban_sdk::panic_with_error!(&env, DIDError::MalformedDID), - }; - Self::resolve(env, key) - } - - /// Canonical `did:stellar:` string for a raw DID key — exact inverse - /// of the parser backing the string entry points. - pub fn did_to_string(env: Env, did: BytesN<32>) -> String { - verification::did_to_string(&env, &did) + /// Resolve a DID Core document using `did:soroban::`. + pub fn resolve_soroban(env: Env, did: BytesN<32>, network: String) -> Option { + if !valid_network(&network) { + panic_with_error!(&env, DidError::InvalidInput); + } + let dids = read_dids(&env); + let doc = dids.get(did.clone())?; + Some(w3c_document( + &env, + &did, + &doc, + soroban_did(&env, &did, &network), + )) } /// Returns the bound GitHub handle for a DID, if any. @@ -317,11 +476,7 @@ impl DIDRegistryContract { /// Returns the Ed25519 verification key for a DID, if set. pub fn get_verification_key(env: Env, did: BytesN<32>) -> Option> { - let dids: Map, DIDDocument> = env - .storage() - .persistent() - .get(&DataKey::DIDs) - .unwrap_or_else(|| Map::new(&env)); + let dids = read_dids(&env); dids.get(did).and_then(|d| d.verification_key) } @@ -336,6 +491,249 @@ impl DIDRegistryContract { } } +fn read_dids(env: &Env) -> Map, DIDDocument> { + env.storage() + .persistent() + .get(&DataKey::DIDs) + .unwrap_or_else(|| Map::new(env)) +} + +fn read_doc(env: &Env, dids: &Map, DIDDocument>, did: &BytesN<32>) -> DIDDocument { + dids.get(did.clone()) + .unwrap_or_else(|| panic_with_error!(env, DidError::NotFound)) +} + +fn ensure_active(env: &Env, doc: &DIDDocument) { + if doc.revoked { + panic_with_error!(env, DidError::Revoked); + } +} + +fn rotation_payload( + env: &Env, + did: &BytesN<32>, + doc: &DIDDocument, + new_key: &BytesN<32>, +) -> Option { + let current_key = doc.verification_key.as_ref()?; + let network_id = env.ledger().network_id(); + let mut payload = Bytes::from_slice(env, b"did-registry:key-rotation:v1:"); + payload.append(&env.current_contract_address().to_string().to_bytes()); + payload.append(&Bytes::from_slice(env, b":")); + payload.append(&Bytes::from_slice(env, &network_id.to_array())); + payload.append(&Bytes::from_slice(env, &did.to_array())); + payload.append(&Bytes::from_slice(env, ¤t_key.to_array())); + payload.append(&Bytes::from_slice(env, &new_key.to_array())); + payload.append(&Bytes::from_slice( + env, + &doc.key_rotation_nonce.to_be_bytes(), + )); + Some(payload) +} + +fn stellar_did(env: &Env, did: &BytesN<32>) -> String { + make_did_string(env, b"did:stellar:", None, did) +} + +fn soroban_did(env: &Env, did: &BytesN<32>, network: &String) -> String { + make_did_string(env, b"did:soroban:", Some(network), did) +} + +fn make_did_string(env: &Env, prefix: &[u8], network: Option<&String>, did: &BytesN<32>) -> String { + let mut result = [0u8; 128]; + let mut len = prefix.len(); + result[..len].copy_from_slice(prefix); + if let Some(network) = network { + let network_len = network.len() as usize; + network.copy_into_slice(&mut result[len..len + network_len]); + len += network_len; + result[len] = b':'; + len += 1; + } + const HEX: &[u8; 16] = b"0123456789abcdef"; + for byte in did.to_array() { + result[len] = HEX[(byte >> 4) as usize]; + result[len + 1] = HEX[(byte & 0x0f) as usize]; + len += 2; + } + String::from_bytes(env, &result[..len]) +} + +fn w3c_document( + env: &Env, + did: &BytesN<32>, + doc: &DIDDocument, + identifier: String, +) -> W3CDIDDocument { + let mut context = Vec::new(env); + context.push_back(String::from_str(env, "https://www.w3.org/ns/did/v1")); + context.push_back(String::from_str( + env, + "https://w3id.org/security/suites/ed25519-2020/v1", + )); + + let mut verification_method = Vec::new(env); + let mut authentication = Vec::new(env); + let mut assertion_method = Vec::new(env); + for (index, key) in doc.historical_verification_keys.iter().enumerate() { + let method_id = key_method_id(env, &identifier, index as u32 + 1); + verification_method.push_back(verification_method_entry(env, &identifier, &method_id, key)); + } + if let Some(current_key) = doc.verification_key.as_ref() { + let current_method_id = + key_method_id(env, &identifier, doc.historical_verification_keys.len() + 1); + verification_method.push_back(verification_method_entry( + env, + &identifier, + ¤t_method_id, + current_key, + )); + authentication.push_back(current_method_id.clone()); + assertion_method.push_back(current_method_id); + } + + let mut capability_invocation = Vec::new(env); + if let Some(recovery_key) = doc.recovery_key.as_ref() { + let recovery_method_id = recovery_method_id(env, &identifier); + verification_method.push_back(verification_method_entry( + env, + &identifier, + &recovery_method_id, + recovery_key, + )); + capability_invocation.push_back(recovery_method_id); + } + + W3CDIDDocument { + context, + id: identifier, + verification_method, + authentication, + assertion_method, + capability_invocation, + service: absolute_services(env, &identifier, &doc.services), + } +} + +fn absolute_services( + env: &Env, + did: &String, + services: &Vec, +) -> Vec { + let mut resolved = Vec::new(env); + for service in services.iter() { + let mut id = [0u8; 192]; + let did_len = did.len() as usize; + did.copy_into_slice(&mut id[..did_len]); + let fragment_len = service.id.len() as usize; + service + .id + .copy_into_slice(&mut id[did_len..did_len + fragment_len]); + resolved.push_back(ServiceEndpoint { + id: String::from_bytes(env, &id[..did_len + fragment_len]), + r#type: service.r#type, + service_endpoint: service.service_endpoint, + }); + } + resolved +} + +fn verification_method_entry( + env: &Env, + controller: &String, + method_id: &String, + key: &BytesN<32>, +) -> VerificationMethod { + VerificationMethod { + id: method_id.clone(), + r#type: String::from_str(env, "Ed25519VerificationKey2020"), + controller: controller.clone(), + public_key_multibase: ed25519_multibase(env, key), + } +} + +fn key_method_id(env: &Env, did: &String, index: u32) -> String { + let mut output = [0u8; 160]; + let did_len = did.len() as usize; + did.copy_into_slice(&mut output[..did_len]); + let mut digits = [0u8; 10]; + let mut value = index; + let mut digit_len = 0usize; + while value > 0 { + digits[digit_len] = b'0' + (value % 10) as u8; + digit_len += 1; + value /= 10; + } + let mut len = did_len; + output[len..len + 5].copy_from_slice(b"#key-"); + len += 5; + for digit in digits[..digit_len].iter().rev() { + output[len] = *digit; + len += 1; + } + String::from_bytes(env, &output[..len]) +} + +fn recovery_method_id(env: &Env, did: &String) -> String { + let mut output = [0u8; 160]; + let did_len = did.len() as usize; + did.copy_into_slice(&mut output[..did_len]); + output[did_len..did_len + 13].copy_from_slice(b"#recovery-key"); + String::from_bytes(env, &output[..did_len + 13]) +} + +fn ed25519_multibase(env: &Env, key: &BytesN<32>) -> String { + const ALPHABET: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + let mut input = [0u8; 34]; + input[0] = 0xed; + input[1] = 0x01; + input[2..].copy_from_slice(&key.to_array()); + + let mut digits = [0u8; 47]; + let mut digit_len = 0usize; + for byte in input { + let mut carry = byte as u32; + for digit in digits[..digit_len].iter_mut() { + carry += (*digit as u32) << 8; + *digit = (carry % 58) as u8; + carry /= 58; + } + while carry > 0 { + digits[digit_len] = (carry % 58) as u8; + digit_len += 1; + carry /= 58; + } + } + + let mut encoded = [0u8; 48]; + encoded[0] = b'z'; + let mut len = 1usize; + for digit in digits[..digit_len].iter().rev() { + encoded[len] = ALPHABET[*digit as usize]; + len += 1; + } + String::from_bytes(env, &encoded[..len]) +} + +fn valid_network(network: &String) -> bool { + let len = network.len() as usize; + if len == 0 || len > 32 { + return false; + } + let mut bytes = [0u8; 32]; + network.copy_into_slice(&mut bytes[..len]); + bytes[..len].iter().all(|byte| { + byte.is_ascii_lowercase() + || byte.is_ascii_uppercase() + || byte.is_ascii_digit() + || *byte == b'-' + }) +} + +#[cfg(test)] +#[path = "test.rs"] +mod integration_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/contracts/did_registry/src/test.rs b/contracts/did_registry/src/test.rs index a4e3c641..fd340b6f 100644 --- a/contracts/did_registry/src/test.rs +++ b/contracts/did_registry/src/test.rs @@ -16,7 +16,7 @@ //! - Unauthorized key binding attempts rejected (SC-010) //! - Delegated verification key revocation (SC-010) -use crate::{ContributorProof, DIDRegistryContract, DIDRegistryContractClient}; +use crate::{ContributorProof, DIDRegistryContract, DIDRegistryContractClient, DidError}; use soroban_sdk::{ symbol_short, testutils::Address as _, Address, Bytes, BytesN, Env, Map, String, Symbol, }; @@ -410,114 +410,139 @@ fn test_update_attributes() { assert!(doc.attributes.contains_key(symbol_short!("endpoint"))); } -// ── DID string form (SC-010) ────────────────────────────────────────────────── - #[test] -fn test_register_and_resolve_via_did_string() { +fn test_resolves_w3c_documents_for_stellar_and_soroban() { let env = Env::default(); env.mock_all_auths(); let (_id, client) = deploy(&env); let owner = Address::generate(&env); let did = make_did(&env, 20); - let did_str = canonical_string(&env, 20); - let mut attrs = Map::new(&env); - attrs.set(symbol_short!("name"), Bytes::from_slice(&env, b"Alice")); + register_default(&env, &client, &owner, &did); - assert!(client.validate_did(&did_str)); + let verification_key = BytesN::from_array(&env, &[21u8; 32]); + let recovery_key = BytesN::from_array(&env, &[22u8; 32]); + client.set_verification_key(&owner, &did, &verification_key); + client.set_recovery_key(&owner, &did, &recovery_key); + client.add_service( + &owner, + &did, + &String::from_str(&env, "#profile"), + &String::from_str(&env, "LinkedDomains"), + &String::from_str(&env, "https://example.com"), + ); - client.register_string(&owner, &did_str, &attrs); - let doc = client.resolve_string(&did_str).unwrap(); - assert_eq!(doc.owner, owner); - // The string form resolves to the same document as the raw 32-byte key. - assert_eq!(client.resolve(&did).unwrap().owner, owner); - // Contract-side formatter round-trips to the exact canonical string. - assert_eq!(client.did_to_string(&did), did_str); - assert!(client.validate_did(&client.did_to_string(&did))); + let stellar = client.resolve_stellar(&did).unwrap(); + assert_eq!( + stellar.id, + String::from_str( + &env, + "did:stellar:1414141414141414141414141414141414141414141414141414141414141414" + ) + ); + assert_eq!( + stellar.context.len(), + 2, + "DID Core and Ed25519 contexts should be present" + ); + assert_eq!(stellar.verification_method.len(), 2); + assert_eq!(stellar.authentication.len(), 1); + assert_eq!(stellar.assertion_method.len(), 1); + assert_eq!(stellar.capability_invocation.len(), 1); + assert_eq!(stellar.service.len(), 1); + assert_eq!( + stellar.service.get(0).unwrap().id, + String::from_str( + &env, + "did:stellar:1414141414141414141414141414141414141414141414141414141414141414#profile" + ) + ); + assert_eq!( + stellar.verification_method.get(0).unwrap().r#type, + String::from_str(&env, "Ed25519VerificationKey2020") + ); + assert!( + stellar + .verification_method + .get(0) + .unwrap() + .public_key_multibase + .len() + > 1 + ); + + let soroban = client + .resolve_soroban(&did, &String::from_str(&env, "testnet")) + .unwrap(); + assert_eq!( + soroban.id, + String::from_str( + &env, + "did:soroban:testnet:1414141414141414141414141414141414141414141414141414141414141414" + ) + ); } #[test] -fn test_malformed_did_strings_rejected() { +fn test_recovery_signature_rotates_key_and_preserves_history() { + use ed25519_dalek::Signer; + let env = Env::default(); env.mock_all_auths(); let (_id, client) = deploy(&env); let owner = Address::generate(&env); + let did = make_did(&env, 21); + register_default(&env, &client, &owner, &did); - let hex64 = [b'a'; 64]; - // Sanity: the happy-path construction is accepted by the view. - let valid = cat(&env, &[b"did:stellar:", &hex64]); - assert!(client.validate_did(&valid)); - - let cases = [ - cat(&env, &[]), // empty - cat(&env, &[b"did:stellar:"]), // prefix only - cat(&env, &[b"did:stellar:", &hex64[..63]]), // 63 hex chars - cat(&env, &[b"did:stellar:", &hex64, b"a"]), // 65 hex chars - cat(&env, &[b"did:stellar:", &[b'z'; 64]]), // non-hex payload - cat(&env, &[b"did:ethr:", &hex64]), // wrong method - cat(&env, &[b"did:STELLAR:", &hex64]), // case-sensitive prefix - cat(&env, &[&hex64]), // missing prefix - cat(&env, &[b"did:stellar:", &hex64, b"x"]), // trailing suffix - ]; - for case in cases { - assert!(!client.validate_did(&case), "view must reject: {case:?}"); - let reg = client.try_register_string(&owner, &case, &Map::new(&env)); - assert!(reg.is_err(), "register_string must reject: {case:?}"); - let res = client.try_resolve_string(&case); - assert!(res.is_err(), "resolve_string must reject: {case:?}"); - } + let current_signing_key = ed25519_dalek::SigningKey::from_bytes(&[31u8; 32]); + let recovery_signing_key = ed25519_dalek::SigningKey::from_bytes(&[32u8; 32]); + let new_signing_key = ed25519_dalek::SigningKey::from_bytes(&[33u8; 32]); + let current_key = BytesN::from_array(&env, current_signing_key.verifying_key().as_bytes()); + let recovery_key = BytesN::from_array(&env, recovery_signing_key.verifying_key().as_bytes()); + let new_key = BytesN::from_array(&env, new_signing_key.verifying_key().as_bytes()); + client.set_verification_key(&owner, &did, ¤t_key); + client.set_recovery_key(&owner, &did, &recovery_key); + + let payload = client.key_rotation_payload(&did, &new_key); + let signature = recovery_signing_key.sign(&payload.to_alloc_vec()); + let signature = BytesN::from_array(&env, &signature.to_bytes()); + client.rotate_verification_key(&did, &new_key, &signature); + + let resolved = client.resolve(&did).unwrap(); + assert_eq!(resolved.verification_key, Some(new_key)); + assert_eq!(resolved.historical_verification_keys.len(), 1); + assert_eq!( + resolved.historical_verification_keys.get(0), + Some(current_key) + ); + assert_eq!(resolved.key_rotation_nonce, 1); } -// ── Unauthorized key binding (SC-010) ───────────────────────────────────────── - #[test] -fn test_unauthorized_key_binding_rejected() { +fn test_unauthorized_owner_change_uses_typed_error() { let env = Env::default(); env.mock_all_auths(); let (_id, client) = deploy(&env); let owner = Address::generate(&env); - let stranger = Address::generate(&env); - let did = make_did(&env, 21); + let attacker = Address::generate(&env); + let did = make_did(&env, 22); register_default(&env, &client, &owner, &did); - // A non-owner must be rejected from every binding operation. - let handle = String::from_str(&env, "mallory"); - assert!(client.try_bind_github(&stranger, &did, &handle).is_err()); - assert!(client - .try_bind_social(&stranger, &did, &Symbol::new(&env, "discord"), &handle) - .is_err()); - let key = BytesN::from_array(&env, &[9u8; 32]); - assert!(client - .try_set_verification_key(&stranger, &did, &key) - .is_err()); - assert!(client.try_revoke_verification_key(&stranger, &did).is_err()); - assert!(client - .try_add_contributor_proof(&stranger, &did, &make_proof(&env, "mallory")) - .is_err()); - - // None of the attempts mutated the document. - let doc = client.resolve(&did).unwrap(); - assert!(doc.github_handle.is_none()); - assert_eq!(client.get_verification_key(&did), None); - assert_eq!(client.get_proofs(&did).len(), 0); + let result = client.try_bind_github(&attacker, &did, &String::from_str(&env, "mallory")); + assert_eq!(result, Err(Ok(DidError::Unauthorized))); } #[test] -fn test_owner_revoke_verification_key() { +fn test_verification_key_cannot_be_replaced_without_recovery_signature() { let env = Env::default(); env.mock_all_auths(); let (_id, client) = deploy(&env); let owner = Address::generate(&env); - let did = make_did(&env, 22); + let did = make_did(&env, 23); register_default(&env, &client, &owner, &did); - let key = BytesN::from_array(&env, &[7u8; 32]); - client.set_verification_key(&owner, &did, &key); - assert_eq!(client.get_verification_key(&did), Some(key.clone())); - - client.revoke_verification_key(&owner, &did); - assert_eq!(client.get_verification_key(&did), None); - - // A new key can be bound again after revocation. - client.set_verification_key(&owner, &did, &key); - assert_eq!(client.get_verification_key(&did), Some(key)); + let original = BytesN::from_array(&env, &[23u8; 32]); + let replacement = BytesN::from_array(&env, &[24u8; 32]); + client.set_verification_key(&owner, &did, &original); + let result = client.try_set_verification_key(&owner, &did, &replacement); + assert_eq!(result, Err(Ok(DidError::Unauthorized))); } diff --git a/contracts/fractional_nft_vault/src/lib.rs b/contracts/fractional_nft_vault/src/lib.rs index db034238..d8671efa 100644 --- a/contracts/fractional_nft_vault/src/lib.rs +++ b/contracts/fractional_nft_vault/src/lib.rs @@ -608,7 +608,7 @@ impl FractionalNftVaultContract { /// Start a blinded commit-reveal buyout auction. /// /// * `min_bid` — minimum acceptable revealed bid. - /// * `deposit` — anti-spam deposit escrowed with each commitment. + /// * `deposit` — anti-spam deposit, at least 10% of `min_bid`. /// * `commit_duration` — seconds the commit phase lasts. /// * `reveal_duration` — seconds the reveal phase lasts after commit closes. pub fn start_commit_reveal_auction( @@ -624,7 +624,9 @@ impl FractionalNftVaultContract { admin.require_auth(); require_admin(&env, &admin); - if min_bid <= 0 || deposit <= 0 || commit_duration == 0 || reveal_duration == 0 { + let minimum_deposit = min_bid / 10 + if min_bid % 10 == 0 { 0 } else { 1 }; + if min_bid <= 0 || deposit < minimum_deposit || commit_duration == 0 || reveal_duration == 0 + { panic_with_error!(&env, VaultError::InvalidAmount); } ensure_no_auction(&env); @@ -771,11 +773,7 @@ impl FractionalNftVaultContract { .highest_bidder .clone() .unwrap_or_else(|| panic_with_error!(&env, VaultError::NoBids)); - let price = if auction.second_highest_bid > 0 { - auction.second_highest_bid - } else { - auction.highest_bid - }; + let price = auction.second_highest_bid.max(auction.min_bid); let payment = token::Client::new(&env, &read_payment_token(&env)); for (bidder, amount) in auction.reveals.iter() { @@ -799,8 +797,9 @@ impl FractionalNftVaultContract { auction.forfeited_deposits = forfeited; auction.finalized = true; - let treasury = price - .checked_add(forfeited) + let treasury = read_treasury(&env) + .checked_add(price) + .and_then(|amount| amount.checked_add(forfeited)) .unwrap_or_else(|| panic_with_error!(&env, VaultError::Overflow)); env.storage().instance().set(&DataKey::Treasury, &treasury); env.storage().instance().set(&DataKey::Finalized, &true); @@ -820,6 +819,38 @@ impl FractionalNftVaultContract { publish_auction(&env, &winner, treasury, read_total_shares(&env), true); } + /// Settle an auction with no valid reveals after its reveal deadline. + /// + /// Outstanding deposits are forfeited into the buyout treasury and the + /// empty auction is cleared so a later auction can proceed. The slashed + /// amount is distributed pro-rata with the proceeds of the eventual + /// successful buyout. + pub fn settle_unrevealed_bids(env: Env) -> i128 { + ensure_initialized(&env); + ensure_not_finalized(&env); + + let auction = read_cr_auction(&env); + if env.ledger().timestamp() <= auction.reveal_deadline { + panic_with_error!(&env, VaultError::AuctionActive); + } + if auction.revealed_count != 0 { + panic_with_error!(&env, VaultError::AuctionActive); + } + + let mut forfeited = 0i128; + for (_, deposit) in auction.deposits.iter() { + forfeited = forfeited + .checked_add(deposit) + .unwrap_or_else(|| panic_with_error!(&env, VaultError::Overflow)); + } + let treasury = read_treasury(&env) + .checked_add(forfeited) + .unwrap_or_else(|| panic_with_error!(&env, VaultError::Overflow)); + env.storage().instance().set(&DataKey::Treasury, &treasury); + env.storage().instance().remove(&DataKey::CrAuction); + forfeited + } + /// Cancel a live commit-reveal auction and refund every escrow. Admin only. pub fn cancel_commit_reveal_auction(env: Env, admin: Address) { ensure_initialized(&env); @@ -828,6 +859,9 @@ impl FractionalNftVaultContract { require_admin(&env, &admin); let auction = read_cr_auction(&env); + if env.ledger().timestamp() > auction.reveal_deadline { + panic_with_error!(&env, VaultError::AuctionActive); + } let payment = token::Client::new(&env, &read_payment_token(&env)); for (bidder, amount) in auction.reveals.iter() { if amount > 0 { @@ -1627,6 +1661,50 @@ mod tests { assert!(v.client().finalized()); } + #[test] + fn no_reveal_deposits_are_slashed_and_distributed_with_next_buyout() { + let v = setup(); + fractionalize(&v, 300, 200, 500); + let sac = token::StellarAssetClient::new(&v.env, &v.payment_token); + + v.client() + .start_commit_reveal_auction(&v.admin, &1_000, &100, &10, &10); + let (no_show_commitment, _) = commitment(&v.env, 5_000); + v.client().commit_bid(&v.bidder, &no_show_commitment, &100); + + v.env.ledger().with_mut(|li| li.timestamp = 21); + assert_eq!(v.client().settle_unrevealed_bids(), 100); + assert_eq!(v.client().treasury(), 100); + assert!(v.client().commit_reveal_auction().is_none()); + assert!(!v.client().finalized()); + assert!(v.client().nft_locked()); + assert_eq!(sac.balance(&v.bidder), 10_000_000 - 100); + + v.client() + .start_commit_reveal_auction(&v.admin, &1_000, &100, &10, &10); + let (next_commitment, nonce) = commitment(&v.env, 5_000); + v.client().commit_bid(&v.bidder, &next_commitment, &100); + v.env.ledger().with_mut(|li| li.timestamp = 32); + v.client().reveal_bid(&v.bidder, &5_000, &nonce); + v.env.ledger().with_mut(|li| li.timestamp = 42); + v.client().finalize_commit_reveal_auction(&v.admin); + + assert_eq!(v.client().treasury(), 1_100); + assert_eq!(v.client().claim_buyout_payout(&v.user_a), 330); + assert_eq!(v.client().claim_buyout_payout(&v.user_b), 220); + assert_eq!(v.client().claim_buyout_payout(&v.admin), 550); + assert_eq!(nft_owner(&v), v.bidder); + } + + #[test] + #[should_panic(expected = "Error(Contract, #4)")] + fn commit_reveal_requires_ten_percent_minimum_deposit() { + let v = setup(); + fractionalize(&v, 300, 200, 500); + v.client() + .start_commit_reveal_auction(&v.admin, &1_000, &99, &10, &10); + } + #[test] fn commit_reveal_anti_snipe_extends_both_deadlines() { let v = setup();