1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
#![allow(deprecated)]

use crate::*;

#[repr(u8)]
#[derive(
    Copy, Clone, Default, Debug, Eq, PartialEq, AnchorSerialize, AnchorDeserialize, InitSpace,
)]
pub enum ServiceStatus {
    #[default]
    None = 0, // 0
    Active,
    Pending,
    NonExecutable,
}
impl ServiceStatus {
    pub fn is_active(&self) -> bool {
        matches!(self, ServiceStatus::Active)
    }
}
impl From<ServiceStatus> for u8 {
    fn from(value: ServiceStatus) -> Self {
        match value {
            ServiceStatus::Active => 1,
            ServiceStatus::Pending => 2,
            ServiceStatus::NonExecutable => 3,
            _ => 0,
        }
    }
}
impl From<u8> for ServiceStatus {
    fn from(value: u8) -> Self {
        match value {
            1 => ServiceStatus::Active,
            2 => ServiceStatus::Pending,
            3 => ServiceStatus::NonExecutable,
            _ => ServiceStatus::default(),
        }
    }
}

#[repr(u8)]
#[derive(
    Copy, Clone, Default, Debug, Eq, PartialEq, AnchorSerialize, AnchorDeserialize, InitSpace,
)]
pub enum EnclaveRotationStatus {
    #[default]
    None = 0, // 0
    InProgress,
}
impl EnclaveRotationStatus {
    pub fn is_in_progress(&self) -> bool {
        matches!(self, EnclaveRotationStatus::InProgress)
    }
}
impl From<EnclaveRotationStatus> for u8 {
    fn from(value: EnclaveRotationStatus) -> Self {
        match value {
            EnclaveRotationStatus::InProgress => 1,
            _ => 0,
        }
    }
}
impl From<u8> for EnclaveRotationStatus {
    fn from(value: u8) -> Self {
        match value {
            1 => EnclaveRotationStatus::InProgress,
            _ => EnclaveRotationStatus::default(),
        }
    }
}

/// A [`FunctionServiceAccountData`] represents a long running function for a given [`FunctionAccountData`].
/// A service determines the execution parameters (environment variables, oracle config, cost).
// #[account]
#[derive(AnchorDeserialize, AnchorSerialize, Clone, Debug, PartialEq)]
pub struct FunctionServiceAccountData {
    // Rpc filtering over att_queue, servie_worker, status, and is_disabled to get active services for a given service worker
    /// The Attestation Queue for this service, responsible for verifying any SGX quotes.
    pub attestation_queue: Pubkey,
    /// The service workerr that is executing the managed service.
    pub service_worker: Pubkey,

    /// The status of the current service.
    /// 0 = disabled, 1 = active.
    pub status: ServiceStatus,

    // Disabled Config
    /// Flag to disable the service and prevent new verification requests.
    pub is_disabled: ResourceLevel,

    /// Whether the enclave is in progress for being rotated. Used for quote verifiers to filter and find pending verification requests.
    pub enclave_rotation_status: EnclaveRotationStatus,

    /// The last reported error code if the most recent response was a failure
    pub error_status: u8,

    // Accounts
    /// Signer allowed to manage the service.
    pub authority: Pubkey,
    /// The pubkey of the [`FunctionAccountData`] that this service belongs to.
    pub function: Pubkey,
    // The SwitchboardWallet that manages the escrow. A single SwitchboardWallet can support many routines.
    pub escrow_wallet: Pubkey,
    /// The TokenAccount with funds for the escrow.
    pub escrow_token_wallet: Pubkey,

    // Metadata
    /// The name of the service for easier identification.
    pub name: [u8; 64],
    /// The metadata of the service for easier identification.
    pub metadata: [u8; 256],
    /// The unix timestamp when the service was created.
    pub created_at: i64,
    /// The unix timestamp when the service was last updated.
    pub updated_at: i64,

    // Enclave
    /// Represents the state of the quote verifiers enclave.
    pub enclave: BorshQuote,
    /// The previous verified quote. Used to facilitate smooth transitions during signer rotations.
    pub previous_enclave: BorshQuote,
    /// The pending [`Quote`] indicating a signer rotation is in-progress.
    pub pending_enclave: BorshQuote,
    /// The timestamp when the signer was last rotated.
    pub last_rotation_timestamp: i64,
    /// The index on the queue of the verifier that is assigned to verify the SGX quote.
    pub queue_idx: u32,

    // Container Params
    /// The maximum number of bytes to pass to the container params.
    pub max_container_params_len: u32,
    /// Hash of the serialized container_params to prevent RPC tampering.
    /// Should be verified within your function to ensure you are using the correct parameters.
    pub container_params_hash: [u8; 32],
    /// The stringified container params to pass to the function.
    pub container_params: Vec<u8>,

    // Execution
    /// The size of the enclave to reserve, in bytes.
    pub enclave_size: u64,
    ///
    pub cpu: u64,
    /// Reserved.
    pub _ebuf: [u8; 512],
}

impl Default for FunctionServiceAccountData {
    fn default() -> Self {
        Self {
            attestation_queue: Pubkey::default(),
            service_worker: Pubkey::default(),

            status: ServiceStatus::None,
            is_disabled: ResourceLevel::None,
            enclave_rotation_status: EnclaveRotationStatus::None,
            error_status: 0,

            // _padding1: [0u8; 3],
            authority: Pubkey::default(),
            function: Pubkey::default(),
            escrow_wallet: Pubkey::default(),
            escrow_token_wallet: Pubkey::default(),

            name: [0u8; 64],
            metadata: [0u8; 256],
            created_at: 0,
            updated_at: 0,

            enclave: BorshQuote::default(),
            previous_enclave: BorshQuote::default(),
            pending_enclave: BorshQuote::default(),
            last_rotation_timestamp: 0,
            queue_idx: 0,

            max_container_params_len: 0,
            container_params_hash: [0u8; 32],
            container_params: Vec::new(),

            enclave_size: 0,
            cpu: 0,

            _ebuf: [0u8; 512],
        }
    }
}

impl anchor_lang::AccountSerialize for FunctionServiceAccountData {
    fn try_serialize<W: std::io::Write>(&self, writer: &mut W) -> anchor_lang::Result<()> {
        if writer
            .write_all(&FunctionServiceAccountData::discriminator())
            .is_err()
        {
            return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
        }
        if AnchorSerialize::serialize(self, writer).is_err() {
            return Err(anchor_lang::error::ErrorCode::AccountDidNotSerialize.into());
        }
        Ok(())
    }
}

impl anchor_lang::AccountDeserialize for FunctionServiceAccountData {
    fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        if buf.len() < FunctionServiceAccountData::discriminator().len() {
            return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
        }
        let given_disc = &buf[..8];
        if FunctionServiceAccountData::discriminator() != given_disc {
            return Err(
                anchor_lang::error::Error::from(anchor_lang::error::AnchorError {
                    error_name: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch.name(),
                    error_code_number: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch
                        .into(),
                    error_msg: anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch
                        .to_string(),
                    error_origin: Some(anchor_lang::error::ErrorOrigin::Source(
                        anchor_lang::error::Source {
                            filename: "programs/attestation_program/src/lib.rs",
                            line: 1u32,
                        },
                    )),
                    compared_values: None,
                })
                .with_account_name("FunctionServiceAccountData"),
            );
        }
        Self::try_deserialize_unchecked(buf)
    }
    fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
        let mut data: &[u8] = &buf[8..];
        AnchorDeserialize::deserialize(&mut data)
            .map_err(|_| anchor_lang::error::ErrorCode::AccountDidNotDeserialize.into())
    }
}

impl Discriminator for FunctionServiceAccountData {
    const DISCRIMINATOR: [u8; 8] = [2, 2, 33, 121, 177, 19, 195, 195];
}

impl Owner for FunctionServiceAccountData {
    fn owner() -> Pubkey {
        *SWITCHBOARD_ATTESTATION_PROGRAM_ID
    }
}

impl FunctionServiceAccountData {
    /// Returns the amount of memory space required for a FunctionService account.
    ///
    /// # Arguments
    ///
    /// * `len` - An optional `u32` value representing the length of the container parameters vector.
    ///
    /// # Returns
    ///
    /// * `usize` - The total amount of memory space required for a FunctionService account.
    pub fn space(len: Option<u32>) -> usize {
        let base: usize = 8  // discriminator
            + solana_program::borsh::get_instance_packed_len(Box::<FunctionServiceAccountData>::default().as_ref()).unwrap();
        let vec_elements: usize = len.unwrap_or(DEFAULT_MAX_CONTAINER_PARAMS_LEN) as usize;
        base + vec_elements
    }

    /// Checks if the enclave is ready to rotate its quote.
    ///
    /// # Returns
    ///
    /// * `bool` - `true` if the routine is ready for quote rotation, `false` otherwise.
    pub fn ready_for_quote_rotation(&self, func_signer_rotation_interval: i64) -> bool {
        // Quote never needs to be manually rotated, only on startup
        if func_signer_rotation_interval < 0 {
            return false;
        }

        let now = unix_timestamp();

        // Not ready if quote rotation is in-progress and less than 2 minutes old
        if self.enclave_rotation_status == EnclaveRotationStatus::InProgress
            && 120 > now - self.pending_enclave.request_timestamp
        {
            return false;
        }

        let time_until_rotation = self.enclave.valid_until - now;

        // Quote is already stale and invalid
        if time_until_rotation < 0 {
            return true;
        }

        let rotation_interval = std::cmp::min(120, func_signer_rotation_interval);

        if rotation_interval > time_until_rotation {
            return true;
        }

        false
    }

    /// Sets the name of the routine.
    ///
    /// # Arguments
    ///
    /// * `name` - An optional vector of bytes representing the name of the routine.
    ///
    /// # Errors
    ///
    /// Returns an error if the length of the name is greater than 64 bytes.
    ///
    /// # Example
    ///
    /// ```
    /// # use crate::FunctionServiceAccountData;
    /// let mut routine = FunctionServiceAccountData::default();
    /// let name = Some(vec![72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
    /// routine.set_name(&name).unwrap();
    /// ```
    pub fn set_name(&mut self, name: &Option<Vec<u8>>) -> anchor_lang::Result<()> {
        if let Some(name) = name {
            if name.len() > 64 {
                return Err(error!(SwitchboardError::IllegalExecuteAttempt));
            }
            let mut name = name.clone();
            name.resize(64, 0);
            self.name = name.try_into().unwrap();
        }

        Ok(())
    }

    /// If provided, set the metadata for the function routine for easier identification.
    ///
    /// # Errors
    ///
    /// Returns an error if the length of the metadata is greater than 256 bytes.
    pub fn set_metadata(&mut self, metadata: &Option<Vec<u8>>) -> anchor_lang::Result<()> {
        if let Some(metadata) = metadata {
            if metadata.len() > 256 {
                return Err(error!(SwitchboardError::IllegalExecuteAttempt));
            }
            let mut metadata = metadata.clone();
            metadata.resize(256, 0);
            self.metadata = metadata.try_into().unwrap();
        }

        Ok(())
    }

    /// Returns a bool representing whether the routine is disabled for use.
    pub fn is_disabled(&self) -> bool {
        self.is_disabled.into()
    }

    /// Sets the container parameters for the routine. Optionally pass a param to append the bytes
    /// to the existing container parameters.
    ///
    /// # Arguments
    ///
    /// * `container_params` - A mutable reference to a vector of bytes representing the container parameters.
    /// * `append_container_params` - A boolean indicating whether to append the container parameters to the existing ones or replace them.
    ///
    /// # Errors
    ///
    /// Returns an error if the length of the container parameters exceeds the maximum allowed length.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the operation was successful.
    pub fn set_container_params(
        &mut self,
        container_params: &mut Vec<u8>,
        append_container_params: bool,
    ) -> anchor_lang::Result<()> {
        let max_len = self.max_container_params_len as usize;

        if append_container_params {
            if self.container_params.len() + container_params.len() > max_len {
                return Err(error!(SwitchboardError::IllegalExecuteAttempt));
            }

            self.container_params.append(container_params);
        } else {
            if container_params.len() > max_len {
                return Err(error!(SwitchboardError::IllegalExecuteAttempt));
            }
            self.container_params = container_params.clone();
        }

        self.container_params_hash = solana_program::hash::hash(&self.container_params).to_bytes();

        Ok(())
    }

    /// Increments the queue index and wraps around if it exceeds the queue's data length.
    /// Used to provide round-robin oracle assignment.
    fn increment_queue_idx(&mut self, queue_data_len: u32) {
        self.queue_idx += 1;
        self.queue_idx %= queue_data_len;
    }

    /// Saves the enclave verification
    ///
    /// # Arguments
    ///
    /// * `clock` - The current clock instance.
    /// * `error_code` - The error code for the attestation round.
    /// * `verifier` - The public key of the verifier.
    /// * `enclave_signer` - The public key of the enclave signer.
    /// * `queue_data_len` - The number of oracles heartbeating on the attestation queue.
    pub fn save_enclave(
        &mut self,
        clock: &Clock,
        error_code: u8,
        verifier: &Pubkey,
        mr_enclave: &[u8; 32],
        func_signer_rotation_interval: i64,
        queue_data_len: u32,
    ) -> anchor_lang::Result<()> {
        self.last_rotation_timestamp = clock.unix_timestamp;

        self.enclave = self.pending_enclave;
        self.pending_enclave = BorshQuote::default();

        self.enclave.verifier = *verifier;
        self.enclave.mr_enclave = *mr_enclave;
        self.enclave.verification_timestamp = clock.unix_timestamp;
        self.enclave.valid_until = clock
            .unix_timestamp
            .saturating_add(func_signer_rotation_interval);

        // Increment the queue idx for round robin assignment
        self.increment_queue_idx(queue_data_len);

        // Errors
        // 0            : No error
        // 1 - 199      : User defined errors, still successful
        // 200 - 255    : Switchboard errors, verification failed
        self.error_status = error_code;
        if self.error_status < 200 {
            // No error, success
            self.enclave.verification_status = 1;
        } else {
            // Failure
            self.enclave.enclave_signer = Pubkey::default();
        }

        Ok(())
    }

    /// Validates the given `signer` account against the `function_account_info` and the enclave_signer
    /// stored in this `FunctionServiceAccountData`.
    ///
    /// # Arguments
    ///
    /// * `function_account_info` - The `AccountInfo` of the function account.
    /// * `signer` - The `AccountInfo` of the account to validate.
    ///
    /// # Errors
    ///
    /// Returns an error if the function account data cannot be loaded or if the `signer` account does not match
    /// the expected `enclave_signer`.
    ///
    /// # Returns
    ///
    /// Returns `Ok(true)` if the validation succeeds, `Ok(false)` otherwise.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use switchboard_solana::FunctionServiceAccountData;
    ///
    /// #[derive(Accounts)]
    /// pub struct Settle<'info> {
    ///     // YOUR PROGRAM ACCOUNTS
    ///     #[account(
    ///         mut,
    ///         has_one = switchboard_routine,
    ///     )]
    ///     pub user: AccountLoader<'info, UserState>,
    ///
    ///     // SWITCHBOARD ACCOUNTS
    ///     pub switchboard_function: AccountLoader<'info, FunctionAccountData>,
    ///     #[account(
    ///         constraint = switchboard_service.validate_signer(
    ///             &switchboard_function.to_account_info(),
    ///             &enclave_signer.to_account_info()
    ///         )?
    ///     )]
    ///     pub switchboard_service: Box<Account<'info, FunctionServiceAccountData>>,
    ///     pub enclave_signer: Signer<'info>,
    /// }
    /// ```
    pub fn validate_signer<'a>(
        &self,
        function_loader: &AccountLoader<'a, FunctionAccountData>,
        signer: &Signer<'a>,
    ) -> anchor_lang::Result<bool> {
        if self.function != function_loader.key() {
            msg!(
                "FunctionMismatch: expected {}, received {}",
                self.function,
                function_loader.key()
            );
            return Ok(false);
        }

        let func = function_loader.load()?; // check owner/discriminator

        if self.attestation_queue != func.attestation_queue {
            msg!(
                "QueueMismatch: expected {}, received {}",
                self.attestation_queue,
                func.attestation_queue
            );
            return Ok(false);
        }

        let clock = Clock::get()?;

        // Check if enclave_signer matches the currently assigned enclave or the previously assigned enclave
        if signer.key() == self.enclave.enclave_signer {
            Ok(self.enclave.valid_until >= clock.unix_timestamp)
        } else if signer.key() == self.previous_enclave.enclave_signer {
            Ok(self.previous_enclave.valid_until >= clock.unix_timestamp)
        } else {
            msg!(
                "SignerMismatch: expected {}, received {}",
                self.enclave.enclave_signer,
                signer.key()
            );
            Ok(false)
        }
    }

    pub fn get_name(&self) -> String {
        std::str::from_utf8(&self.name)
            .unwrap_or("")
            .trim()
            .to_string()
    }

    pub fn get_metadata(&self) -> String {
        std::str::from_utf8(&self.metadata)
            .unwrap_or("")
            .trim()
            .to_string()
    }
}