diff --git a/dlp-api/src/v2/args/mod.rs b/dlp-api/src/v2/args/mod.rs index ab1733b1..e73da8ba 100644 --- a/dlp-api/src/v2/args/mod.rs +++ b/dlp-api/src/v2/args/mod.rs @@ -7,6 +7,7 @@ mod post_commitment; mod raise_challenge; mod register_operator; mod register_verifier; +mod resolve_dispute; mod update_protocol_config; mod update_verifier_registry; mod write_state_buffer; @@ -17,6 +18,7 @@ pub use post_commitment::*; pub use raise_challenge::*; pub use register_operator::*; pub use register_verifier::*; +pub use resolve_dispute::*; pub use update_protocol_config::*; pub use update_verifier_registry::*; pub use write_state_buffer::*; diff --git a/dlp-api/src/v2/args/resolve_dispute.rs b/dlp-api/src/v2/args/resolve_dispute.rs new file mode 100644 index 00000000..fda26890 --- /dev/null +++ b/dlp-api/src/v2/args/resolve_dispute.rs @@ -0,0 +1,11 @@ +use wheels::variable_offset_layout; + +pub const DISPUTE_DECISION_OPERATOR_STATE_CORRECT: u8 = 1; +pub const DISPUTE_DECISION_CHALLENGER_STATE_CORRECT: u8 = 2; + +#[derive(Clone, Debug, PartialEq, Eq)] +#[variable_offset_layout(buffer_offset = 1)] +pub struct ResolveDisputeArgs { + /// Resolver decision for a valid mismatched reveal. + pub decision: u8, +} diff --git a/dlp-api/src/v2/instruction.rs b/dlp-api/src/v2/instruction.rs index 77a0ffa9..3f98a878 100644 --- a/dlp-api/src/v2/instruction.rs +++ b/dlp-api/src/v2/instruction.rs @@ -31,6 +31,8 @@ pub enum DlpV2Instruction { RaiseChallenge = 109, /// Reveals challenger state for a v2 challenge. ChallengerReveal = 110, + /// Applies resolver decision for a v2 challenge. + ResolveDispute = 111, } impl DlpV2Instruction { diff --git a/dlp-api/src/v2/instruction_builder/mod.rs b/dlp-api/src/v2/instruction_builder/mod.rs index 4d9d4eff..56f615af 100644 --- a/dlp-api/src/v2/instruction_builder/mod.rs +++ b/dlp-api/src/v2/instruction_builder/mod.rs @@ -6,6 +6,7 @@ mod post_commitment; mod raise_challenge; mod register_operator; mod register_verifier; +mod resolve_dispute; mod update_protocol_config; mod update_verifier_registry; mod write_state_buffer; @@ -18,6 +19,7 @@ pub use post_commitment::*; pub use raise_challenge::*; pub use register_operator::*; pub use register_verifier::*; +pub use resolve_dispute::*; pub use update_protocol_config::*; pub use update_verifier_registry::*; pub use write_state_buffer::*; diff --git a/dlp-api/src/v2/instruction_builder/resolve_dispute.rs b/dlp-api/src/v2/instruction_builder/resolve_dispute.rs new file mode 100644 index 00000000..a5ca99f9 --- /dev/null +++ b/dlp-api/src/v2/instruction_builder/resolve_dispute.rs @@ -0,0 +1,60 @@ +use solana_program::{ + instruction::{AccountMeta, Instruction}, + pubkey::Pubkey, +}; +use wheels::layout::Encodable; + +use crate::{ + compat::{Compatize, Modernize}, + pda::fees_vault_pda, + v2::{ + pda::{ + challenge_pda, operator_bond_pda, pending_commitment_pda, + protocol_config_pda, + }, + DlpV2Instruction, ResolveDisputeArgs, + }, +}; + +/// Builds the instruction that applies a resolver decision for a v2 challenge. +pub fn resolve_dispute( + resolver: Pubkey, + operator: Pubkey, + challenger: Pubkey, + account: Pubkey, + commit_id: u64, + args: ResolveDisputeArgs, +) -> Instruction { + Instruction { + program_id: crate::id().modernize(), + accounts: vec![ + AccountMeta::new_readonly(resolver, true), + AccountMeta::new( + challenge_pda( + &account.compatize(), + commit_id, + &challenger.compatize(), + ) + .modernize(), + false, + ), + AccountMeta::new( + pending_commitment_pda(&account.compatize(), commit_id) + .modernize(), + false, + ), + AccountMeta::new( + operator_bond_pda(&operator.compatize()).modernize(), + false, + ), + AccountMeta::new(challenger, false), + AccountMeta::new_readonly(protocol_config_pda().modernize(), false), + AccountMeta::new(fees_vault_pda().modernize(), false), + ], + data: [ + DlpV2Instruction::ResolveDispute.to_vec(), + args.encode().unwrap(), + ] + .concat(), + } +} diff --git a/dlp-api/src/v2/state/challenge.rs b/dlp-api/src/v2/state/challenge.rs index 8653c04c..eb38d797 100644 --- a/dlp-api/src/v2/state/challenge.rs +++ b/dlp-api/src/v2/state/challenge.rs @@ -9,6 +9,8 @@ pub const CHALLENGE_STATUS_TERMINAL: u8 = 3; pub const CHALLENGE_OUTCOME_NONE: u8 = 0; pub const CHALLENGE_OUTCOME_INVALID_REVEAL: u8 = 1; pub const CHALLENGE_OUTCOME_MATCHING_STATE_CHALLENGER_PENALIZED: u8 = 2; +pub const CHALLENGE_OUTCOME_OPERATOR_CORRECT_CHALLENGER_SLASHED: u8 = 3; +pub const CHALLENGE_OUTCOME_CHALLENGER_CORRECT_OPERATOR_SLASHED: u8 = 4; /// PDA: `["challenge", account, commit_id, challenger]`. /// Created by `RaiseChallenge`. diff --git a/src/v2/processor/fraud_proofs/mod.rs b/src/v2/processor/fraud_proofs/mod.rs index 5d10fc64..66ce0897 100644 --- a/src/v2/processor/fraud_proofs/mod.rs +++ b/src/v2/processor/fraud_proofs/mod.rs @@ -5,6 +5,7 @@ mod challenger_reveal; mod finalize_commitment; mod post_commitment; mod raise_challenge; +mod resolve_dispute; mod write_state_buffer; pub use approve_commitment::*; @@ -12,4 +13,5 @@ pub use challenger_reveal::*; pub use finalize_commitment::*; pub use post_commitment::*; pub use raise_challenge::*; +pub use resolve_dispute::*; pub use write_state_buffer::*; diff --git a/src/v2/processor/fraud_proofs/resolve_dispute.rs b/src/v2/processor/fraud_proofs/resolve_dispute.rs new file mode 100644 index 00000000..2aceb9c2 --- /dev/null +++ b/src/v2/processor/fraud_proofs/resolve_dispute.rs @@ -0,0 +1,416 @@ +use dlp_api::{ + error::DlpError, + v2::{ + pda::{ + CHALLENGE_SEED, OPERATOR_BOND_SEED, PENDING_COMMITMENT_SEED, + PROTOCOL_CONFIG_SEED, + }, + Challenge, OperatorBond, OperatorStatus, PendingCommitment, + ProtocolConfig, ResolveDisputeArgs, SelectedVerifier, + CHALLENGE_OUTCOME_CHALLENGER_CORRECT_OPERATOR_SLASHED, + CHALLENGE_OUTCOME_NONE, + CHALLENGE_OUTCOME_OPERATOR_CORRECT_CHALLENGER_SLASHED, + CHALLENGE_STATUS_AWAITING_RESOLVER, CHALLENGE_STATUS_TERMINAL, + DISPUTE_DECISION_CHALLENGER_STATE_CORRECT, + DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + PENDING_COMMITMENT_STATUS_AWAITING_DISPUTE_RESOLUTION, + PENDING_COMMITMENT_STATUS_RESOLVED_CHALLENGER, + PENDING_COMMITMENT_STATUS_RESOLVED_OPERATOR, + RESOLVED_STATE_SOURCE_CHALLENGER_REVEAL, + RESOLVED_STATE_SOURCE_OPERATOR_COMMITMENT, + }, +}; +use pinocchio::{error::ProgramError, AccountView, ProgramResult}; +use wheels::{ + layout::{Decodable, Encodable}, + require_eq, require_eq_keys, require_n_accounts, require_signer, +}; + +use crate::requires::{require_initialized_pda, require_owned_pda}; + +/// Apply resolver decision for one v2 challenge. +/// +/// Accounts: +/// 0: `[signer]` resolver identity from ProtocolConfig +/// 1: `[writable]` Challenge PDA +/// 2: `[writable]` PendingCommitment PDA +/// 3: `[writable]` OperatorBond PDA +/// 4: `[writable]` challenger identity and refund account +/// 5: `[]` ProtocolConfig PDA +/// 6: `[writable]` protocol fee vault +#[inline(never)] +pub fn process_resolve_dispute( + accounts: &[AccountView], + data: &[u8], +) -> ProgramResult { + let [ + resolver, // force multi-line + challenge, + pending_commitment, + operator_bond, + challenger, + protocol_config, + protocol_fee_vault, + ] = require_n_accounts!(accounts, 7); + + let args = ResolveDisputeArgs::decode(data)?; + + require_signer!(resolver); + if !challenge.is_writable() + || !pending_commitment.is_writable() + || !operator_bond.is_writable() + || !challenger.is_writable() + || !protocol_fee_vault.is_writable() + { + return Err(ProgramError::Immutable); + } + + require_owned_pda(challenge, &crate::fast::ID, "challenge")?; + require_owned_pda( + pending_commitment, + &crate::fast::ID, + "pending commitment", + )?; + require_owned_pda(operator_bond, &crate::fast::ID, "operator bond")?; + + let (configured_resolver, configured_fee_vault) = + load_protocol_config(protocol_config)?; + require_eq_keys!( + &configured_resolver, + resolver.address(), + DlpError::InvalidAuthority + ); + require_eq_keys!( + &configured_fee_vault, + protocol_fee_vault.address(), + ProgramError::InvalidAccountData + ); + + let mut pending = load_pending_commitment(pending_commitment)?; + let mut challenge_state = load_challenge(challenge)?; + let mut operator_bond_state = load_operator_bond(operator_bond, &pending)?; + + validate_pending_commitment(&pending, pending_commitment, challenge)?; + validate_challenge( + &challenge_state, + challenge, + pending_commitment, + challenger, + &pending, + )?; + + // CHECKPOINT: MVP dispute economics are intentionally immediate and simple: + // operator-correct slashes the challenger stake to the fee vault; + // challenger-correct refunds that stake and slashes the operator's full + // recorded stake to the fee vault. No payout timelock is created here. + match args.decision() { + DISPUTE_DECISION_OPERATOR_STATE_CORRECT => { + move_lamports( + challenge, + protocol_fee_vault, + challenge_state.challenger_stake_lamports, + )?; + + resolve_pending_commitment( + &mut pending, + PENDING_COMMITMENT_STATUS_RESOLVED_OPERATOR, + RESOLVED_STATE_SOURCE_OPERATOR_COMMITMENT, + ); + challenge_state.status = CHALLENGE_STATUS_TERMINAL; + challenge_state.outcome = + CHALLENGE_OUTCOME_OPERATOR_CORRECT_CHALLENGER_SLASHED; + } + DISPUTE_DECISION_CHALLENGER_STATE_CORRECT => { + move_lamports( + challenge, + challenger, + challenge_state.challenger_stake_lamports, + )?; + move_lamports( + operator_bond, + protocol_fee_vault, + operator_bond_state.stake_lamports, + )?; + + operator_bond_state.stake_lamports = 0; + operator_bond_state.locked_lamports = 0; + operator_bond_state.status = OperatorStatus::Slashed.value(); + operator_bond_state.withdraw_requested_slot = None; + + resolve_pending_commitment( + &mut pending, + PENDING_COMMITMENT_STATUS_RESOLVED_CHALLENGER, + RESOLVED_STATE_SOURCE_CHALLENGER_REVEAL, + ); + challenge_state.status = CHALLENGE_STATUS_TERMINAL; + challenge_state.outcome = + CHALLENGE_OUTCOME_CHALLENGER_CORRECT_OPERATOR_SLASHED; + } + _ => return Err(ProgramError::InvalidInstructionData), + } + + challenge_state.encode_to(challenge.try_borrow_mut()?.as_mut())?; + pending.encode_to(pending_commitment.try_borrow_mut()?.as_mut())?; + operator_bond_state.encode_to(operator_bond.try_borrow_mut()?.as_mut())?; + + Ok(()) +} + +fn load_protocol_config( + protocol_config: &AccountView, +) -> Result<(dlp_api::compat::Pubkey, dlp_api::compat::Pubkey), ProgramError> { + require_initialized_pda( + protocol_config, + &[PROTOCOL_CONFIG_SEED], + &crate::fast::ID, + false, + "protocol config", + )?; + + let data = protocol_config.try_borrow()?; + let state = ProtocolConfig::decode(data.as_ref())?; + if state.discriminator() != ProtocolConfig::DISCRIMINATOR { + return Err(ProgramError::InvalidAccountData); + } + require_eq!(state.paused(), false, ProgramError::InvalidAccountData); + + Ok((*state.resolver(), *state.protocol_fee_vault())) +} + +fn load_pending_commitment( + pending_commitment: &AccountView, +) -> Result { + let pending_data = pending_commitment.try_borrow()?; + let pending_view = PendingCommitment::decode(pending_data.as_ref())?; + + if pending_view.discriminator() != PendingCommitment::DISCRIMINATOR { + return Err(ProgramError::InvalidAccountData); + } + + Ok(PendingCommitment { + discriminator: PendingCommitment::DISCRIMINATOR, + status: pending_view.status(), + operator_identity: *pending_view.operator_identity(), + operator_bond: *pending_view.operator_bond(), + account_pubkey: *pending_view.account_pubkey(), + commit_id: pending_view.commit_id(), + delegation_record: *pending_view.delegation_record(), + da_pointer_hash: *pending_view.da_pointer_hash(), + account_state_hash: *pending_view.account_state_hash(), + data_hash: *pending_view.data_hash(), + lamports: pending_view.lamports(), + owner: *pending_view.owner(), + state_commitment_hash: *pending_view.state_commitment_hash(), + verifier_registry: *pending_view.verifier_registry(), + challenge_window_id: pending_view.challenge_window_id(), + posted_slot: pending_view.posted_slot(), + activation_slot: pending_view.activation_slot(), + challenge_window_end_slot: pending_view.challenge_window_end_slot(), + approval_count: pending_view.approval_count(), + approval_threshold: pending_view.approval_threshold(), + active_challenge: pending_view.active_challenge().cloned(), + resolved_state_source: pending_view.resolved_state_source(), + er_slot: pending_view.er_slot(), + _pad_before_selected_verifiers: [0; 7], + selected_verifiers: pending_view + .selected_verifiers() + .iter() + .map(|verifier| SelectedVerifier { + verifier_identity: *verifier.verifier_identity(), + approved: verifier.approved(), + _pad_after_approved: [0; 7], + }) + .collect(), + }) +} + +fn load_challenge(challenge: &AccountView) -> Result { + let challenge_data = challenge.try_borrow()?; + let challenge_view = Challenge::decode(challenge_data.as_ref())?; + + if challenge_view.discriminator() != Challenge::DISCRIMINATOR { + return Err(ProgramError::InvalidAccountData); + } + + Ok(Challenge { + discriminator: Challenge::DISCRIMINATOR, + status: challenge_view.status(), + outcome: challenge_view.outcome(), + _pad_after_outcome: [0; 6], + pending_commitment: *challenge_view.pending_commitment(), + challenger_identity: *challenge_view.challenger_identity(), + state_commitment_hash: *challenge_view.state_commitment_hash(), + challenge_hash: *challenge_view.challenge_hash(), + challenger_lamports: challenge_view.challenger_lamports(), + challenger_owner: *challenge_view.challenger_owner(), + challenger_data_hash: *challenge_view.challenger_data_hash(), + challenger_state_buffer: *challenge_view.challenger_state_buffer(), + challenger_stake_lamports: challenge_view.challenger_stake_lamports(), + raised_slot: challenge_view.raised_slot(), + reveal_deadline_slot: challenge_view.reveal_deadline_slot(), + }) +} + +fn load_operator_bond( + operator_bond: &AccountView, + pending: &PendingCommitment, +) -> Result { + require_eq_keys!( + &pending.operator_bond, + operator_bond.address(), + ProgramError::InvalidAccountData + ); + require_initialized_pda( + operator_bond, + &[OPERATOR_BOND_SEED, pending.operator_identity.as_ref()], + &crate::fast::ID, + true, + "operator bond", + )?; + + let data = operator_bond.try_borrow()?; + let state = OperatorBond::decode(data.as_ref())?; + if state.discriminator() != OperatorBond::DISCRIMINATOR { + return Err(ProgramError::InvalidAccountData); + } + require_eq_keys!( + state.operator_identity(), + &pending.operator_identity, + DlpError::InvalidAuthority + ); + + Ok(OperatorBond { + discriminator: OperatorBond::DISCRIMINATOR, + bump: state.bump(), + operator_identity: *state.operator_identity(), + stake_lamports: state.stake_lamports(), + locked_lamports: state.locked_lamports(), + status: state.status(), + withdraw_requested_slot: state.withdraw_requested_slot(), + }) +} + +fn validate_pending_commitment( + pending: &PendingCommitment, + pending_commitment: &AccountView, + challenge: &AccountView, +) -> ProgramResult { + let commit_id_bytes = pending.commit_id.to_le_bytes(); + require_initialized_pda( + pending_commitment, + &[ + PENDING_COMMITMENT_SEED, + pending.account_pubkey.as_ref(), + &commit_id_bytes, + ], + &crate::fast::ID, + true, + "pending commitment", + )?; + + require_eq!( + pending.status, + PENDING_COMMITMENT_STATUS_AWAITING_DISPUTE_RESOLUTION, + ProgramError::InvalidInstructionData + ); + let active_challenge = pending + .active_challenge + .as_ref() + .ok_or(ProgramError::InvalidInstructionData)?; + require_eq_keys!( + active_challenge, + challenge.address(), + ProgramError::InvalidInstructionData + ); + require_eq!( + pending.resolved_state_source.is_none(), + true, + ProgramError::InvalidInstructionData + ); + + Ok(()) +} + +fn validate_challenge( + challenge_state: &Challenge, + challenge: &AccountView, + pending_commitment: &AccountView, + challenger: &AccountView, + pending: &PendingCommitment, +) -> ProgramResult { + let commit_id_bytes = pending.commit_id.to_le_bytes(); + require_initialized_pda( + challenge, + &[ + CHALLENGE_SEED, + pending.account_pubkey.as_ref(), + &commit_id_bytes, + challenger.address().as_ref(), + ], + &crate::fast::ID, + true, + "challenge", + )?; + + require_eq!( + challenge_state.status, + CHALLENGE_STATUS_AWAITING_RESOLVER, + ProgramError::InvalidInstructionData + ); + require_eq!( + challenge_state.outcome, + CHALLENGE_OUTCOME_NONE, + ProgramError::InvalidInstructionData + ); + require_eq_keys!( + &challenge_state.pending_commitment, + pending_commitment.address(), + ProgramError::InvalidInstructionData + ); + require_eq_keys!( + &challenge_state.challenger_identity, + challenger.address(), + DlpError::InvalidAuthority + ); + require_eq!( + &challenge_state.state_commitment_hash, + &pending.state_commitment_hash, + ProgramError::InvalidInstructionData + ); + + Ok(()) +} + +fn resolve_pending_commitment( + pending: &mut PendingCommitment, + status: u8, + resolved_state_source: u8, +) { + pending.status = status; + pending.active_challenge = None; + pending.resolved_state_source = Some(resolved_state_source); +} + +fn move_lamports( + from: &AccountView, + to: &AccountView, + amount: u64, +) -> ProgramResult { + if amount == 0 { + return Ok(()); + } + + let from_lamports = from + .lamports() + .checked_sub(amount) + .ok_or(DlpError::Overflow)?; + let to_lamports = to + .lamports() + .checked_add(amount) + .ok_or(DlpError::Overflow)?; + + from.set_lamports(from_lamports); + to.set_lamports(to_lamports); + + Ok(()) +} diff --git a/src/v2/processor/mod.rs b/src/v2/processor/mod.rs index 68c9cbec..e25725f6 100644 --- a/src/v2/processor/mod.rs +++ b/src/v2/processor/mod.rs @@ -48,5 +48,8 @@ pub fn process_instruction( DlpV2Instruction::ChallengerReveal => { process_challenger_reveal(accounts, data) } + DlpV2Instruction::ResolveDispute => { + process_resolve_dispute(accounts, data) + } } } diff --git a/tests/test_v2_resolve_dispute.rs b/tests/test_v2_resolve_dispute.rs new file mode 100644 index 00000000..0576b3d7 --- /dev/null +++ b/tests/test_v2_resolve_dispute.rs @@ -0,0 +1,798 @@ +use dlp_api::{ + pda::{ + delegation_metadata_pda_from_delegated_account, + delegation_record_pda_from_delegated_account, fees_vault_pda, + }, + v2::{ + instruction_builder::{ + challenger_reveal, post_commitment, raise_challenge, + register_operator, register_verifier, resolve_dispute, + update_verifier_registry, write_state_buffer, + }, + pda::{challenge_pda, operator_bond_pda, pending_commitment_pda}, + Challenge, ChallengerRevealArgs, OperatorBond, OperatorStatus, + PendingCommitment, PostCommitmentArgs, RaiseChallengeArgs, + RegisterOperatorArgs, RegisterVerifierArgs, ResolveDisputeArgs, + WriteStateBufferArgs, + CHALLENGE_OUTCOME_CHALLENGER_CORRECT_OPERATOR_SLASHED, + CHALLENGE_OUTCOME_OPERATOR_CORRECT_CHALLENGER_SLASHED, + CHALLENGE_STATUS_AWAITING_RESOLVER, CHALLENGE_STATUS_TERMINAL, + DISPUTE_DECISION_CHALLENGER_STATE_CORRECT, + DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + PENDING_COMMITMENT_STATUS_AWAITING_CHALLENGER_REVEAL, + PENDING_COMMITMENT_STATUS_AWAITING_DISPUTE_RESOLUTION, + PENDING_COMMITMENT_STATUS_RESOLVED_CHALLENGER, + PENDING_COMMITMENT_STATUS_RESOLVED_OPERATOR, + RESOLVED_STATE_SOURCE_CHALLENGER_REVEAL, + RESOLVED_STATE_SOURCE_OPERATOR_COMMITMENT, + VERIFIER_REGISTRY_ACTION_ADD, + }, +}; +use solana_program::{native_token::LAMPORTS_PER_SOL, rent::Rent}; +use solana_program_test::{ + BanksClientError, ProgramTest, ProgramTestBanksClientExt, + ProgramTestContext, +}; +use solana_sdk::{ + account::Account, + hash::Hash, + instruction::Instruction, + pubkey::Pubkey, + signature::{Keypair, Signer}, + transaction::Transaction, +}; +use solana_sdk_ids::system_program; +use wheels::layout::Decodable; + +mod fixtures; + +use crate::fixtures::{ + create_delegation_metadata_data, create_delegation_record_data, + v2::{initialize_protocol_config, valid_protocol_config_args}, +}; + +const CHALLENGE_STAKE: u64 = 10_000; +const OPERATOR_STAKE: u64 = 50_000; + +#[tokio::test] +async fn test_resolve_dispute_operator_correct_slashes_challenger_and_selects_operator( +) { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + let fee_vault_before = + account_lamports(&mut env.context, fees_vault_pda()).await; + let challenger_before = + account_lamports(&mut env.context, env.challenger.pubkey()).await; + let operator_bond_before = read_operator_bond(&mut env).await; + + resolve_v2_dispute( + &mut env, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + }, + ) + .await + .unwrap(); + + let challenge = read_challenge(&mut env).await; + assert_eq!(challenge.status, CHALLENGE_STATUS_TERMINAL); + assert_eq!( + challenge.outcome, + CHALLENGE_OUTCOME_OPERATOR_CORRECT_CHALLENGER_SLASHED + ); + assert_eq!( + challenge.account_lamports, + Rent::default().minimum_balance(Challenge::DATA_LEN) + ); + + let pending = read_pending_commitment(&mut env).await; + assert_eq!(pending.status, PENDING_COMMITMENT_STATUS_RESOLVED_OPERATOR); + assert_eq!(pending.active_challenge, None); + assert_eq!( + pending.resolved_state_source, + Some(RESOLVED_STATE_SOURCE_OPERATOR_COMMITMENT) + ); + assert_eq!( + account_lamports(&mut env.context, fees_vault_pda()).await, + fee_vault_before + CHALLENGE_STAKE + ); + assert_eq!( + account_lamports(&mut env.context, env.challenger.pubkey()).await, + challenger_before + ); + + let operator_bond_after = read_operator_bond(&mut env).await; + assert_eq!(operator_bond_after.status, operator_bond_before.status); + assert_eq!( + operator_bond_after.stake_lamports, + operator_bond_before.stake_lamports + ); + assert_eq!( + operator_bond_after.account_lamports, + operator_bond_before.account_lamports + ); +} + +#[tokio::test] +async fn test_resolve_dispute_challenger_correct_refunds_challenger_and_slashes_operator( +) { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + let fee_vault_before = + account_lamports(&mut env.context, fees_vault_pda()).await; + let challenger_before = + account_lamports(&mut env.context, env.challenger.pubkey()).await; + let operator_bond_before = read_operator_bond(&mut env).await; + + resolve_v2_dispute( + &mut env, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_CHALLENGER_STATE_CORRECT, + }, + ) + .await + .unwrap(); + + let challenge = read_challenge(&mut env).await; + assert_eq!(challenge.status, CHALLENGE_STATUS_TERMINAL); + assert_eq!( + challenge.outcome, + CHALLENGE_OUTCOME_CHALLENGER_CORRECT_OPERATOR_SLASHED + ); + assert_eq!( + challenge.account_lamports, + Rent::default().minimum_balance(Challenge::DATA_LEN) + ); + + let pending = read_pending_commitment(&mut env).await; + assert_eq!( + pending.status, + PENDING_COMMITMENT_STATUS_RESOLVED_CHALLENGER + ); + assert_eq!(pending.active_challenge, None); + assert_eq!( + pending.resolved_state_source, + Some(RESOLVED_STATE_SOURCE_CHALLENGER_REVEAL) + ); + assert_eq!( + account_lamports(&mut env.context, env.challenger.pubkey()).await, + challenger_before + CHALLENGE_STAKE + ); + assert_eq!( + account_lamports(&mut env.context, fees_vault_pda()).await, + fee_vault_before + OPERATOR_STAKE + ); + + let operator_bond_after = read_operator_bond(&mut env).await; + assert_eq!(operator_bond_after.status, OperatorStatus::Slashed.value()); + assert_eq!(operator_bond_after.stake_lamports, 0); + assert_eq!(operator_bond_after.locked_lamports, 0); + assert_eq!( + operator_bond_after.account_lamports, + operator_bond_before.account_lamports - OPERATOR_STAKE + ); +} + +#[tokio::test] +async fn test_resolve_dispute_fails_with_wrong_resolver() { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + let ix = resolve_dispute( + env.operator.pubkey(), + env.operator.pubkey(), + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + }, + ); + + assert!(process_ix(&mut env.context, ix, &[&env.operator]) + .await + .is_err()); +} + +#[tokio::test] +async fn test_resolve_dispute_fails_before_mismatched_reveal() { + let mut env = setup_resolve_dispute_env().await; + post_v2_commitment(&mut env).await.unwrap(); + + let data_hash = account_data_hash(&[4, 3, 2, 1]); + let reveal_args = valid_reveal_args( + env.committed_lamports, + env.committed_owner, + data_hash, + ); + raise_v2_challenge_for_reveal(&mut env, &reveal_args, CHALLENGE_STAKE) + .await + .unwrap(); + + let pending = read_pending_commitment(&mut env).await; + assert_eq!( + pending.status, + PENDING_COMMITMENT_STATUS_AWAITING_CHALLENGER_REVEAL + ); + + assert!(resolve_v2_dispute( + &mut env, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + }, + ) + .await + .is_err()); +} + +#[tokio::test] +async fn test_resolve_dispute_fails_with_wrong_operator_bond() { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + let mut ix = resolve_dispute( + env.resolver.pubkey(), + env.operator.pubkey(), + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + }, + ); + ix.accounts[3].pubkey = operator_bond_pda(&env.other_operator.pubkey()); + + assert!(process_ix(&mut env.context, ix, &[&env.resolver]) + .await + .is_err()); +} + +#[tokio::test] +async fn test_resolve_dispute_fails_with_wrong_fee_vault() { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + let mut ix = resolve_dispute( + env.resolver.pubkey(), + env.operator.pubkey(), + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + ResolveDisputeArgs { + decision: DISPUTE_DECISION_OPERATOR_STATE_CORRECT, + }, + ); + ix.accounts[6].pubkey = env.challenger.pubkey(); + + assert!(process_ix(&mut env.context, ix, &[&env.resolver]) + .await + .is_err()); +} + +#[tokio::test] +async fn test_resolve_dispute_fails_with_invalid_decision() { + let mut env = setup_resolve_dispute_env().await; + open_dispute(&mut env).await; + + assert!( + resolve_v2_dispute(&mut env, ResolveDisputeArgs { decision: 99 }) + .await + .is_err() + ); +} + +struct ResolveDisputeEnv { + context: ProgramTestContext, + resolver: Keypair, + operator: Keypair, + other_operator: Keypair, + challenger: Keypair, + delegated_account: Pubkey, + committed_owner: Pubkey, + committed_lamports: u64, + commit_id: u64, +} + +async fn setup_resolve_dispute_env() -> ResolveDisputeEnv { + let mut program_test = ProgramTest::new("dlp", dlp_api::ID, None); + program_test.prefer_bpf(true); + + let authority = Keypair::new(); + let resolver = Keypair::new(); + let operator = Keypair::new(); + let other_operator = Keypair::new(); + let verifier = Keypair::new(); + let challenger = Keypair::new(); + let delegated_account = Pubkey::new_unique(); + let committed_owner = Pubkey::new_unique(); + let commit_id = 1; + let operator_state_data = vec![9, 8, 7, 6, 5]; + let record_lamports = LAMPORTS_PER_SOL; + let committed_lamports = LAMPORTS_PER_SOL; + + add_lamport_account(&mut program_test, authority.pubkey()); + add_lamport_account(&mut program_test, resolver.pubkey()); + add_lamport_account(&mut program_test, operator.pubkey()); + add_lamport_account(&mut program_test, other_operator.pubkey()); + add_lamport_account(&mut program_test, verifier.pubkey()); + add_lamport_account(&mut program_test, challenger.pubkey()); + add_protocol_fee_vault(&mut program_test); + + program_test.add_account( + delegated_account, + Account { + lamports: record_lamports, + data: vec![1, 2], + owner: dlp_api::ID, + executable: false, + rent_epoch: 0, + }, + ); + program_test.add_account( + delegation_record_pda_from_delegated_account(&delegated_account), + Account { + lamports: LAMPORTS_PER_SOL, + data: create_delegation_record_data( + operator.pubkey(), + committed_owner, + Some(record_lamports), + ), + owner: dlp_api::ID, + executable: false, + rent_epoch: 0, + }, + ); + program_test.add_account( + delegation_metadata_pda_from_delegated_account(&delegated_account), + Account { + lamports: LAMPORTS_PER_SOL, + data: create_delegation_metadata_data( + authority.pubkey(), + &[], + false, + ), + owner: dlp_api::ID, + executable: false, + rent_epoch: 0, + }, + ); + + let mut context = program_test.start_with_context().await; + let mut config_args = valid_protocol_config_args(); + config_args.resolver = resolver.pubkey(); + initialize_protocol_config( + &context.banks_client, + &context.payer, + &authority, + context.last_blockhash, + config_args.clone(), + ) + .await; + + register_v2_operator(&mut context, &operator, &authority, OPERATOR_STAKE) + .await + .unwrap(); + register_v2_operator( + &mut context, + &other_operator, + &authority, + OPERATOR_STAKE, + ) + .await + .unwrap(); + register_and_add_v2_verifier( + &mut context, + &verifier, + &authority, + config_args.min_verifier_bond, + ) + .await + .unwrap(); + + write_v2_state_buffer( + &mut context, + &operator, + delegated_account, + WriteStateBufferArgs { + commit_id, + total_len: operator_state_data.len() as u32, + offset: 0, + chunk: operator_state_data.clone(), + }, + ) + .await + .unwrap(); + + ResolveDisputeEnv { + context, + resolver, + operator, + other_operator, + challenger, + delegated_account, + committed_owner, + committed_lamports, + commit_id, + } +} + +async fn open_dispute(env: &mut ResolveDisputeEnv) -> ChallengerRevealArgs { + post_v2_commitment(env).await.unwrap(); + + let challenger_data = vec![4, 3, 2, 1]; + let reveal_args = valid_reveal_args( + env.committed_lamports, + env.committed_owner, + account_data_hash(&challenger_data), + ); + write_challenger_state_buffer(env, challenger_data) + .await + .unwrap(); + raise_v2_challenge_for_reveal(env, &reveal_args, CHALLENGE_STAKE) + .await + .unwrap(); + reveal_v2_challenge(env, reveal_args.clone()).await.unwrap(); + + let pending = read_pending_commitment(env).await; + assert_eq!( + pending.status, + PENDING_COMMITMENT_STATUS_AWAITING_DISPUTE_RESOLUTION + ); + let challenge = read_challenge(env).await; + assert_eq!(challenge.status, CHALLENGE_STATUS_AWAITING_RESOLVER); + + reveal_args +} + +async fn post_v2_commitment( + env: &mut ResolveDisputeEnv, +) -> Result<(), BanksClientError> { + let ix = post_commitment( + env.operator.pubkey(), + env.delegated_account, + PostCommitmentArgs { + commit_id: env.commit_id, + lamports: env.committed_lamports, + owner: env.committed_owner, + da_pointer_hash: [9; 32], + er_slot: Some(42), + }, + ); + + process_ix(&mut env.context, ix, &[&env.operator]).await +} + +async fn raise_v2_challenge_for_reveal( + env: &mut ResolveDisputeEnv, + reveal_args: &ChallengerRevealArgs, + stake_lamports: u64, +) -> Result<(), BanksClientError> { + let pending = read_pending_commitment(env).await; + let ix = raise_challenge( + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + RaiseChallengeArgs { + state_commitment_hash: pending.state_commitment_hash, + challenge_hash: challenge_hash( + pending.state_commitment_hash, + env.operator.pubkey(), + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + reveal_args, + ), + stake_lamports, + }, + ); + + process_ix(&mut env.context, ix, &[&env.challenger]).await +} + +async fn reveal_v2_challenge( + env: &mut ResolveDisputeEnv, + args: ChallengerRevealArgs, +) -> Result<(), BanksClientError> { + let ix = challenger_reveal( + env.challenger.pubkey(), + env.operator.pubkey(), + env.delegated_account, + env.commit_id, + args, + ); + + process_ix(&mut env.context, ix, &[&env.challenger]).await +} + +async fn resolve_v2_dispute( + env: &mut ResolveDisputeEnv, + args: ResolveDisputeArgs, +) -> Result<(), BanksClientError> { + let ix = resolve_dispute( + env.resolver.pubkey(), + env.operator.pubkey(), + env.challenger.pubkey(), + env.delegated_account, + env.commit_id, + args, + ); + + process_ix(&mut env.context, ix, &[&env.resolver]).await +} + +async fn write_challenger_state_buffer( + env: &mut ResolveDisputeEnv, + data: Vec, +) -> Result<(), BanksClientError> { + write_v2_state_buffer( + &mut env.context, + &env.challenger, + env.delegated_account, + WriteStateBufferArgs { + commit_id: env.commit_id, + total_len: data.len() as u32, + offset: 0, + chunk: data, + }, + ) + .await +} + +async fn register_v2_operator( + context: &mut ProgramTestContext, + operator: &Keypair, + authority: &Keypair, + amount_lamports: u64, +) -> Result<(), BanksClientError> { + let ix = register_operator( + operator.pubkey(), + authority.pubkey(), + RegisterOperatorArgs { amount_lamports }, + ); + + process_ix(context, ix, &[operator, authority]).await +} + +async fn register_and_add_v2_verifier( + context: &mut ProgramTestContext, + verifier: &Keypair, + authority: &Keypair, + amount_lamports: u64, +) -> Result<(), BanksClientError> { + let ix = register_verifier( + verifier.pubkey(), + authority.pubkey(), + RegisterVerifierArgs { amount_lamports }, + ); + process_ix(context, ix, &[verifier, authority]).await?; + + let ix = update_verifier_registry( + authority.pubkey(), + verifier.pubkey(), + dlp_api::v2::UpdateVerifierRegistryArgs { + action: VERIFIER_REGISTRY_ACTION_ADD, + weight: 1, + }, + ); + + process_ix(context, ix, &[authority]).await +} + +async fn write_v2_state_buffer( + context: &mut ProgramTestContext, + authority: &Keypair, + account: Pubkey, + args: WriteStateBufferArgs, +) -> Result<(), BanksClientError> { + let ix = write_state_buffer( + context.payer.pubkey(), + authority.pubkey(), + account, + args, + ); + + process_ix(context, ix, &[authority]).await +} + +async fn process_ix( + context: &mut ProgramTestContext, + ix: Instruction, + signers: &[&Keypair], +) -> Result<(), BanksClientError> { + let latest_blockhash: Hash = + context.banks_client.get_latest_blockhash().await.unwrap(); + let blockhash = context + .banks_client + .get_new_latest_blockhash(&latest_blockhash) + .await + .unwrap(); + let tx = { + let mut all_signers = Vec::with_capacity(signers.len() + 1); + all_signers.push(&context.payer); + all_signers.extend_from_slice(signers); + + Transaction::new_signed_with_payer( + &[ix], + Some(&context.payer.pubkey()), + &all_signers, + blockhash, + ) + }; + + context.banks_client.process_transaction(tx).await +} + +struct PendingCommitmentSnapshot { + status: u8, + active_challenge: Option, + resolved_state_source: Option, + state_commitment_hash: [u8; 32], +} + +async fn read_pending_commitment( + env: &mut ResolveDisputeEnv, +) -> PendingCommitmentSnapshot { + let account = env + .context + .banks_client + .get_account(pending_commitment_pda( + &env.delegated_account, + env.commit_id, + )) + .await + .unwrap() + .unwrap(); + + let pending = + ::decode(&account.data).unwrap(); + + PendingCommitmentSnapshot { + status: pending.status(), + active_challenge: pending.active_challenge().cloned(), + resolved_state_source: pending.resolved_state_source(), + state_commitment_hash: *pending.state_commitment_hash(), + } +} + +struct ChallengeSnapshot { + status: u8, + outcome: u8, + account_lamports: u64, +} + +async fn read_challenge(env: &mut ResolveDisputeEnv) -> ChallengeSnapshot { + let account = env + .context + .banks_client + .get_account(challenge_address(env)) + .await + .unwrap() + .unwrap(); + + let challenge = ::decode(&account.data).unwrap(); + + ChallengeSnapshot { + status: challenge.status(), + outcome: challenge.outcome(), + account_lamports: account.lamports, + } +} + +struct OperatorBondSnapshot { + status: u8, + stake_lamports: u64, + locked_lamports: u64, + account_lamports: u64, +} + +async fn read_operator_bond( + env: &mut ResolveDisputeEnv, +) -> OperatorBondSnapshot { + let account = env + .context + .banks_client + .get_account(operator_bond_pda(&env.operator.pubkey())) + .await + .unwrap() + .unwrap(); + + let operator_bond = + ::decode(&account.data).unwrap(); + + OperatorBondSnapshot { + status: operator_bond.status(), + stake_lamports: operator_bond.stake_lamports(), + locked_lamports: operator_bond.locked_lamports(), + account_lamports: account.lamports, + } +} + +async fn account_lamports( + context: &mut ProgramTestContext, + pubkey: Pubkey, +) -> u64 { + context + .banks_client + .get_account(pubkey) + .await + .unwrap() + .unwrap() + .lamports +} + +fn add_lamport_account(program_test: &mut ProgramTest, pubkey: Pubkey) { + program_test.add_account( + pubkey, + Account { + lamports: LAMPORTS_PER_SOL, + data: vec![], + owner: system_program::id(), + executable: false, + rent_epoch: 0, + }, + ); +} + +fn add_protocol_fee_vault(program_test: &mut ProgramTest) { + program_test.add_account( + fees_vault_pda(), + Account { + lamports: LAMPORTS_PER_SOL, + data: vec![0; 8], + owner: dlp_api::ID, + executable: false, + rent_epoch: 0, + }, + ); +} + +fn valid_reveal_args( + lamports: u64, + owner: Pubkey, + data_hash: [u8; 32], +) -> ChallengerRevealArgs { + ChallengerRevealArgs { + lamports, + owner, + data_hash, + salt: [7; 32], + } +} + +fn challenge_address(env: &ResolveDisputeEnv) -> Pubkey { + challenge_pda( + &env.delegated_account, + env.commit_id, + &env.challenger.pubkey(), + ) +} + +fn account_data_hash(data: &[u8]) -> [u8; 32] { + solana_sha256_hasher::hashv(&[b"magicblock.account_data.v1", data]) + .to_bytes() +} + +fn challenge_hash( + state_commitment_hash: [u8; 32], + operator: Pubkey, + challenger: Pubkey, + account: Pubkey, + commit_id: u64, + args: &ChallengerRevealArgs, +) -> [u8; 32] { + solana_sha256_hasher::hashv(&[ + b"magicblock.challenge.v1", + &state_commitment_hash, + operator.as_ref(), + challenger.as_ref(), + account.as_ref(), + &commit_id.to_le_bytes(), + &args.lamports.to_le_bytes(), + args.owner.as_ref(), + &args.data_hash, + &args.salt, + ]) + .to_bytes() +}