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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! On-chain coordination for ROFL components.
use std::collections::BTreeSet;

use once_cell::sync::Lazy;

use crate::{
    context::Context,
    core::{
        common::crypto::signature::PublicKey as CorePublicKey,
        consensus::{
            registry::{Node, RolesMask, VerifiedEndorsedCapabilityTEE},
            state::registry::ImmutableState as RegistryImmutableState,
        },
    },
    crypto::signature::PublicKey,
    handler, migration,
    module::{self, Module as _, Parameters as _},
    modules::{self, accounts::API as _, core::API as _},
    sdk_derive,
    state::CurrentState,
    types::{address::Address, transaction::Transaction},
    Runtime,
};

pub mod app;
pub mod app_id;
mod config;
mod error;
mod event;
pub mod policy;
pub mod state;
#[cfg(test)]
mod test;
pub mod types;

/// Unique module name.
const MODULE_NAME: &str = "rofl";

pub use config::Config;
pub use error::Error;
pub use event::Event;

/// Parameters for the module.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct Parameters {}

/// Errors emitted during parameter validation.
#[derive(thiserror::Error, Debug)]
pub enum ParameterValidationError {}

impl module::Parameters for Parameters {
    type Error = ParameterValidationError;

    fn validate_basic(&self) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// Genesis state for the module.
#[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)]
pub struct Genesis {
    pub parameters: Parameters,

    /// Application configurations.
    pub apps: Vec<types::AppConfig>,
}

/// Interface that can be called from other modules.
pub trait API {
    /// Get the Runtime Attestation Key of the ROFL app instance in case the origin transaction is
    /// signed by a ROFL instance. Otherwise `None` is returned.
    ///
    /// # Panics
    ///
    /// This method will panic if called outside a transaction environment.
    fn get_origin_rak() -> Option<PublicKey>;

    /// Get the registration descriptor of the ROFL app instance in case the origin transaction is
    /// signed by a ROFL instance of the specified app. Otherwise `None` is returned.
    ///
    /// # Panics
    ///
    /// This method will panic if called outside a transaction environment.
    fn get_origin_registration(app: app_id::AppId) -> Option<types::Registration>;

    /// Verify whether the origin transaction is signed by an authorized ROFL instance for the given
    /// application.
    ///
    /// # Panics
    ///
    /// This method will panic if called outside a transaction environment.
    fn is_authorized_origin(app: app_id::AppId) -> bool;

    /// Get a specific registered instance for an application.
    fn get_registration(app: app_id::AppId, rak: PublicKey) -> Result<types::Registration, Error>;

    /// Get an application's configuration.
    fn get_app(id: app_id::AppId) -> Result<types::AppConfig, Error>;

    /// Get all registered instances for an application.
    fn get_instances(id: app_id::AppId) -> Result<Vec<types::Registration>, Error>;
}

/// Module's address that has the application stake pool.
///
/// oasis1qza6sddnalgzexk3ct30gqfvntgth5m4hsyywmff
pub static ADDRESS_APP_STAKE_POOL: Lazy<Address> =
    Lazy::new(|| Address::from_module(MODULE_NAME, "app-stake-pool"));

pub struct Module<Cfg: Config> {
    _cfg: std::marker::PhantomData<Cfg>,
}

impl<Cfg: Config> API for Module<Cfg> {
    fn get_origin_rak() -> Option<PublicKey> {
        let caller_pk = CurrentState::with_env_origin(|env| env.tx_caller_public_key())?;

        // Resolve RAK as the call may be made by an extra key.
        state::get_endorser(&caller_pk).map(|kei| match kei {
            // It may point to a RAK.
            state::KeyEndorsementInfo { rak: Some(rak), .. } => rak.into(),
            // Or it points to itself.
            _ => caller_pk,
        })
    }

    fn get_origin_registration(app: app_id::AppId) -> Option<types::Registration> {
        Self::get_origin_rak()
            .and_then(|rak| state::get_registration(app, &rak.try_into().unwrap()))
    }

    fn is_authorized_origin(app: app_id::AppId) -> bool {
        Self::get_origin_registration(app).is_some()
    }

    fn get_registration(app: app_id::AppId, rak: PublicKey) -> Result<types::Registration, Error> {
        state::get_registration(app, &rak.try_into().map_err(|_| Error::InvalidArgument)?)
            .ok_or(Error::UnknownInstance)
    }

    fn get_app(id: app_id::AppId) -> Result<types::AppConfig, Error> {
        state::get_app(id).ok_or(Error::UnknownApp)
    }

    fn get_instances(id: app_id::AppId) -> Result<Vec<types::Registration>, Error> {
        Ok(state::get_registrations_for_app(id))
    }
}

#[sdk_derive(Module)]
impl<Cfg: Config> Module<Cfg> {
    const NAME: &'static str = MODULE_NAME;
    type Error = Error;
    type Event = Event;
    type Parameters = Parameters;
    type Genesis = Genesis;

    #[migration(init)]
    fn init(genesis: Genesis) {
        genesis
            .parameters
            .validate_basic()
            .expect("invalid genesis parameters");

        // Set genesis parameters.
        Self::set_params(genesis.parameters);

        // Insert all applications.
        for cfg in genesis.apps {
            if state::get_app(cfg.id).is_some() {
                panic!("duplicate application in genesis: {:?}", cfg.id);
            }

            state::set_app(cfg);
        }
    }

    /// Create a new ROFL application.
    #[handler(call = "rofl.Create")]
    fn tx_create<C: Context>(ctx: &C, body: types::Create) -> Result<app_id::AppId, Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_CREATE)?;

        if CurrentState::with_env(|env| env.is_check_only()) {
            return Ok(Default::default());
        }

        let (creator, tx_index) =
            CurrentState::with_env(|env| (env.tx_caller_address(), env.tx_index()));
        let app_id = match body.scheme {
            types::IdentifierScheme::CreatorRoundIndex => app_id::AppId::from_creator_round_index(
                creator,
                ctx.runtime_header().round,
                tx_index.try_into().map_err(|_| Error::InvalidArgument)?,
            ),
            types::IdentifierScheme::CreatorNonce => {
                let nonce = <C::Runtime as Runtime>::Accounts::get_nonce(creator)?;

                app_id::AppId::from_creator_nonce(creator, nonce)
            }
        };

        // Sanity check that the application doesn't already exist.
        if state::get_app(app_id).is_some() {
            return Err(Error::AppAlreadyExists);
        }

        // Transfer stake.
        <C::Runtime as Runtime>::Accounts::transfer(
            creator,
            *ADDRESS_APP_STAKE_POOL,
            &Cfg::STAKE_APP_CREATE,
        )?;

        // Register the application.
        let cfg = types::AppConfig {
            id: app_id,
            policy: body.policy,
            admin: Some(creator),
            stake: Cfg::STAKE_APP_CREATE,
        };
        state::set_app(cfg);

        CurrentState::with(|state| state.emit_event(Event::AppCreated { id: app_id }));

        Ok(app_id)
    }

    /// Ensure caller is the current administrator, return an error otherwise.
    fn ensure_caller_is_admin(cfg: &types::AppConfig) -> Result<(), Error> {
        let caller = CurrentState::with_env(|env| env.tx_caller_address());
        if cfg.admin != Some(caller) {
            return Err(Error::Forbidden);
        }
        Ok(())
    }

    /// Update a ROFL application.
    #[handler(call = "rofl.Update")]
    fn tx_update<C: Context>(ctx: &C, body: types::Update) -> Result<(), Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_UPDATE)?;

        let mut cfg = state::get_app(body.id).ok_or(Error::UnknownApp)?;

        // Ensure caller is the admin and is allowed to update the configuration.
        Self::ensure_caller_is_admin(&cfg)?;

        if CurrentState::with_env(|env| env.is_check_only()) {
            return Ok(());
        }

        // Return early if nothing has actually changed.
        if cfg.policy == body.policy && cfg.admin == body.admin {
            return Ok(());
        }

        cfg.policy = body.policy;
        cfg.admin = body.admin;
        state::set_app(cfg);

        CurrentState::with(|state| state.emit_event(Event::AppUpdated { id: body.id }));

        Ok(())
    }

    /// Remove a ROFL application.
    #[handler(call = "rofl.Remove")]
    fn tx_remove<C: Context>(ctx: &C, body: types::Remove) -> Result<(), Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_REMOVE)?;

        let cfg = state::get_app(body.id).ok_or(Error::UnknownApp)?;

        // Ensure caller is the admin and is allowed to update the configuration.
        Self::ensure_caller_is_admin(&cfg)?;

        if CurrentState::with_env(|env| env.is_check_only()) {
            return Ok(());
        }

        state::remove_app(body.id);

        // Return stake to the administrator account.
        if let Some(admin) = cfg.admin {
            <C::Runtime as Runtime>::Accounts::transfer(
                *ADDRESS_APP_STAKE_POOL,
                admin,
                &cfg.stake,
            )?;
        }

        CurrentState::with(|state| state.emit_event(Event::AppRemoved { id: body.id }));

        Ok(())
    }

    /// Register a new ROFL instance.
    #[handler(call = "rofl.Register")]
    fn tx_register<C: Context>(ctx: &C, body: types::Register) -> Result<(), Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_REGISTER)?;

        if body.expiration <= ctx.epoch() {
            return Err(Error::RegistrationExpired);
        }

        let cfg = state::get_app(body.app).ok_or(Error::UnknownApp)?;

        if body.expiration - ctx.epoch() > cfg.policy.max_expiration {
            return Err(Error::InvalidArgument);
        }

        // Ensure that the transaction is signed by RAK (and co-signed by extra keys).
        let signer_pks: BTreeSet<PublicKey> = CurrentState::with_env(|env| {
            env.tx_auth_info()
                .signer_info
                .iter()
                .filter_map(|si| si.address_spec.public_key())
                .collect()
        });
        if !signer_pks.contains(&body.ect.capability_tee.rak.into()) {
            return Err(Error::NotSignedByRAK);
        }
        for extra_pk in &body.extra_keys {
            if !signer_pks.contains(extra_pk) {
                return Err(Error::NotSignedByExtraKey);
            }
        }

        if CurrentState::with_env(|env| env.is_check_only()) {
            return Ok(());
        }

        // Verify policy.
        let verified_ect = body
            .ect
            .verify(&cfg.policy.quotes)
            .map_err(|_| Error::InvalidArgument)?;

        // Verify enclave identity.
        if !cfg
            .policy
            .enclaves
            .contains(&verified_ect.verified_attestation.quote.identity)
        {
            return Err(Error::UnknownEnclave);
        }

        // Verify allowed endorsement.
        let node = Self::verify_endorsement(ctx, &cfg.policy, &verified_ect)?;

        // Update registration.
        let registration = types::Registration {
            app: body.app,
            node_id: verified_ect.node_id.unwrap(), // Verified above.
            entity_id: node.map(|n| n.entity_id),
            rak: body.ect.capability_tee.rak,
            rek: body.ect.capability_tee.rek.ok_or(Error::InvalidArgument)?, // REK required.
            expiration: body.expiration,
            extra_keys: body.extra_keys,
        };
        state::update_registration(registration)?;

        Ok(())
    }

    /// Verify whether the given endorsement is allowed by the application policy.
    ///
    /// Returns an optional endorsing node descriptor when available.
    fn verify_endorsement<C: Context>(
        ctx: &C,
        app_policy: &policy::AppAuthPolicy,
        ect: &VerifiedEndorsedCapabilityTEE,
    ) -> Result<Option<Node>, Error> {
        use policy::AllowedEndorsement;

        let endorsing_node_id = ect.node_id.ok_or(Error::UnknownNode)?;

        // Attempt to resolve the node that endorsed the enclave. It may be that the node is not
        // even registered in the consensus layer which may be acceptable for some policies.
        let maybe_node = || -> Result<Option<Node>, Error> {
            let registry = RegistryImmutableState::new(ctx.consensus_state());
            let node = registry
                .node(&endorsing_node_id)
                .map_err(|_| Error::UnknownNode)?;
            let node = if let Some(node) = node {
                node
            } else {
                return Ok(None);
            };
            // Ensure node is not expired.
            if node.expiration < ctx.epoch() {
                return Ok(None);
            }

            Ok(Some(node))
        }()?;

        // Ensure node is registered for this runtime.
        let has_runtime = |node: &Node| -> bool {
            let version = &<C::Runtime as Runtime>::VERSION;
            node.get_runtime(ctx.runtime_id(), version).is_some()
        };

        for allowed in &app_policy.endorsements {
            match (allowed, &maybe_node) {
                (AllowedEndorsement::Any, _) => {
                    // Any node is allowed.
                    return Ok(maybe_node);
                }
                (AllowedEndorsement::ComputeRole, Some(node)) => {
                    if node.has_roles(RolesMask::ROLE_COMPUTE_WORKER) && has_runtime(node) {
                        return Ok(maybe_node);
                    }
                }
                (AllowedEndorsement::ObserverRole, Some(node)) => {
                    if node.has_roles(RolesMask::ROLE_OBSERVER) && has_runtime(node) {
                        return Ok(maybe_node);
                    }
                }
                (AllowedEndorsement::Entity(entity_id), Some(node)) => {
                    // If a specific entity is required, it may be registered for any runtime.
                    if &node.entity_id == entity_id {
                        return Ok(maybe_node);
                    }
                }
                (AllowedEndorsement::Node(node_id), _) => {
                    if endorsing_node_id == *node_id {
                        return Ok(maybe_node);
                    }
                }
                _ => continue,
            }
        }

        // If nothing matched, this node is not allowed to register.
        Err(Error::NodeNotAllowed)
    }

    /// Verify whether the origin transaction is signed by an authorized ROFL instance for the given
    /// application.
    #[handler(call = "rofl.IsAuthorizedOrigin", internal)]
    fn internal_is_authorized_origin<C: Context>(
        _ctx: &C,
        app: app_id::AppId,
    ) -> Result<bool, Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_IS_AUTHORIZED_ORIGIN)?;

        Ok(Self::is_authorized_origin(app))
    }

    #[handler(call = "rofl.AuthorizedOriginNode", internal)]
    fn internal_authorized_origin_node<C: Context>(
        _ctx: &C,
        app: app_id::AppId,
    ) -> Result<CorePublicKey, Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_AUTHORIZED_ORIGIN_NODE)?;

        let registration = Self::get_origin_registration(app).ok_or(Error::UnknownInstance)?;
        Ok(registration.node_id)
    }

    #[handler(call = "rofl.AuthorizedOriginEntity", internal)]
    fn internal_authorized_origin_entity<C: Context>(
        _ctx: &C,
        app: app_id::AppId,
    ) -> Result<Option<CorePublicKey>, Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_AUTHORIZED_ORIGIN_ENTITY)?;

        let registration = Self::get_origin_registration(app).ok_or(Error::UnknownInstance)?;
        Ok(registration.entity_id)
    }

    /// Returns the configuration for the given ROFL application.
    #[handler(query = "rofl.App")]
    fn query_app<C: Context>(_ctx: &C, args: types::AppQuery) -> Result<types::AppConfig, Error> {
        Self::get_app(args.id)
    }

    /// Returns a specific registered instance for the given ROFL application.
    #[handler(query = "rofl.AppInstance")]
    fn query_app_instance<C: Context>(
        _ctx: &C,
        args: types::AppInstanceQuery,
    ) -> Result<types::Registration, Error> {
        Self::get_registration(args.app, args.rak)
    }

    /// Returns a list of all registered instances for the given ROFL application.
    #[handler(query = "rofl.AppInstances", expensive)]
    fn query_app_instances<C: Context>(
        _ctx: &C,
        args: types::AppQuery,
    ) -> Result<Vec<types::Registration>, Error> {
        Self::get_instances(args.id)
    }

    /// Returns the minimum stake thresholds for managing ROFL.
    #[handler(query = "rofl.StakeThresholds")]
    fn query_stake_thresholds<C: Context>(
        _ctx: &C,
        _args: (),
    ) -> Result<types::StakeThresholds, Error> {
        Ok(types::StakeThresholds {
            app_create: Cfg::STAKE_APP_CREATE,
        })
    }

    /// Returns the minimum stake thresholds for managing ROFL.
    #[handler(call = "rofl.StakeThresholds", internal)]
    fn internal_query_stake_thresholds<C: Context>(
        ctx: &C,
        _args: (),
    ) -> Result<types::StakeThresholds, Error> {
        <C::Runtime as Runtime>::Core::use_tx_gas(Cfg::GAS_COST_CALL_STAKE_THRESHOLDS)?;
        Ok(types::StakeThresholds {
            app_create: Cfg::STAKE_APP_CREATE,
        })
    }

    fn resolve_payer_from_tx<C: Context>(
        ctx: &C,
        tx: &Transaction,
        app_policy: &policy::AppAuthPolicy,
    ) -> Result<Option<Address>, anyhow::Error> {
        let caller_pk = tx
            .auth_info
            .signer_info
            .first()
            .and_then(|si| si.address_spec.public_key());

        match tx.call.method.as_str() {
            "rofl.Register" => {
                // For registration transactions, extract endorsing node.
                let body: types::Register = cbor::from_value(tx.call.body.clone())?;
                if body.expiration <= ctx.epoch() {
                    return Err(Error::RegistrationExpired.into());
                }

                // Ensure that the transaction is signed by RAK.
                let caller_pk = caller_pk.ok_or(Error::NotSignedByRAK)?;
                if caller_pk != body.ect.capability_tee.rak {
                    return Err(Error::NotSignedByRAK.into());
                }

                body.ect.verify_endorsement()?;

                // Checking other details is not relevant for authorizing fee payments as if the
                // node signed a TEE capability then it is authorizing fees to be spent on its
                // behalf.

                let node_id = body.ect.node_endorsement.public_key;
                let payer = Address::from_consensus_pk(&node_id);

                Ok(Some(payer))
            }
            _ => {
                // For others, check if caller is one of the endorsed keys.
                let caller_pk = match caller_pk {
                    Some(pk) => pk,
                    None => return Ok(None),
                };

                Ok(state::get_endorser(&caller_pk)
                    .map(|ei| Address::from_consensus_pk(&ei.node_id)))
            }
        }
    }
}

impl<Cfg: Config> module::FeeProxyHandler for Module<Cfg> {
    fn resolve_payer<C: Context>(
        ctx: &C,
        tx: &Transaction,
    ) -> Result<Option<Address>, modules::core::Error> {
        use policy::FeePolicy;

        let proxy = if let Some(ref proxy) = tx.auth_info.fee.proxy {
            proxy
        } else {
            return Ok(None);
        };

        if proxy.module != MODULE_NAME {
            return Ok(None);
        }

        // Look up the per-ROFL app policy.
        let app_id = app_id::AppId::try_from(proxy.id.as_slice())
            .map_err(|err| modules::core::Error::InvalidArgument(err.into()))?;
        let app_policy = state::get_app(app_id).map(|cfg| cfg.policy).ok_or(
            modules::core::Error::InvalidArgument(Error::UnknownApp.into()),
        )?;

        match app_policy.fees {
            FeePolicy::InstancePays => {
                // Application needs to figure out a way to pay, defer to regular handler.
                Ok(None)
            }
            FeePolicy::EndorsingNodePays => Self::resolve_payer_from_tx(ctx, tx, &app_policy)
                .map_err(modules::core::Error::InvalidArgument),
        }
    }
}

impl<Cfg: Config> module::TransactionHandler for Module<Cfg> {}

impl<Cfg: Config> module::BlockHandler for Module<Cfg> {
    fn end_block<C: Context>(ctx: &C) {
        // Only do work in case the epoch has changed since the last processed block.
        if !<C::Runtime as Runtime>::Core::has_epoch_changed() {
            return;
        }

        // Process enclave expirations.
        // TODO: Consider processing unprocessed in the next block(s) if there are too many.
        state::expire_registrations(ctx.epoch(), 128);
    }
}

impl<Cfg: Config> module::InvariantHandler for Module<Cfg> {}