1use crate::{
19 Config, H256,
20 access_list::{StorageOp, Warmth},
21 limits,
22 metering::Token,
23 weightinfo_extension::OnFinalizeBlockParts,
24 weights::WeightInfo,
25};
26use frame_support::{
27 traits::Get,
28 weights::{Weight, constants::WEIGHT_REF_TIME_PER_SECOND},
29};
30
31const GAS_PER_SECOND: u64 = 40_000_000;
36
37const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
41
42pub const BENCH_MIN_EVM_INIT_CODE_LEN: u32 = 1;
44
45#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
46#[derive(Copy, Clone)]
47pub enum RuntimeCosts {
48 HostFn,
50 EvmMemoryGrow { words: u32, allocation_words: u32 },
53 EvmMemoryCopyOut(u32),
55 EvmCopyToContract(u32),
57 ExtCodeCopy(u32),
59 CopyFromContract(u32),
61 CopyToContract(u32),
63 CallDataLoad,
65 CallDataCopy(u32),
67 Caller,
69 CallDataSize,
71 ReturnDataSize,
73 ToAccountId,
75 Origin,
77 CodeHash,
79 OwnCodeHash,
81 CodeSize,
83 CallerIsOrigin,
85 CallerIsRoot,
87 OriginIsRoot,
89 Address,
91 RefTimeLeft,
93 WeightLeft,
95 Balance,
97 BalanceOf,
99 ValueTransferred,
101 MinimumBalance,
103 BlockNumber,
105 BlockHash,
107 BlockAuthor,
109 GasPrice,
111 BaseFee,
113 Now,
115 GasLimit,
117 Terminate { code_removed: bool },
119 DepositEvent { num_topic: u32, len: u32 },
129 SetStorage { new_bytes: u32, old_bytes: u32, kind: StorageAccessKind },
132 ClearStorage { len: u32, kind: StorageAccessKind },
134 ContainsStorage { len: u32, kind: StorageAccessKind },
136 GetStorage { len: u32, kind: StorageAccessKind },
138 TakeStorage { len: u32, kind: StorageAccessKind },
140 CallBase,
142 DelegateCallBase,
144 PrecompileBase,
146 PrecompileWithInfoBase,
148 PrecompileDecode(u32),
150 CallTransferSurcharge { dust_transfer: bool },
153 CallInputCloned(u32),
155 Instantiate { input_data_len: u32, balance_transfer: bool, dust_transfer: bool },
157 Create { init_code_len: u32, balance_transfer: bool, dust_transfer: bool },
159 Ripemd160(u32),
161 HashSha256(u32),
163 HashKeccak256(u32),
165 HashBlake256(u32),
168 HashBlake128(u32),
170 EcdsaRecovery,
172 P256Verify,
174 Sr25519Verify(u32),
176 Precompile(Weight),
178 EcdsaToEthAddress,
180 GetImmutableData(u32),
182 SetImmutableData(u32),
184 Bn128Add,
186 Bn128Mul,
188 Bn128Pairing(u32),
190 Identity(u32),
192 Blake2F(u32),
194 Modexp(u64),
196 Delegations { new_accounts: u32, existing_accounts: u32, invalid_accounts: u32 },
205}
206
207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
209pub enum StorageAccessKind {
210 Persistent(Warmth),
212 Transient,
214}
215
216impl StorageAccessKind {
217 pub fn new(transient: bool, warmth: impl FnOnce() -> Warmth) -> Self {
219 if transient { Self::Transient } else { Self::Persistent(warmth()) }
220 }
221}
222
223macro_rules! cost_storage {
228 (write_transient, $name:ident $(, $arg:expr )*) => {
229 T::WeightInfo::$name($( $arg ),*)
230 .saturating_add(T::WeightInfo::rollback_transient_storage())
231 .saturating_add(T::WeightInfo::set_transient_storage_full()
232 .saturating_sub(T::WeightInfo::set_transient_storage_empty()))
233 };
234
235 (read_transient, $name:ident $(, $arg:expr )*) => {
236 T::WeightInfo::$name($( $arg ),*)
237 .saturating_add(T::WeightInfo::get_transient_storage_full()
238 .saturating_sub(T::WeightInfo::get_transient_storage_empty()))
239 };
240
241 (write_cold, $name:ident $(, $arg:expr )*) => {
242 T::WeightInfo::$name($( $arg ),*)
243 .saturating_add(T::WeightInfo::set_storage_full()
244 .saturating_sub(T::WeightInfo::set_storage_empty()))
245 };
246
247 (read_cold, $name:ident $(, $arg:expr )*) => {
248 T::WeightInfo::$name($( $arg ),*)
249 .saturating_add(T::WeightInfo::get_storage_full()
250 .saturating_sub(T::WeightInfo::get_storage_empty()))
251 };
252}
253
254macro_rules! cost_args {
255 ($name:ident, $( $arg: expr ),+) => {
257 (T::WeightInfo::$name($( $arg ),+).saturating_sub(cost_args!(@call_zero $name, $( $arg ),+)))
258 };
259 (@call_zero $name:ident, $( $arg:expr ),*) => {
261 T::WeightInfo::$name($( cost_args!(@replace_token $arg) ),*)
262 };
263 (@replace_token $_in:tt) => { 0 };
265}
266
267impl RuntimeCosts {
268 fn hot_storage_overlay_overhead<T: Config>() -> Weight {
270 let per_read = |weight_fn: fn(u32) -> Weight| weight_fn(1).saturating_sub(weight_fn(0));
271 per_read(T::WeightInfo::overlay_probe_full)
272 .saturating_sub(per_read(T::WeightInfo::overlay_probe_empty))
273 }
274
275 fn hot_write_surcharge<T: Config>() -> Weight {
279 let db = T::DbWeight::get();
280 db.writes(1).saturating_sub(db.reads(1))
281 }
282
283 fn weight_for_storage_access<T: Config>(
285 op: StorageOp,
286 kind: StorageAccessKind,
287 cold: impl FnOnce() -> Weight,
288 hot: impl FnOnce() -> Weight,
289 transient: impl FnOnce() -> Weight,
290 ) -> Weight {
291 match kind {
292 StorageAccessKind::Persistent(Warmth::Cold { revertible }) => {
293 let cost = cold()
294 .saturating_add(T::WeightInfo::access_list_touch_cold_full())
295 .saturating_sub(T::WeightInfo::access_list_touch_cold_empty());
296 if revertible {
297 cost.saturating_add(T::WeightInfo::access_list_rollback_amortization())
298 } else {
299 cost
300 }
301 },
302 StorageAccessKind::Persistent(Warmth::Hot { charged }) => hot()
303 .saturating_add(if charged.covers(op) {
304 Weight::zero()
305 } else {
306 Self::hot_write_surcharge::<T>()
307 })
308 .saturating_add(Self::hot_storage_overlay_overhead::<T>())
309 .saturating_add(T::WeightInfo::access_list_touch_hot_full())
310 .saturating_sub(T::WeightInfo::access_list_touch_hot_single_element()),
311 StorageAccessKind::Transient => transient(),
312 }
313 }
314}
315
316impl<T: Config> Token<T> for RuntimeCosts {
317 fn influence_lowest_weight_limit(&self) -> bool {
318 true
319 }
320
321 fn weight(&self) -> Weight {
322 use self::RuntimeCosts::*;
323 match *self {
324 HostFn => cost_args!(noop_host_fn, 1),
325 EvmMemoryGrow { words, allocation_words } => {
326 let grow = cost_args!(evm_memory_grow, words);
327 let allocate = if allocation_words == 0 {
328 Weight::zero()
329 } else {
330 T::WeightInfo::evm_memory_reallocate(allocation_words)
331 };
332 grow.saturating_add(allocate)
333 },
334 EvmMemoryCopyOut(len) => {
335 if len == 0 {
336 Weight::zero()
337 } else {
338 T::WeightInfo::evm_memory_copy_out(len)
339 }
340 },
341 ExtCodeCopy(len) => {
344 T::WeightInfo::extcodecopy(len).saturating_sub(T::WeightInfo::seal_code_size())
345 },
346 CopyToContract(len) => T::WeightInfo::seal_copy_to_contract(len),
347 EvmCopyToContract(len) => cost_args!(seal_copy_to_contract, len),
348 CopyFromContract(len) => T::WeightInfo::seal_return(len),
349 CallDataSize => T::WeightInfo::seal_call_data_size(),
350 ReturnDataSize => T::WeightInfo::seal_return_data_size(),
351 CallDataLoad => T::WeightInfo::seal_call_data_load(),
352 CallDataCopy(len) => T::WeightInfo::seal_call_data_copy(len),
353 Caller => T::WeightInfo::seal_caller(),
354 Origin => T::WeightInfo::seal_origin(),
355 ToAccountId => T::WeightInfo::to_account_id(),
356 CodeHash => T::WeightInfo::seal_code_hash(),
357 CodeSize => T::WeightInfo::seal_code_size(),
358 OwnCodeHash => T::WeightInfo::own_code_hash(),
359 CallerIsOrigin => T::WeightInfo::caller_is_origin(),
360 CallerIsRoot => T::WeightInfo::caller_is_root(),
361 OriginIsRoot => T::WeightInfo::origin_is_root(),
362 Address => T::WeightInfo::seal_address(),
363 RefTimeLeft => T::WeightInfo::seal_ref_time_left(),
364 WeightLeft => T::WeightInfo::weight_left(),
365 Balance => T::WeightInfo::seal_balance(),
366 BalanceOf => T::WeightInfo::seal_balance_of(),
367 ValueTransferred => T::WeightInfo::seal_value_transferred(),
368 MinimumBalance => T::WeightInfo::minimum_balance(),
369 BlockNumber => T::WeightInfo::seal_block_number(),
370 BlockHash => T::WeightInfo::seal_block_hash(),
371 BlockAuthor => T::WeightInfo::seal_block_author(),
372 GasPrice => T::WeightInfo::seal_gas_price(),
373 BaseFee => T::WeightInfo::seal_base_fee(),
374 Now => T::WeightInfo::seal_now(),
375 GasLimit => T::WeightInfo::seal_gas_limit(),
376 Terminate { code_removed } => {
377 if code_removed {
379 T::WeightInfo::seal_terminate(code_removed.into())
380 .saturating_add(T::WeightInfo::seal_terminate_logic())
381 } else {
382 T::WeightInfo::seal_terminate(code_removed.into())
383 }
384 },
385 DepositEvent { num_topic, len } => {
386 let topic_bytes =
387 num_topic.min(limits::NUM_EVENT_TOPICS) * H256::len_bytes() as u32;
388 let event_bytes = len.saturating_add(topic_bytes);
389 T::WeightInfo::seal_deposit_event(num_topic, len)
390 .saturating_add(T::WeightInfo::on_finalize_block_per_event(event_bytes))
391 .saturating_add(Weight::from_parts(
392 limits::EXTRA_EVENT_CHARGE_PER_BYTE.saturating_mul(event_bytes.into()),
393 0,
394 ))
395 },
396 SetStorage { new_bytes, old_bytes, kind } => Self::weight_for_storage_access::<T>(
397 StorageOp::Write,
398 kind,
399 || cost_storage!(write_cold, seal_set_storage, new_bytes, old_bytes),
400 || T::WeightInfo::seal_set_storage_hot(new_bytes, old_bytes),
401 || cost_storage!(write_transient, seal_set_transient_storage, new_bytes, old_bytes),
402 ),
403 ClearStorage { len, kind } => Self::weight_for_storage_access::<T>(
404 StorageOp::Write,
405 kind,
406 || cost_storage!(write_cold, clear_storage, len),
407 || T::WeightInfo::clear_storage_hot(len),
408 || cost_storage!(write_transient, seal_clear_transient_storage, len),
409 ),
410 ContainsStorage { len, kind } => Self::weight_for_storage_access::<T>(
411 StorageOp::Read,
412 kind,
413 || cost_storage!(read_cold, contains_storage, len),
414 || T::WeightInfo::contains_storage_hot(len),
415 || cost_storage!(read_transient, seal_contains_transient_storage, len),
416 ),
417 GetStorage { len, kind } => Self::weight_for_storage_access::<T>(
418 StorageOp::Read,
419 kind,
420 || cost_storage!(read_cold, seal_get_storage, len),
421 || T::WeightInfo::seal_get_storage_hot(len),
422 || cost_storage!(read_transient, seal_get_transient_storage, len),
423 ),
424 TakeStorage { len, kind } => Self::weight_for_storage_access::<T>(
425 StorageOp::Write,
426 kind,
427 || cost_storage!(write_cold, take_storage, len),
428 || T::WeightInfo::take_storage_hot(len),
429 || cost_storage!(write_transient, seal_take_transient_storage, len),
430 ),
431 CallBase => T::WeightInfo::seal_call(0),
432 DelegateCallBase => T::WeightInfo::seal_delegate_call(),
433 PrecompileBase => T::WeightInfo::seal_call_precompile(0, 0),
434 PrecompileWithInfoBase => T::WeightInfo::seal_call_precompile(1, 0),
435 PrecompileDecode(len) => cost_args!(seal_call_precompile, 0, len),
436 CallTransferSurcharge { dust_transfer } => {
437 T::WeightInfo::seal_call_transfer(dust_transfer.into())
440 .max(T::WeightInfo::seal_call_transfer_to_existing(dust_transfer.into()))
441 .saturating_sub(T::WeightInfo::seal_call(0))
442 },
443 CallInputCloned(len) => cost_args!(seal_call, len),
444 Instantiate { input_data_len, balance_transfer, dust_transfer } => {
445 let transfer = if balance_transfer || dust_transfer {
446 T::WeightInfo::seal_instantiate_transfer(dust_transfer.into())
447 .saturating_sub(T::WeightInfo::seal_instantiate(0))
448 } else {
449 Weight::zero()
450 };
451 T::WeightInfo::seal_instantiate(input_data_len).saturating_add(transfer)
452 },
453 Create { init_code_len, balance_transfer, dust_transfer } => {
454 let transfer = if balance_transfer || dust_transfer {
455 T::WeightInfo::evm_instantiate_transfer(dust_transfer.into())
456 .saturating_sub(T::WeightInfo::evm_instantiate(BENCH_MIN_EVM_INIT_CODE_LEN))
457 } else {
458 Weight::zero()
459 };
460 T::WeightInfo::evm_instantiate(init_code_len).saturating_add(transfer)
461 },
462 HashSha256(len) => T::WeightInfo::sha2_256(len),
463 Ripemd160(len) => T::WeightInfo::ripemd_160(len),
464 HashKeccak256(len) => T::WeightInfo::seal_hash_keccak_256(len),
465 HashBlake256(len) => T::WeightInfo::hash_blake2_256(len),
466 HashBlake128(len) => T::WeightInfo::hash_blake2_128(len),
467 EcdsaRecovery => T::WeightInfo::ecdsa_recover(),
468 P256Verify => T::WeightInfo::p256_verify(),
469 Sr25519Verify(len) => T::WeightInfo::seal_sr25519_verify(len),
470 Precompile(weight) => weight,
471 EcdsaToEthAddress => T::WeightInfo::seal_ecdsa_to_eth_address(),
472 GetImmutableData(len) => T::WeightInfo::seal_get_immutable_data(len),
473 SetImmutableData(len) => T::WeightInfo::seal_set_immutable_data(len),
474 Bn128Add => T::WeightInfo::bn128_add(),
475 Bn128Mul => T::WeightInfo::bn128_mul(),
476 Bn128Pairing(len) => T::WeightInfo::bn128_pairing(len),
477 Identity(len) => T::WeightInfo::identity(len),
478 Blake2F(rounds) => T::WeightInfo::blake2f(rounds),
479 Modexp(gas) => Weight::from_parts(gas.saturating_mul(WEIGHT_PER_GAS), 0),
480 Delegations { new_accounts, existing_accounts, invalid_accounts } => {
481 T::WeightInfo::process_new_account_authorization(new_accounts)
482 .saturating_add(T::WeightInfo::process_existing_account_authorization(
483 existing_accounts,
484 ))
485 .saturating_add(T::WeightInfo::process_invalid_authorization(invalid_accounts))
486 },
487 }
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494 use crate::tests::Test;
495
496 #[test]
497 fn storage_pricing_by_access_kind() {
498 let len = 64u32;
499 let cold = StorageAccessKind::Persistent(Warmth::Cold { revertible: false });
500 let cold_revertible = StorageAccessKind::Persistent(Warmth::Cold { revertible: true });
501 let hot_kinds = [
502 StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Read }),
503 StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Write }),
504 ];
505
506 let with_kind = |kind: StorageAccessKind| -> Vec<RuntimeCosts> {
507 vec![
508 RuntimeCosts::GetStorage { len, kind },
509 RuntimeCosts::SetStorage { new_bytes: len, old_bytes: len, kind },
510 RuntimeCosts::ClearStorage { len, kind },
511 RuntimeCosts::ContainsStorage { len, kind },
512 RuntimeCosts::TakeStorage { len, kind },
513 ]
514 };
515
516 for hot in hot_kinds {
517 for (cold_cost, hot_cost) in with_kind(cold).into_iter().zip(with_kind(hot)) {
518 let cold_weight = <RuntimeCosts as Token<Test>>::weight(&cold_cost);
519 let hot_weight = <RuntimeCosts as Token<Test>>::weight(&hot_cost);
520 assert!(
521 cold_weight.ref_time() > hot_weight.ref_time(),
522 "expected cold > hot ref_time for {cold_cost:?}: \
523 cold={cold_weight:?} hot={hot_weight:?}",
524 );
525 assert_eq!(
526 hot_weight.proof_size(),
527 0,
528 "hot proof_size {hot_cost:?}: {hot_weight:?}"
529 );
530 assert!(
531 cold_weight.proof_size() > 0,
532 "cold proof_size {cold_cost:?}: {cold_weight:?}",
533 );
534 }
535 }
536
537 for (rev_cost, non_rev_cost) in with_kind(cold_revertible).into_iter().zip(with_kind(cold))
538 {
539 let rev_weight = <RuntimeCosts as Token<Test>>::weight(&rev_cost);
540 let non_rev_weight = <RuntimeCosts as Token<Test>>::weight(&non_rev_cost);
541 assert!(
542 rev_weight.ref_time() > non_rev_weight.ref_time(),
543 "expected revertible > non-revertible ref_time for {rev_cost:?}: \
544 rev={rev_weight:?} non={non_rev_weight:?}",
545 );
546 assert_eq!(
547 rev_weight.proof_size(),
548 non_rev_weight.proof_size(),
549 "proof_size differs {rev_cost:?}: rev={rev_weight:?} non={non_rev_weight:?}",
550 );
551 }
552
553 for transient_cost in with_kind(StorageAccessKind::Transient) {
554 let weight = <RuntimeCosts as Token<Test>>::weight(&transient_cost);
555 assert_eq!(
556 weight.proof_size(),
557 0,
558 "transient storage is priced without proof: {transient_cost:?}: {weight:?}"
559 );
560 assert!(
561 weight.ref_time() > 0,
562 "transient storage ref_time must be above zero: {transient_cost:?}: {weight:?}"
563 );
564 }
565 }
566
567 #[test]
568 fn the_first_hot_write_pays_the_surcharge() {
569 const LEN: u32 = 64;
570 let weight = |cost: &RuntimeCosts| <RuntimeCosts as Token<Test>>::weight(cost);
571
572 let surcharge = RuntimeCosts::hot_write_surcharge::<Test>();
573 let db = <Test as frame_system::Config>::DbWeight::get();
574 assert!(
575 surcharge.ref_time() > 0 && surcharge.ref_time() < db.writes(1).ref_time(),
576 "the surcharge is part of a write: above zero, below all of it: {surcharge:?}",
577 );
578 assert_eq!(surcharge.proof_size(), 0, "the surcharge adds no proof: {surcharge:?}");
579
580 let read_paid = StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Read });
581 let write_paid = StorageAccessKind::Persistent(Warmth::Hot { charged: StorageOp::Write });
582
583 let write_costs = |kind: StorageAccessKind| {
584 [
585 RuntimeCosts::SetStorage { new_bytes: LEN, old_bytes: LEN, kind },
586 RuntimeCosts::ClearStorage { len: LEN, kind },
587 RuntimeCosts::TakeStorage { len: LEN, kind },
588 ]
589 };
590 for (write_to_read_paid_slot, write_to_write_paid_slot) in
591 write_costs(read_paid).into_iter().zip(write_costs(write_paid))
592 {
593 assert_eq!(
594 weight(&write_to_read_paid_slot).saturating_sub(weight(&write_to_write_paid_slot)),
595 surcharge,
596 "a write to a read-paid slot pays exactly the surcharge: \
597 {write_to_read_paid_slot:?}",
598 );
599 }
600
601 let read_costs = |kind: StorageAccessKind| {
602 [
603 RuntimeCosts::GetStorage { len: LEN, kind },
604 RuntimeCosts::ContainsStorage { len: LEN, kind },
605 ]
606 };
607 for (read_of_read_paid_slot, read_of_write_paid_slot) in
608 read_costs(read_paid).into_iter().zip(read_costs(write_paid))
609 {
610 assert_eq!(
611 weight(&read_of_read_paid_slot),
612 weight(&read_of_write_paid_slot),
613 "a read is covered at either paid level: {read_of_read_paid_slot:?}",
614 );
615 }
616 }
617
618 #[test]
619 fn a_transient_access_never_consults_the_access_list() {
620 assert_eq!(
621 StorageAccessKind::new(true, || unreachable!("transient storage has no warmth")),
622 StorageAccessKind::Transient,
623 );
624 }
625
626 #[test]
627 fn hot_storage_overlay_overhead_is_not_zero() {
628 let overhead = RuntimeCosts::hot_storage_overlay_overhead::<Test>();
629 assert!(
630 overhead.ref_time() > 0,
631 "the per-read cost of overlay_probe_full must stay above overlay_probe_empty",
632 );
633 assert_eq!(overhead.proof_size(), 0, "the overlay probe is in-memory only: {overhead:?}");
634 }
635
636 #[test]
637 fn value_transfers_pay_a_surcharge() {
638 let weight = |cost: RuntimeCosts| <RuntimeCosts as Token<Test>>::weight(&cost);
639
640 let call = |dust_transfer| weight(RuntimeCosts::CallTransferSurcharge { dust_transfer });
641 assert!(call(false).ref_time() > 0, "a call with value must pay for its transfer");
642 assert!(call(true).ref_time() > call(false).ref_time(), "a call with dust must cost more");
643
644 let instantiate: fn(bool, bool) -> RuntimeCosts = |balance_transfer, dust_transfer| {
645 RuntimeCosts::Instantiate { input_data_len: 0, balance_transfer, dust_transfer }
646 };
647 let create: fn(bool, bool) -> RuntimeCosts = |balance_transfer, dust_transfer| {
648 RuntimeCosts::Create { init_code_len: 0, balance_transfer, dust_transfer }
649 };
650
651 for (name, cost_of) in [("instantiate", instantiate), ("create", create)] {
652 let surcharge = |balance_transfer, dust_transfer| {
653 weight(cost_of(balance_transfer, dust_transfer))
654 .saturating_sub(weight(cost_of(false, false)))
655 };
656 assert!(
657 surcharge(true, false).ref_time() > 0,
658 "{name} with value must pay for its transfer",
659 );
660 assert!(
661 surcharge(true, true).ref_time() > surcharge(true, false).ref_time(),
662 "{name} with dust must cost more",
663 );
664 assert_eq!(
665 surcharge(false, true),
666 surcharge(true, true),
667 "{name} with only dust does the same work as with value and dust",
668 );
669 }
670 }
671}