linera-execution 0.15.17

Persistent data and the corresponding logics used by the Linera protocol for runtime and execution of smart contracts / applications.
Documentation
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! This module tracks the resources used during the execution of a transaction.

use std::{fmt, sync::Arc, time::Duration};

use custom_debug_derive::Debug;
use linera_base::{
    data_types::{Amount, ApplicationDescription, ArithmeticError, Blob},
    ensure,
    identifiers::AccountOwner,
    ownership::ChainOwnership,
    vm::VmRuntime,
};
use linera_views::{context::Context, ViewError};
use serde::Serialize;

use crate::{ExecutionError, Message, Operation, ResourceControlPolicy, SystemExecutionStateView};

#[derive(Clone, Debug, Default)]
pub struct ResourceController<Account = Amount, Tracker = ResourceTracker> {
    /// The (fixed) policy used to charge fees and control resource usage.
    policy: Arc<ResourceControlPolicy>,
    /// How the resources were used so far.
    pub tracker: Tracker,
    /// The account paying for the resource usage.
    pub account: Account,
    /// When true, balance deductions are skipped (fees waived for free apps).
    pub is_free: bool,
}

impl<Account, Tracker> ResourceController<Account, Tracker> {
    /// Creates a new resource controller with the given policy and account.
    pub fn new(policy: Arc<ResourceControlPolicy>, tracker: Tracker, account: Account) -> Self {
        Self {
            policy,
            tracker,
            account,
            is_free: false,
        }
    }

    /// Returns a reference to the policy.
    pub fn policy(&self) -> &Arc<ResourceControlPolicy> {
        &self.policy
    }

    /// Returns a reference to the tracker.
    pub fn tracker(&self) -> &Tracker {
        &self.tracker
    }
}

/// The runtime size of an `Amount`.
pub const RUNTIME_AMOUNT_SIZE: u32 = 16;

/// The runtime size of a `ApplicationId`.
pub const RUNTIME_APPLICATION_ID_SIZE: u32 = 32;

/// The runtime size of a `BlockHeight`.
pub const RUNTIME_BLOCK_HEIGHT_SIZE: u32 = 8;

/// The runtime size of a `ChainId`.
pub const RUNTIME_CHAIN_ID_SIZE: u32 = 32;

/// The runtime size of a `Timestamp`.
pub const RUNTIME_TIMESTAMP_SIZE: u32 = 8;

/// The runtime size of the weight of an owner.
pub const RUNTIME_OWNER_WEIGHT_SIZE: u32 = 8;

/// The runtime constant part size of the `ChainOwnership`.
/// It consists of one `u32` and four `TimeDelta` which are the constant part of
/// the `ChainOwnership`. The way we do it is not optimal:
/// TODO(#4164): Implement a procedure for computing naive sizes.
pub const RUNTIME_CONSTANT_CHAIN_OWNERSHIP_SIZE: u32 = 4 + 4 * 8;

/// The runtime size of a `CryptoHash`.
pub const RUNTIME_CRYPTO_HASH_SIZE: u32 = 32;

/// The runtime size of a `VmRuntime` enum.
pub const RUNTIME_VM_RUNTIME_SIZE: u32 = 1;

/// The runtime constant part size of an `ApplicationDescription`.
/// This includes: `ModuleId` (2 hashes + VmRuntime) + `ChainId` + `BlockHeight` + `u32`.
/// Variable parts (`parameters` and `required_application_ids`) are calculated separately.
pub const RUNTIME_CONSTANT_APPLICATION_DESCRIPTION_SIZE: u32 = 2 * RUNTIME_CRYPTO_HASH_SIZE + RUNTIME_VM_RUNTIME_SIZE  // ModuleId
    + RUNTIME_CHAIN_ID_SIZE                                  // creator_chain_id
    + RUNTIME_BLOCK_HEIGHT_SIZE                              // block_height
    + 4; // application_index (u32)

#[cfg(test)]
mod tests {
    use std::mem::size_of;

    use linera_base::{
        data_types::{Amount, ApplicationDescription, BlockHeight, Timestamp},
        identifiers::{ApplicationId, ChainId, ModuleId},
    };

    use crate::resources::{
        RUNTIME_AMOUNT_SIZE, RUNTIME_APPLICATION_ID_SIZE, RUNTIME_BLOCK_HEIGHT_SIZE,
        RUNTIME_CHAIN_ID_SIZE, RUNTIME_CONSTANT_APPLICATION_DESCRIPTION_SIZE,
        RUNTIME_OWNER_WEIGHT_SIZE, RUNTIME_TIMESTAMP_SIZE,
    };

    #[test]
    fn test_size_of_runtime_operations() {
        assert_eq!(RUNTIME_AMOUNT_SIZE as usize, size_of::<Amount>());
        assert_eq!(
            RUNTIME_APPLICATION_ID_SIZE as usize,
            size_of::<ApplicationId>()
        );
        assert_eq!(RUNTIME_BLOCK_HEIGHT_SIZE as usize, size_of::<BlockHeight>());
        assert_eq!(RUNTIME_CHAIN_ID_SIZE as usize, size_of::<ChainId>());
        assert_eq!(RUNTIME_TIMESTAMP_SIZE as usize, size_of::<Timestamp>());
        assert_eq!(RUNTIME_OWNER_WEIGHT_SIZE as usize, size_of::<u64>());
    }

    /// Verifies that `RUNTIME_CONSTANT_APPLICATION_DESCRIPTION_SIZE` matches the actual
    /// structure of `ApplicationDescription`. This test will fail if a new fixed-size
    /// field is added to the struct.
    #[test]
    fn test_application_description_size() {
        // Verify using BCS serialization, which is architecture-independent.
        // BCS encodes Vec length as ULEB128, so empty vectors add 1 byte each.
        let description = ApplicationDescription {
            module_id: ModuleId::default(),
            creator_chain_id: ChainId::default(),
            block_height: BlockHeight::default(),
            application_index: 0,
            parameters: vec![],
            required_application_ids: vec![],
        };
        let serialized = bcs::to_bytes(&description).expect("serialization should succeed");
        // Serialized size = fixed fields + 2 bytes for empty vectors (1 byte each for ULEB128 length).
        assert_eq!(
            serialized.len(),
            RUNTIME_CONSTANT_APPLICATION_DESCRIPTION_SIZE as usize + 2
        );
    }
}

/// The resources used so far by an execution process.
/// Acts as an accumulator for all resources consumed during
/// a specific execution flow. This could be the execution of a block,
/// the processing of a single message, or a specific phase within these
/// broader operations.
#[derive(Copy, Debug, Clone, Default)]
pub struct ResourceTracker {
    /// The total size of the block so far.
    pub block_size: u64,
    /// The EVM fuel used so far.
    pub evm_fuel: u64,
    /// The Wasm fuel used so far.
    pub wasm_fuel: u64,
    /// The number of read operations.
    pub read_operations: u32,
    /// The number of write operations.
    pub write_operations: u32,
    /// The size of bytes read from runtime.
    pub bytes_runtime: u32,
    /// The number of bytes read.
    pub bytes_read: u64,
    /// The number of bytes written.
    pub bytes_written: u64,
    /// The number of blobs read.
    pub blobs_read: u32,
    /// The number of blobs published.
    pub blobs_published: u32,
    /// The number of blob bytes read.
    pub blob_bytes_read: u64,
    /// The number of blob bytes published.
    pub blob_bytes_published: u64,
    /// The change in the number of bytes being stored by user applications.
    pub bytes_stored: i32,
    /// The number of operations executed.
    pub operations: u32,
    /// The total size of the arguments of user operations.
    pub operation_bytes: u64,
    /// The number of outgoing messages created (system and user).
    pub messages: u32,
    /// The total size of the arguments of outgoing user messages.
    pub message_bytes: u64,
    /// The number of HTTP requests performed.
    pub http_requests: u32,
    /// The number of calls to services as oracles.
    pub service_oracle_queries: u32,
    /// The time spent executing services as oracles.
    pub service_oracle_execution: Duration,
    /// The amount allocated to message grants.
    pub grants: Amount,
}

impl ResourceTracker {
    fn fuel(&self, vm_runtime: VmRuntime) -> u64 {
        match vm_runtime {
            VmRuntime::Wasm => self.wasm_fuel,
            VmRuntime::Evm => self.evm_fuel,
        }
    }
}

impl fmt::Display for ResourceTracker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut lines = Vec::new();

        let mut block_parts = Vec::new();
        if self.block_size != 0 {
            block_parts.push(format!("size={}", self.block_size));
        }
        if self.operations != 0 {
            block_parts.push(format!("operations={}", self.operations));
        }
        if self.operation_bytes != 0 {
            block_parts.push(format!("operation_bytes={}", self.operation_bytes));
        }
        if !block_parts.is_empty() {
            lines.push(format!("block: {}", block_parts.join(", ")));
        }

        let mut fuel_parts = Vec::new();
        if self.wasm_fuel != 0 {
            fuel_parts.push(format!("wasm={}", self.wasm_fuel));
        }
        if self.evm_fuel != 0 {
            fuel_parts.push(format!("evm={}", self.evm_fuel));
        }
        if !fuel_parts.is_empty() {
            lines.push(format!("fuel: {}", fuel_parts.join(", ")));
        }

        let mut storage_parts = Vec::new();
        if self.read_operations != 0 {
            storage_parts.push(format!("reads={}", self.read_operations));
        }
        if self.write_operations != 0 {
            storage_parts.push(format!("writes={}", self.write_operations));
        }
        if self.bytes_runtime != 0 {
            storage_parts.push(format!("runtime_bytes={}", self.bytes_runtime));
        }
        if self.bytes_read != 0 {
            storage_parts.push(format!("bytes_read={}", self.bytes_read));
        }
        if self.bytes_written != 0 {
            storage_parts.push(format!("bytes_written={}", self.bytes_written));
        }
        if self.bytes_stored != 0 {
            storage_parts.push(format!("bytes_stored={}", self.bytes_stored));
        }
        if !storage_parts.is_empty() {
            lines.push(format!("storage: {}", storage_parts.join(", ")));
        }

        let mut blob_parts = Vec::new();
        if self.blobs_read != 0 {
            blob_parts.push(format!("read={}", self.blobs_read));
        }
        if self.blobs_published != 0 {
            blob_parts.push(format!("published={}", self.blobs_published));
        }
        if self.blob_bytes_read != 0 {
            blob_parts.push(format!("bytes_read={}", self.blob_bytes_read));
        }
        if self.blob_bytes_published != 0 {
            blob_parts.push(format!("bytes_published={}", self.blob_bytes_published));
        }
        if !blob_parts.is_empty() {
            lines.push(format!("blobs: {}", blob_parts.join(", ")));
        }

        let mut message_parts = Vec::new();
        if self.messages != 0 {
            message_parts.push(format!("count={}", self.messages));
        }
        if self.message_bytes != 0 {
            message_parts.push(format!("bytes={}", self.message_bytes));
        }
        if self.grants != Amount::ZERO {
            message_parts.push(format!("grants={}", self.grants));
        }
        if !message_parts.is_empty() {
            lines.push(format!("messages: {}", message_parts.join(", ")));
        }

        let mut http_service_parts = Vec::new();
        if self.http_requests != 0 {
            http_service_parts.push(format!("http_requests={}", self.http_requests));
        }
        if self.service_oracle_queries != 0 {
            http_service_parts.push(format!("service_queries={}", self.service_oracle_queries));
        }
        if self.service_oracle_execution != Duration::ZERO {
            http_service_parts.push(format!(
                "service_execution={:?}",
                self.service_oracle_execution
            ));
        }
        if !http_service_parts.is_empty() {
            lines.push(format!("http/service: {}", http_service_parts.join(", ")));
        }

        let mut lines_iter = lines.into_iter();
        if let Some(first) = lines_iter.next() {
            write!(f, "{}", first)?;
            for line in lines_iter {
                write!(f, "\n  {}", line)?;
            }
        }

        Ok(())
    }
}

/// How to access the balance of an account.
pub trait BalanceHolder {
    fn balance(&self) -> Result<Amount, ArithmeticError>;

    fn try_add_assign(&mut self, other: Amount) -> Result<(), ArithmeticError>;

    fn try_sub_assign(&mut self, other: Amount) -> Result<(), ArithmeticError>;
}

// The main accounting functions for a ResourceController.
impl<Account, Tracker> ResourceController<Account, Tracker>
where
    Account: BalanceHolder,
    Tracker: AsRef<ResourceTracker> + AsMut<ResourceTracker>,
{
    /// Obtains the balance of the account. The only possible error is an arithmetic
    /// overflow, which should not happen in practice due to final token supply.
    pub fn balance(&self) -> Result<Amount, ArithmeticError> {
        self.account.balance()
    }

    /// Operates a 3-way merge by transferring the difference between `initial`
    /// and `other` to `self`.
    pub fn merge_balance(&mut self, initial: Amount, other: Amount) -> Result<(), ExecutionError> {
        if other <= initial {
            let sub_amount = initial.try_sub(other).expect("other <= initial");
            self.account.try_sub_assign(sub_amount).map_err(|_| {
                ExecutionError::FeesExceedFunding {
                    fees: sub_amount,
                    balance: self.balance().unwrap_or(Amount::MAX),
                }
            })?;
        } else {
            self.account
                .try_add_assign(other.try_sub(initial).expect("other > initial"))?;
        }
        Ok(())
    }

    /// Subtracts an amount from a balance and reports an error if that is impossible.
    /// When `is_free` is set, balance deductions are skipped (fees waived).
    fn update_balance(&mut self, fees: Amount) -> Result<(), ExecutionError> {
        if self.is_free {
            return Ok(());
        }
        self.account
            .try_sub_assign(fees)
            .map_err(|_| ExecutionError::FeesExceedFunding {
                fees,
                balance: self.balance().unwrap_or(Amount::MAX),
            })?;
        Ok(())
    }

    /// Obtains the amount of fuel that could be spent by consuming the entire balance.
    pub(crate) fn remaining_fuel(&self, vm_runtime: VmRuntime) -> u64 {
        let fuel = self.tracker.as_ref().fuel(vm_runtime);
        let maximum_fuel_per_block = self.policy.maximum_fuel_per_block(vm_runtime);
        if self.is_free {
            return maximum_fuel_per_block.saturating_sub(fuel);
        }
        let balance = self.balance().unwrap_or(Amount::MAX);
        self.policy
            .remaining_fuel(balance, vm_runtime)
            .min(maximum_fuel_per_block.saturating_sub(fuel))
    }

    /// Tracks the allocation of a grant.
    pub fn track_grant(&mut self, grant: Amount) -> Result<(), ExecutionError> {
        self.tracker.as_mut().grants.try_add_assign(grant)?;
        self.update_balance(grant)
    }

    /// Tracks the execution of an operation in block.
    pub fn track_operation(&mut self, operation: &Operation) -> Result<(), ExecutionError> {
        self.tracker.as_mut().operations = self
            .tracker
            .as_mut()
            .operations
            .checked_add(1)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.operation)?;
        match operation {
            Operation::System(_) => Ok(()),
            Operation::User { bytes, .. } => {
                let size = bytes.len();
                self.tracker.as_mut().operation_bytes = self
                    .tracker
                    .as_mut()
                    .operation_bytes
                    .checked_add(size as u64)
                    .ok_or(ArithmeticError::Overflow)?;
                self.update_balance(self.policy.operation_bytes_price(size as u64)?)?;
                Ok(())
            }
        }
    }

    /// Tracks the creation of an outgoing message.
    pub fn track_message(&mut self, message: &Message) -> Result<(), ExecutionError> {
        self.tracker.as_mut().messages = self
            .tracker
            .as_mut()
            .messages
            .checked_add(1)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.message)?;
        match message {
            Message::System(_) => Ok(()),
            Message::User { bytes, .. } => {
                let size = bytes.len();
                self.tracker.as_mut().message_bytes = self
                    .tracker
                    .as_mut()
                    .message_bytes
                    .checked_add(size as u64)
                    .ok_or(ArithmeticError::Overflow)?;
                self.update_balance(self.policy.message_bytes_price(size as u64)?)?;
                Ok(())
            }
        }
    }

    /// Tracks the execution of an HTTP request.
    pub fn track_http_request(&mut self) -> Result<(), ExecutionError> {
        self.tracker.as_mut().http_requests = self
            .tracker
            .as_ref()
            .http_requests
            .checked_add(1)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.http_request)
    }

    /// Tracks a number of fuel units used.
    pub(crate) fn track_fuel(
        &mut self,
        fuel: u64,
        vm_runtime: VmRuntime,
    ) -> Result<(), ExecutionError> {
        match vm_runtime {
            VmRuntime::Wasm => {
                self.tracker.as_mut().wasm_fuel = self
                    .tracker
                    .as_ref()
                    .wasm_fuel
                    .checked_add(fuel)
                    .ok_or(ArithmeticError::Overflow)?;
                ensure!(
                    self.tracker.as_ref().wasm_fuel <= self.policy.maximum_wasm_fuel_per_block,
                    ExecutionError::MaximumFuelExceeded(vm_runtime)
                );
            }
            VmRuntime::Evm => {
                self.tracker.as_mut().evm_fuel = self
                    .tracker
                    .as_ref()
                    .evm_fuel
                    .checked_add(fuel)
                    .ok_or(ArithmeticError::Overflow)?;
                ensure!(
                    self.tracker.as_ref().evm_fuel <= self.policy.maximum_evm_fuel_per_block,
                    ExecutionError::MaximumFuelExceeded(vm_runtime)
                );
            }
        }
        self.update_balance(self.policy.fuel_price(fuel, vm_runtime)?)
    }

    /// Tracks runtime reading of `ChainId`
    pub(crate) fn track_runtime_chain_id(&mut self) -> Result<(), ExecutionError> {
        self.track_size_runtime_operations(RUNTIME_CHAIN_ID_SIZE)
    }

    /// Tracks runtime reading of `BlockHeight`
    pub(crate) fn track_runtime_block_height(&mut self) -> Result<(), ExecutionError> {
        self.track_size_runtime_operations(RUNTIME_BLOCK_HEIGHT_SIZE)
    }

    /// Tracks runtime reading of `ApplicationId`
    pub(crate) fn track_runtime_application_id(&mut self) -> Result<(), ExecutionError> {
        self.track_size_runtime_operations(RUNTIME_APPLICATION_ID_SIZE)
    }

    /// Tracks runtime reading of application parameters.
    pub(crate) fn track_runtime_application_parameters(
        &mut self,
        parameters: &[u8],
    ) -> Result<(), ExecutionError> {
        let parameters_len = parameters.len() as u32;
        self.track_size_runtime_operations(parameters_len)
    }

    /// Tracks runtime reading of `Timestamp`
    pub(crate) fn track_runtime_timestamp(&mut self) -> Result<(), ExecutionError> {
        self.track_size_runtime_operations(RUNTIME_TIMESTAMP_SIZE)
    }

    /// Tracks runtime reading of balance
    pub(crate) fn track_runtime_balance(&mut self) -> Result<(), ExecutionError> {
        self.track_size_runtime_operations(RUNTIME_AMOUNT_SIZE)
    }

    /// Tracks runtime reading of owner balances
    pub(crate) fn track_runtime_owner_balances(
        &mut self,
        owner_balances: &[(AccountOwner, Amount)],
    ) -> Result<(), ExecutionError> {
        let mut size = 0;
        for (account_owner, _) in owner_balances {
            size += account_owner.size() + RUNTIME_AMOUNT_SIZE;
        }
        self.track_size_runtime_operations(size)
    }

    /// Tracks runtime reading of owners
    pub(crate) fn track_runtime_owners(
        &mut self,
        owners: &[AccountOwner],
    ) -> Result<(), ExecutionError> {
        let mut size = 0;
        for owner in owners {
            size += owner.size();
        }
        self.track_size_runtime_operations(size)
    }

    /// Tracks runtime reading of owners
    pub(crate) fn track_runtime_chain_ownership(
        &mut self,
        chain_ownership: &ChainOwnership,
    ) -> Result<(), ExecutionError> {
        let mut size = 0;
        for account_owner in &chain_ownership.super_owners {
            size += account_owner.size();
        }
        for account_owner in chain_ownership.owners.keys() {
            size += account_owner.size() + RUNTIME_OWNER_WEIGHT_SIZE;
        }
        size += RUNTIME_CONSTANT_CHAIN_OWNERSHIP_SIZE;
        self.track_size_runtime_operations(size)
    }

    /// Tracks runtime reading of an application description.
    pub(crate) fn track_runtime_application_description(
        &mut self,
        description: &ApplicationDescription,
    ) -> Result<(), ExecutionError> {
        let parameters_size = description.parameters.len() as u32;
        let required_apps_size =
            description.required_application_ids.len() as u32 * RUNTIME_APPLICATION_ID_SIZE;
        let size =
            RUNTIME_CONSTANT_APPLICATION_DESCRIPTION_SIZE + parameters_size + required_apps_size;
        self.track_size_runtime_operations(size)
    }

    /// Tracks runtime operations.
    fn track_size_runtime_operations(&mut self, size: u32) -> Result<(), ExecutionError> {
        self.tracker.as_mut().bytes_runtime = self
            .tracker
            .as_mut()
            .bytes_runtime
            .checked_add(size)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.bytes_runtime_price(size)?)
    }

    /// Tracks a read operation.
    pub(crate) fn track_read_operation(&mut self) -> Result<(), ExecutionError> {
        self.tracker.as_mut().read_operations = self
            .tracker
            .as_mut()
            .read_operations
            .checked_add(1)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.read_operations_price(1)?)
    }

    /// Tracks a write operation.
    pub(crate) fn track_write_operations(&mut self, count: u32) -> Result<(), ExecutionError> {
        self.tracker.as_mut().write_operations = self
            .tracker
            .as_mut()
            .write_operations
            .checked_add(count)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.write_operations_price(count)?)
    }

    /// Tracks a number of bytes read.
    pub(crate) fn track_bytes_read(&mut self, count: u64) -> Result<(), ExecutionError> {
        self.tracker.as_mut().bytes_read = self
            .tracker
            .as_mut()
            .bytes_read
            .checked_add(count)
            .ok_or(ArithmeticError::Overflow)?;
        if self.tracker.as_mut().bytes_read >= self.policy.maximum_bytes_read_per_block {
            return Err(ExecutionError::ExcessiveRead);
        }
        self.update_balance(self.policy.bytes_read_price(count)?)?;
        Ok(())
    }

    /// Tracks a number of bytes written.
    pub(crate) fn track_bytes_written(&mut self, count: u64) -> Result<(), ExecutionError> {
        self.tracker.as_mut().bytes_written = self
            .tracker
            .as_mut()
            .bytes_written
            .checked_add(count)
            .ok_or(ArithmeticError::Overflow)?;
        if self.tracker.as_mut().bytes_written >= self.policy.maximum_bytes_written_per_block {
            return Err(ExecutionError::ExcessiveWrite);
        }
        self.update_balance(self.policy.bytes_written_price(count)?)?;
        Ok(())
    }

    /// Tracks a number of blob bytes written.
    pub(crate) fn track_blob_read(&mut self, count: u64) -> Result<(), ExecutionError> {
        {
            let tracker = self.tracker.as_mut();
            tracker.blob_bytes_read = tracker
                .blob_bytes_read
                .checked_add(count)
                .ok_or(ArithmeticError::Overflow)?;
            tracker.blobs_read = tracker
                .blobs_read
                .checked_add(1)
                .ok_or(ArithmeticError::Overflow)?;
        }
        self.update_balance(self.policy.blob_read_price(count)?)?;
        Ok(())
    }

    /// Tracks a number of blob bytes published.
    pub fn track_blob_published(&mut self, blob: &Blob) -> Result<(), ExecutionError> {
        self.policy.check_blob_size(blob.content())?;
        let size = blob.content().bytes().len() as u64;
        if blob.is_committee_blob() {
            return Ok(());
        }
        {
            let tracker = self.tracker.as_mut();
            tracker.blob_bytes_published = tracker
                .blob_bytes_published
                .checked_add(size)
                .ok_or(ArithmeticError::Overflow)?;
            tracker.blobs_published = tracker
                .blobs_published
                .checked_add(1)
                .ok_or(ArithmeticError::Overflow)?;
        }
        self.update_balance(self.policy.blob_published_price(size)?)?;
        Ok(())
    }

    /// Tracks a change in the number of bytes stored.
    // TODO(#1536): This is not fully implemented.
    #[allow(dead_code)]
    pub(crate) fn track_stored_bytes(&mut self, delta: i32) -> Result<(), ExecutionError> {
        self.tracker.as_mut().bytes_stored = self
            .tracker
            .as_mut()
            .bytes_stored
            .checked_add(delta)
            .ok_or(ArithmeticError::Overflow)?;
        Ok(())
    }

    /// Returns the remaining time services can spend executing as oracles.
    pub(crate) fn remaining_service_oracle_execution_time(
        &self,
    ) -> Result<Duration, ExecutionError> {
        let tracker = self.tracker.as_ref();
        let spent_execution_time = tracker.service_oracle_execution;
        let limit = Duration::from_millis(self.policy.maximum_service_oracle_execution_ms);

        limit
            .checked_sub(spent_execution_time)
            .ok_or(ExecutionError::MaximumServiceOracleExecutionTimeExceeded)
    }

    /// Tracks a call to a service to run as an oracle.
    pub(crate) fn track_service_oracle_call(&mut self) -> Result<(), ExecutionError> {
        self.tracker.as_mut().service_oracle_queries = self
            .tracker
            .as_mut()
            .service_oracle_queries
            .checked_add(1)
            .ok_or(ArithmeticError::Overflow)?;
        self.update_balance(self.policy.service_as_oracle_query)
    }

    /// Tracks the time spent executing the service as an oracle.
    pub(crate) fn track_service_oracle_execution(
        &mut self,
        execution_time: Duration,
    ) -> Result<(), ExecutionError> {
        let tracker = self.tracker.as_mut();
        let spent_execution_time = &mut tracker.service_oracle_execution;
        let limit = Duration::from_millis(self.policy.maximum_service_oracle_execution_ms);

        *spent_execution_time = spent_execution_time.saturating_add(execution_time);

        ensure!(
            *spent_execution_time < limit,
            ExecutionError::MaximumServiceOracleExecutionTimeExceeded
        );

        Ok(())
    }

    /// Tracks the size of a response produced by an oracle.
    pub(crate) fn track_service_oracle_response(
        &mut self,
        response_bytes: usize,
    ) -> Result<(), ExecutionError> {
        ensure!(
            response_bytes as u64 <= self.policy.maximum_oracle_response_bytes,
            ExecutionError::ServiceOracleResponseTooLarge
        );

        Ok(())
    }
}

impl<Account, Tracker> ResourceController<Account, Tracker>
where
    Tracker: AsMut<ResourceTracker>,
{
    /// Tracks the serialized size of a block, or parts of it.
    pub fn track_block_size_of(&mut self, data: &impl Serialize) -> Result<(), ExecutionError> {
        self.track_block_size(bcs::serialized_size(data)?)
    }

    /// Tracks the serialized size of a block, or parts of it.
    pub fn track_block_size(&mut self, size: usize) -> Result<(), ExecutionError> {
        let tracker = self.tracker.as_mut();
        tracker.block_size = u64::try_from(size)
            .ok()
            .and_then(|size| tracker.block_size.checked_add(size))
            .ok_or(ExecutionError::BlockTooLarge)?;
        ensure!(
            tracker.block_size <= self.policy.maximum_block_size,
            ExecutionError::BlockTooLarge
        );
        Ok(())
    }
}

impl ResourceController<Option<AccountOwner>, ResourceTracker> {
    /// Provides a reference to the current execution state and obtains a temporary object
    /// where the accounting functions of [`ResourceController`] are available.
    pub async fn with_state<'a, C>(
        &mut self,
        view: &'a mut SystemExecutionStateView<C>,
    ) -> Result<ResourceController<Sources<'a>, &mut ResourceTracker>, ViewError>
    where
        C: Context + Clone + 'static,
    {
        self.with_state_and_grant(view, None).await
    }

    /// Provides a reference to the current execution state as well as an optional grant,
    /// and obtains a temporary object where the accounting functions of
    /// [`ResourceController`] are available.
    pub async fn with_state_and_grant<'a, C>(
        &mut self,
        view: &'a mut SystemExecutionStateView<C>,
        grant: Option<&'a mut Amount>,
    ) -> Result<ResourceController<Sources<'a>, &mut ResourceTracker>, ViewError>
    where
        C: Context + Clone + 'static,
    {
        let mut sources = Vec::new();
        // First, use the grant (e.g. for messages) and otherwise use the chain account
        // (e.g. for blocks and operations).
        if let Some(grant) = grant {
            sources.push(grant);
        } else {
            sources.push(view.balance.get_mut());
        }
        // Then the local account, if any. Currently, any negative fee (e.g. storage
        // refund) goes preferably to this account.
        if let Some(owner) = &self.account {
            if let Some(balance) = view.balances.get_mut(owner).await? {
                sources.push(balance);
            }
        }

        Ok(ResourceController {
            policy: self.policy.clone(),
            tracker: &mut self.tracker,
            account: Sources { sources },
            is_free: self.is_free,
        })
    }
}

// The simplest `BalanceHolder` is an `Amount`.
impl BalanceHolder for Amount {
    fn balance(&self) -> Result<Amount, ArithmeticError> {
        Ok(*self)
    }

    fn try_add_assign(&mut self, other: Amount) -> Result<(), ArithmeticError> {
        self.try_add_assign(other)
    }

    fn try_sub_assign(&mut self, other: Amount) -> Result<(), ArithmeticError> {
        self.try_sub_assign(other)
    }
}

// This is also needed for the default instantiation `ResourceController<Amount, ResourceTracker>`.
// See https://doc.rust-lang.org/std/convert/trait.AsMut.html#reflexivity for general context.
impl AsMut<ResourceTracker> for ResourceTracker {
    fn as_mut(&mut self) -> &mut Self {
        self
    }
}

impl AsRef<ResourceTracker> for ResourceTracker {
    fn as_ref(&self) -> &Self {
        self
    }
}

/// A temporary object holding a number of references to funding sources.
pub struct Sources<'a> {
    sources: Vec<&'a mut Amount>,
}

impl BalanceHolder for Sources<'_> {
    fn balance(&self) -> Result<Amount, ArithmeticError> {
        let mut amount = Amount::ZERO;
        for source in &self.sources {
            amount.try_add_assign(**source)?;
        }
        Ok(amount)
    }

    fn try_add_assign(&mut self, other: Amount) -> Result<(), ArithmeticError> {
        // Try to credit the owner account first.
        // TODO(#1648): This may need some additional design work.
        let source = self.sources.last_mut().expect("at least one source");
        source.try_add_assign(other)
    }

    fn try_sub_assign(&mut self, mut other: Amount) -> Result<(), ArithmeticError> {
        for source in &mut self.sources {
            if source.try_sub_assign(other).is_ok() {
                return Ok(());
            }
            other.try_sub_assign(**source).expect("*source < other");
            **source = Amount::ZERO;
        }
        if other > Amount::ZERO {
            Err(ArithmeticError::Underflow)
        } else {
            Ok(())
        }
    }
}