-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathprice_list.rs
1370 lines (1189 loc) · 51 KB
/
price_list.rs
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021-2023 Protocol Labs
// Copyright 2019-2022 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::collections::HashMap;
use std::ops::Mul;
use anyhow::Context;
use fvm_shared::clock::ChainEpoch;
#[cfg(feature = "verify-signature")]
use fvm_shared::crypto::signature::SignatureType;
use fvm_shared::piece::PieceInfo;
use fvm_shared::sector::{
AggregateSealVerifyProofAndInfos, RegisteredPoStProof, RegisteredSealProof, ReplicaUpdateInfo,
SealVerifyInfo, WindowPoStVerifyInfo,
};
use fvm_shared::version::NetworkVersion;
use fvm_shared::ActorID;
use fvm_wasm_instrument::gas_metering::{InstructionCost, Operator, Rules};
use lazy_static::lazy_static;
use num_traits::Zero;
use super::GasCharge;
use crate::gas::Gas;
use crate::kernel::SupportedHashes;
// Each element reserves a `usize` in the table, so we charge 8 bytes per pointer.
// https://docs.rs/wasmtime/2.0.2/wasmtime/struct.InstanceLimits.html#structfield.table_elements
const TABLE_ELEMENT_SIZE: u32 = 8;
// The maximum overhead (in bytes) of a single event when encoded into CBOR.
//
// 1: CBOR tuple with 2 fields (StampedEvent)
// 9: Emitter ID
// 2: Entry array overhead (max size 255)
const EVENT_OVERHEAD: u64 = 12;
// The maximum overhead (in bytes) of a single event entry when encoded into CBOR.
//
// 1: CBOR tuple with 4 fields
// 1: Flags (will adjust as more flags are added)
// 2: Key major type + length (up to 255 bytes)
// 2: Codec major type + value (codec should be <= 255)
// 3: Value major type + length (up to 8192 bytes)
const EVENT_ENTRY_OVERHEAD: u64 = 9;
/// Create a mapping from enum items to values in a way that guarantees at compile
/// time that we did not miss any member, in any of the prices, even if the enum
/// gets a new member later.
///
/// # Example
///
/// ```
/// use fvm::total_enum_map;
/// use std::collections::HashMap;
///
/// #[derive(Hash, Eq, PartialEq)]
/// enum Foo {
/// Bar,
/// Baz,
/// }
///
/// let foo_cost: HashMap<Foo, u8> = total_enum_map! {
/// Foo {
/// Bar => 10,
/// Baz => 20
/// }
/// };
/// ```
#[macro_export]
macro_rules! total_enum_map {
($en:ident { $($item:ident => $value:expr),+ $(,)? }) => {
[$($en::$item),+].into_iter().map(|m| {
// This will not compile if a case is missing.
let v = match m {
$($en::$item => $value),+
};
(m, v)
}).collect()
};
}
lazy_static! {
static ref WATERMELON_PRICES: PriceList = PriceList {
on_chain_message_compute: ScalingCost::fixed(Gas::new(38863)),
on_chain_message_storage: ScalingCost {
flat: Gas::new(36*1300),
scale: Gas::new(1300),
},
on_chain_return_compute: ScalingCost::zero(),
on_chain_return_storage: ScalingCost {
flat: Zero::zero(),
scale: Gas::new(1300),
},
send_transfer_funds: Gas::new(6000),
send_invoke_method: Gas::new(75000),
actor_lookup: Gas::new(500_000),
actor_update: Gas::new(475_000),
actor_create_storage: Gas::new(650_000),
address_lookup: Gas::new(1_050_000),
address_assignment: Gas::new(1_000_000),
#[cfg(feature = "verify-signature")]
sig_cost: total_enum_map!{
SignatureType {
Secp256k1 => ScalingCost {
flat: Gas::new(1637292),
scale: Gas::new(10),
},
BLS => ScalingCost{
flat: Gas::new(16598605),
scale: Gas::new(26),
},
}
},
secp256k1_recover_cost: Gas::new(1637292),
bls_pairing_cost: Gas::new(8299302),
bls_hashing_cost: ScalingCost {
flat: Gas::zero(),
scale: Gas::new(7),
},
hashing_cost: total_enum_map! {
SupportedHashes {
Sha2_256 => ScalingCost {
flat: Gas::zero(),
scale: Gas::new(7)
},
Blake2b256 => ScalingCost {
flat: Gas::zero(),
scale: Gas::new(10)
},
Blake2b512 => ScalingCost {
flat: Gas::zero(),
scale: Gas::new(10)
},
Keccak256 => ScalingCost {
flat: Gas::zero(),
scale: Gas::new(33)
},
Ripemd160 => ScalingCost {
flat: Gas::zero(),
scale: Gas::new(35)
}
}
},
compute_unsealed_sector_cid_base: Gas::new(98647),
verify_seal_base: Gas::new(2000), // TODO revisit potential removal of this
verify_aggregate_seal_per: [
(
RegisteredSealProof::StackedDRG32GiBV1P1,
Gas::new(449900)
),
(
RegisteredSealProof::StackedDRG64GiBV1P1,
Gas::new(359272)
)
].iter().copied().collect(),
verify_aggregate_seal_steps: [
(
RegisteredSealProof::StackedDRG32GiBV1P1,
StepCost (
vec![
Step{start: 4, cost: Gas::new(103994170)},
Step{start: 7, cost: Gas::new(112356810)},
Step{start: 13, cost: Gas::new(122912610)},
Step{start: 26, cost: Gas::new(137559930)},
Step{start: 52, cost: Gas::new(162039100)},
Step{start: 103, cost: Gas::new(210960780)},
Step{start: 205, cost: Gas::new(318351180)},
Step{start: 410, cost: Gas::new(528274980)},
]
)
),
(
RegisteredSealProof::StackedDRG64GiBV1P1,
StepCost (
vec![
Step{start: 4, cost: Gas::new(102581240)},
Step{start: 7, cost: Gas::new(110803030)},
Step{start: 13, cost: Gas::new(120803700)},
Step{start: 26, cost: Gas::new(134642130)},
Step{start: 52, cost: Gas::new(157357890)},
Step{start: 103, cost: Gas::new(203017690)},
Step{start: 205, cost: Gas::new(304253590)},
Step{start: 410, cost: Gas::new(509880640)},
]
)
)
].iter()
.cloned()
.collect(),
verify_consensus_fault: Gas::new(516422),
verify_replica_update: Gas::new(36316136),
verify_post_lookup: [
(RegisteredPoStProof::StackedDRGWindow512MiBV1P1,
ScalingCost {
flat: Gas::new(117680921),
scale: Gas::new(43780),
},
),
(
RegisteredPoStProof::StackedDRGWindow32GiBV1P1,
ScalingCost {
flat: Gas::new(117680921),
scale: Gas::new(43780),
},
),
(
RegisteredPoStProof::StackedDRGWindow64GiBV1P1,
ScalingCost {
flat: Gas::new(117680921),
scale: Gas::new(43780),
},
),
]
.iter()
.copied()
.collect(),
lookback_cost: ScalingCost {
// 5800 * 19 based on walking up the blockchain skipping 20 epochs at a time,
// 15000 for the cost of the base operation (randomness / CID computation),
// 21000 for the extern cost
flat: Gas::new(5800*19 + 15000 + 21000),
scale: Gas::new(75),
},
block_allocate: ScalingCost {
flat: Gas::zero(),
scale: Gas::new(2),
},
block_memcpy: ScalingCost {
flat: Gas::zero(),
scale: Gas::from_milligas(400),
},
block_memory_retention_minimum: ScalingCost {
flat: Gas::zero(),
scale: Gas::new(10),
},
block_open: ScalingCost {
// This was benchmarked (#1264) at 187440 gas/read.
flat: Gas::new(187440),
// It costs takes about 0.562 ns/byte (5.6gas) to "read" from a client. However, that
// includes one allocation and memory copy, which we charge for separately.
//
// We disable this charge now because it's entirely covered by the "memory retention"
// cost. If we do drop the memory retention cost, we need to re-enable this.
/* scale: Gas::from_milligas(3200), */
scale: Gas::zero(),
},
block_persist_storage: ScalingCost {
flat: Gas::new(334000), // ~ Assume about 100 bytes of metadata per block.
scale: Gas::new(3340),
},
block_persist_compute: Gas::new(172000),
// TODO(#1347)
builtin_actor_manifest_lookup: Zero::zero(),
// TODO(#1347)
network_context: Zero::zero(),
// TODO(#1347)
message_context: Zero::zero(),
install_wasm_per_byte_cost: Zero::zero(),
wasm_rules: WasmGasPrices{
// Use the default instruction cost of 4 everywhere.
instruction_default: Gas::new(4),
math_default: Gas::new(4),
jump_unconditional: Gas::new(4),
jump_conditional: Gas::new(4),
jump_indirect: Gas::new(4),
// Don't add any additional costs for calls/memory access for now.
call: Zero::zero(),
memory_fill_base_cost: Gas::zero(),
memory_access_cost: Gas::zero(),
// Charge 0.4gas/byte for copying/fill.
memory_copy_per_byte_cost: Gas::from_milligas(400),
memory_fill_per_byte_cost: Gas::from_milligas(400),
host_call_cost: Gas::new(14000),
},
event_per_entry: ScalingCost {
flat: Gas::new(2000),
scale: Gas::new(1400),
},
utf8_validation: ScalingCost {
flat: Gas::new(500),
scale: Gas::new(16),
},
// Preloaded actor IDs per FIP-0055.
preloaded_actors: vec![0, 1, 2, 3, 4, 5, 6, 7, 10, 99],
ipld_cbor_scan_per_cid: Gas::new(400),
ipld_cbor_scan_per_field: Gas::new(35),
ipld_link_tracked: Gas::new(300),
ipld_link_checked: Gas::new(300),
};
}
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
pub(crate) struct ScalingCost {
pub flat: Gas,
pub scale: Gas,
}
impl ScalingCost {
/// Computes the scaled cost for the given value, or saturates.
pub fn apply<V>(&self, value: V) -> Gas
where
Gas: Mul<V, Output = Gas>,
{
self.flat + self.scale * value
}
/// Create a new "fixed" cost. Useful when some network versions scale the cost and others don't.
pub fn fixed(g: Gas) -> Self {
Self {
flat: g,
scale: Gas::zero(),
}
}
/// Create a "zero" scaling cost.
pub fn zero() -> Self {
Self {
flat: Gas::zero(),
scale: Gas::zero(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StepCost(Vec<Step>);
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
pub(crate) struct Step {
start: u64,
cost: Gas,
}
impl StepCost {
pub(crate) fn lookup(&self, x: u64) -> Gas {
self.0
.iter()
.rev() // from the end
.find(|s| s.start <= x) // find the first "start" at or before the target.
.map(|s| s.cost) // and return the cost
.unwrap_or_default() // or zero
}
}
/// Provides prices for operations in the VM.
/// All costs are in milligas.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PriceList {
/// Gas cost charged to the originator of an on-chain message (regardless of
/// whether it succeeds or fails in application) is given by:
/// OnChainMessageBase + len(serialized message)*OnChainMessagePerByte
/// Together, these account for the cost of message propagation and validation,
/// up to but excluding any actual processing by the VM.
/// This is the cost a block producer burns when including an invalid message.
pub(crate) on_chain_message_compute: ScalingCost,
pub(crate) on_chain_message_storage: ScalingCost,
/// Gas cost charged to the originator of a non-nil return value produced
/// by an on-chain message is given by:
/// len(return value)*OnChainReturnValuePerByte
pub(crate) on_chain_return_compute: ScalingCost,
pub(crate) on_chain_return_storage: ScalingCost,
/// Gas cost charged for transferring funds to an actor (compute only).
pub(crate) send_transfer_funds: Gas,
/// Gas cost charged for invoking an actor (compute only).
pub(crate) send_invoke_method: Gas,
/// Gas cost to lookup an actor by address in the init actor's address table.
pub(crate) address_lookup: Gas,
/// Gas cost to assign an address to an actor in the init actor's address table.
pub(crate) address_assignment: Gas,
/// Gas cost of looking up an actor in the common state tree.
pub(crate) actor_lookup: Gas,
/// Gas cost of storing an updated actor in the common state tree.
pub(crate) actor_update: Gas,
/// Storage gas cost for adding a new actor to the state tree.
pub(crate) actor_create_storage: Gas,
/// Gas cost for verifying a cryptographic signature.
#[cfg(feature = "verify-signature")]
pub(crate) sig_cost: HashMap<SignatureType, ScalingCost>,
/// Gas cost for recovering secp256k1 signer public key
pub(crate) secp256k1_recover_cost: Gas,
pub(crate) bls_pairing_cost: Gas,
pub(crate) bls_hashing_cost: ScalingCost,
pub(crate) hashing_cost: HashMap<SupportedHashes, ScalingCost>,
/// Gas cost for walking up the chain.
/// Applied to operations like getting randomness, tipset CIDs, etc.
pub(crate) lookback_cost: ScalingCost,
pub(crate) compute_unsealed_sector_cid_base: Gas,
pub(crate) verify_seal_base: Gas,
pub(crate) verify_aggregate_seal_per: HashMap<RegisteredSealProof, Gas>,
pub(crate) verify_aggregate_seal_steps: HashMap<RegisteredSealProof, StepCost>,
pub(crate) verify_post_lookup: HashMap<RegisteredPoStProof, ScalingCost>,
pub(crate) verify_consensus_fault: Gas,
pub(crate) verify_replica_update: Gas,
/// Gas cost per byte copied.
pub(crate) block_memcpy: ScalingCost,
/// Gas cost per byte allocated (computation cost).
pub(crate) block_allocate: ScalingCost,
/// Minimum gas cost for every block retained in memory (read and/or written) to ensure we can't
/// retain more than 1GiB of memory while executing a block.
///
/// This is just a _minimum_. The final per-byte charge of retaining a block is:
/// `min(block_memory_retention.scale, compute_costs)`.
pub(crate) block_memory_retention_minimum: ScalingCost,
/// Gas cost for opening a block.
pub(crate) block_open: ScalingCost,
/// Gas cost for persisting a block over time.
pub(crate) block_persist_storage: ScalingCost,
/// Gas cost to cover the cost of flushing a block.
pub(crate) block_persist_compute: Gas,
/// Rules for execution gas.
pub(crate) wasm_rules: WasmGasPrices,
/// Gas cost to validate an ActorEvent as soon as it's received from the actor, and prior
/// to it being parsed.
pub(crate) event_per_entry: ScalingCost,
/// Gas cost of doing lookups in the builtin actor mappings.
pub(crate) builtin_actor_manifest_lookup: Gas,
/// Gas cost of utf8 parsing.
pub(crate) utf8_validation: ScalingCost,
/// Gas cost of accessing the network context.
pub(crate) network_context: Gas,
/// Gas cost of accessing the message context.
pub(crate) message_context: Gas,
/// Gas cost of compiling a Wasm module during install.
pub(crate) install_wasm_per_byte_cost: Gas,
/// Actor IDs that can be updated for free.
pub(crate) preloaded_actors: Vec<ActorID>,
/// Gas cost per field encountered when parsing CBOR.
pub(crate) ipld_cbor_scan_per_field: Gas,
/// Gas cost per CID encountered when parsing CBOR.
pub(crate) ipld_cbor_scan_per_cid: Gas,
/// Gas cost for tracking new reachable links.
pub(crate) ipld_link_tracked: Gas,
/// Gas cost for checking if CID is reachable.
pub(crate) ipld_link_checked: Gas,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct WasmGasPrices {
/// The default gas cost for instructions.
pub(crate) instruction_default: Gas,
/// The default gas cost for math instructions.
pub(crate) math_default: Gas,
/// The gas cost for unconditional jumps.
pub(crate) jump_unconditional: Gas,
/// The gas cost for conditional jumps.
pub(crate) jump_conditional: Gas,
/// The gas cost for indirect jumps.
pub(crate) jump_indirect: Gas,
/// The gas cost for calls (not including the jump cost).
pub(crate) call: Gas,
/// Gas cost for any memory fill instruction (one time charge).
pub(crate) memory_fill_base_cost: Gas,
/// Gas cost for every byte "filled" in Wasm memory.
pub(crate) memory_fill_per_byte_cost: Gas,
/// Gas cost for any memory copy instruction (one time charge).
pub(crate) memory_access_cost: Gas,
/// Gas cost for every byte copied in Wasm memory.
pub(crate) memory_copy_per_byte_cost: Gas,
/// Gas cost for a call from wasm to the system.
pub(crate) host_call_cost: Gas,
}
impl WasmGasPrices {
/// Returns the gas required for initializing memory.
pub(crate) fn init_memory_gas(&self, min_memory_bytes: usize) -> Gas {
self.memory_fill_base_cost + self.memory_fill_per_byte_cost * min_memory_bytes
}
/// Returns the gas required for growing memory.
pub(crate) fn grow_memory_gas(&self, grow_memory_bytes: usize) -> Gas {
self.memory_fill_base_cost + self.memory_fill_per_byte_cost * grow_memory_bytes
}
/// Returns the gas required for initializing tables.
pub(crate) fn init_table_gas(&self, min_table_elements: u32) -> Gas {
self.memory_fill_base_cost
+ self.memory_fill_per_byte_cost * min_table_elements * TABLE_ELEMENT_SIZE
}
}
impl PriceList {
/// Returns the gas required for storing a message of a given size in the chain, plus the cost
/// of updating the sending actor's nonce and balance in the state-tree.
#[inline]
pub fn on_chain_message(&self, msg_size: usize) -> GasCharge {
GasCharge::new(
"OnChainMessage",
self.on_chain_message_compute.apply(msg_size),
self.actor_update + self.on_chain_message_storage.apply(msg_size),
)
}
/// Returns the gas required when invoking a method.
#[inline]
pub fn on_value_transfer(&self) -> GasCharge {
GasCharge::new("OnValueTransfer", self.send_transfer_funds, Zero::zero())
}
/// Returns the gas required when invoking a method.
#[inline]
pub fn on_method_invocation(&self, _param_size: u32, param_links: usize) -> GasCharge {
let charge = self.send_invoke_method + self.ipld_link_tracked * param_links;
GasCharge::new("OnMethodInvocation", charge, Zero::zero())
}
/// Returns the gas required for returning a value from a method. At the top-level, this charges
/// for storing the block on-chain. Everywhere else, it charges for tracking IPLD links.
#[inline]
pub fn on_method_return(
&self,
call_depth: u32,
return_size: u32,
return_links: usize,
) -> GasCharge {
if call_depth == 1 {
GasCharge::new(
"OnChainReturnValue",
self.on_chain_return_compute.apply(return_size),
self.on_chain_return_storage.apply(return_size),
)
} else {
GasCharge::new(
"OnReturnValue",
self.ipld_link_tracked * return_links,
Zero::zero(),
)
}
}
/// Returns the gas required for creating an actor. Pass `true` to when explicitly assigning a
/// new address.
#[inline]
pub fn on_create_actor(&self, new_address: bool) -> GasCharge {
let mut gas = self.actor_create_storage;
if new_address {
gas += self.address_assignment + self.address_lookup;
}
GasCharge::new("OnCreateActor", Zero::zero(), gas)
}
/// Returns the gas required for deleting an actor.
#[inline]
pub fn on_delete_actor(&self) -> GasCharge {
GasCharge::new("OnDeleteActor", Zero::zero(), Zero::zero())
}
/// Returns gas required for signature verification.
#[cfg(feature = "verify-signature")]
#[inline]
pub fn on_verify_signature(&self, sig_type: SignatureType, data_len: usize) -> GasCharge {
let cost = self.sig_cost[&sig_type];
let gas = cost.apply(data_len);
GasCharge::new("OnVerifySignature", gas, Zero::zero())
}
/// Returns gas required for BLS aggregate signature verification.
#[inline]
pub fn on_verify_aggregate_signature(&self, num_sigs: usize, data_len: usize) -> GasCharge {
// When `num_sigs` BLS signatures are aggregated into a single signature, the aggregate
// signature verifier must perform `num_sigs + 1` expensive pairing operations (one
// pairing on the aggregate signature, and one pairing for each signed plaintext's digest).
//
// Note that `bls_signatures` rearranges the textbook verifier equation (containing
// `num_sigs + 1` full pairings) into a more efficient equation containing `num_sigs + 1`
// Miller loops and one final exponentiation.
let num_pairings = num_sigs as u64 + 1;
let gas_pairings = self.bls_pairing_cost * num_pairings;
let gas_hashing = self.bls_hashing_cost.apply(data_len);
GasCharge::new(
"OnVerifyBlsAggregateSignature",
gas_pairings + gas_hashing,
Zero::zero(),
)
}
/// Returns gas required for recovering signer pubkey from signature
#[inline]
pub fn on_recover_secp_public_key(&self) -> GasCharge {
GasCharge::new(
"OnRecoverSecpPublicKey",
self.secp256k1_recover_cost,
Zero::zero(),
)
}
/// Returns gas required for hashing data.
#[inline]
pub fn on_hashing(&self, hasher: SupportedHashes, data_len: usize) -> GasCharge {
let cost = self.hashing_cost[&hasher];
let gas = cost.apply(data_len);
GasCharge::new("OnHashing", gas, Zero::zero())
}
#[inline]
pub fn on_utf8_validation(&self, len: usize) -> GasCharge {
GasCharge::new(
"OnUtf8Validation",
self.utf8_validation.apply(len),
Zero::zero(),
)
}
/// Returns gas required for computing unsealed sector Cid.
#[inline]
pub fn on_compute_unsealed_sector_cid(
&self,
_proof: RegisteredSealProof,
_pieces: &[PieceInfo],
) -> GasCharge {
GasCharge::new(
"OnComputeUnsealedSectorCid",
self.compute_unsealed_sector_cid_base,
Zero::zero(),
)
}
/// Returns gas required for seal verification.
#[inline]
pub fn on_verify_seal(&self, _info: &SealVerifyInfo) -> GasCharge {
GasCharge::new("OnVerifySeal", self.verify_seal_base, Zero::zero())
}
#[inline]
pub fn on_verify_aggregate_seals(
&self,
aggregate: &AggregateSealVerifyProofAndInfos,
) -> GasCharge {
let proof_type = aggregate.seal_proof;
let per_proof = *self
.verify_aggregate_seal_per
.get(&proof_type)
.unwrap_or_else(|| {
self.verify_aggregate_seal_per
.get(&RegisteredSealProof::StackedDRG32GiBV1P1)
.expect(
"There is an implementation error where proof type does not exist in table",
)
});
let step = self
.verify_aggregate_seal_steps
.get(&proof_type)
.unwrap_or_else(|| {
self.verify_aggregate_seal_steps
.get(&RegisteredSealProof::StackedDRG32GiBV1P1)
.expect(
"There is an implementation error where proof type does not exist in table",
)
});
// Should be safe because there is a limit to how much seals get aggregated
let num = aggregate.infos.len() as u64;
GasCharge::new(
"OnVerifyAggregateSeals",
per_proof * num + step.lookup(num),
Zero::zero(),
)
}
/// Returns gas required for replica verification.
#[inline]
pub fn on_verify_replica_update(&self, _replica: &ReplicaUpdateInfo) -> GasCharge {
GasCharge::new(
"OnVerifyReplicaUpdate",
self.verify_replica_update,
Zero::zero(),
)
}
/// Returns gas required for PoSt verification.
#[inline]
pub fn on_verify_post(&self, info: &WindowPoStVerifyInfo) -> GasCharge {
let p_proof = info
.proofs
.first()
.map(|p| p.post_proof)
.unwrap_or(RegisteredPoStProof::StackedDRGWindow512MiBV1P1);
let cost = self.verify_post_lookup.get(&p_proof).unwrap_or_else(|| {
self.verify_post_lookup
.get(&RegisteredPoStProof::StackedDRGWindow512MiBV1P1)
.expect("512MiB lookup must exist in price table")
});
let gas_used = cost.apply(info.challenged_sectors.len());
GasCharge::new("OnVerifyPost", gas_used, Zero::zero())
}
/// Returns gas required for verifying consensus fault.
#[inline]
pub fn on_verify_consensus_fault(
&self,
_h1_len: usize,
_h2_len: usize,
_extra_len: usize,
) -> GasCharge {
GasCharge::new(
"OnVerifyConsensusFault",
Zero::zero(),
self.verify_consensus_fault,
)
}
/// Returns the cost of the gas required for getting randomness from the client with the given lookback.
#[inline]
pub fn on_get_randomness(&self, lookback: ChainEpoch) -> GasCharge {
GasCharge::new(
"OnGetRandomness",
Zero::zero(),
self.lookback_cost.apply(lookback as u64),
)
}
/// Returns the base gas required for loading an object, independent of the object's size.
#[inline]
pub fn on_block_open_base(&self) -> GasCharge {
GasCharge::new(
"OnBlockOpenBase",
self.ipld_link_checked,
self.block_open.flat,
)
}
/// Returns the gas required for loading an object based on the size of the object.
#[inline]
pub fn on_block_open(&self, data_size: usize, links: usize) -> GasCharge {
// These are the actual compute costs involved.
let compute = self.ipld_link_tracked * links;
let block_open = self.block_open.scale * data_size
+ self.block_allocate.apply(data_size)
+ self.block_memcpy.apply(data_size);
// But we need to make sure we charge at least the memory retention cost.
let retention_min = self.block_memory_retention_minimum.apply(data_size);
let retention_surcharge = (retention_min - (compute + block_open)).max(Gas::zero());
GasCharge::new(
"OnBlockOpen",
compute,
// We charge the `block_open` fee as "extra" to make sure the FVM benchmarks still work.
block_open + retention_surcharge,
)
}
/// Returns the gas required for reading a loaded object.
#[inline]
pub fn on_block_read(&self, data_size: usize) -> GasCharge {
GasCharge::new(
"OnBlockRead",
self.block_memcpy.apply(data_size),
Zero::zero(),
)
}
/// Returns the gas required for adding an object to the FVM cache.
#[inline]
pub fn on_block_create(&self, data_size: usize, links: usize) -> GasCharge {
// These are the actual compute costs involved.
let compute = self.block_memcpy.apply(data_size)
+ self.block_allocate.apply(data_size)
+ self.ipld_link_checked * links;
// But we need to make sure we charge at least the memory retention cost.
let retention_min = self.block_memory_retention_minimum.apply(data_size);
let retention_surcharge = (retention_min - compute).max(Gas::zero());
GasCharge::new("OnBlockCreate", compute, retention_surcharge)
}
/// Returns the gas required for committing an object to the state blockstore.
#[inline]
pub fn on_block_link(&self, hash_code: SupportedHashes, data_size: usize) -> GasCharge {
// The initial compute costs include a single memcpy + alloc and the cost of actually
// hashing the block to compute the CID.
let memcpy = self.block_memcpy.apply(data_size);
let alloc = self.block_allocate.apply(data_size);
let hashing = self.hashing_cost[&hash_code].apply(data_size);
let initial_compute = memcpy + alloc + hashing + self.ipld_link_tracked;
// We also have to charge for storage...
let storage = self.block_persist_storage.apply(data_size);
// And deferred compute (the cost of flushing). Technically, there are a few memcpys and
// allocations here, but the storage cost itself is _much_ greater than all these small
// per-byte charges combined, so we ignore them for simplicity.
let deferred_compute = self.block_persist_compute;
GasCharge::new("OnBlockLink", initial_compute, deferred_compute + storage)
}
/// Returns the gas required for storing an object.
#[inline]
pub fn on_block_stat(&self) -> GasCharge {
GasCharge::new("OnBlockStat", Zero::zero(), Zero::zero())
}
/// Returns the gas required to lookup an actor in the state-tree.
#[inline]
pub fn on_actor_lookup(&self) -> GasCharge {
GasCharge::new("OnActorLookup", Zero::zero(), self.actor_lookup)
}
/// Returns the gas required to update an actor in the state-tree. Assumes that the actor lookup
/// fee has already been charged.
#[inline]
pub fn on_actor_update(&self) -> GasCharge {
GasCharge::new("OnActorUpdate", Zero::zero(), self.actor_update)
}
/// Returns the gas required to create a new actor in the state-tree. Assumes that the actor
/// lookup and update fees have already been charged.
#[inline]
pub fn on_actor_create(&self) -> GasCharge {
GasCharge::new("OnActorCreate", Zero::zero(), self.actor_create_storage)
}
/// Returns the gas required for accessing the balance of the current actor.
#[inline]
pub fn on_self_balance(&self) -> GasCharge {
GasCharge::new("OnSelfBalance", Zero::zero(), Zero::zero())
}
/// Returns the gas required for accessing the balance of an actor.
#[inline]
pub fn on_balance_of(&self) -> GasCharge {
GasCharge::new("OnBalanceOf", Zero::zero(), Zero::zero())
}
/// Returns the gas required for resolving an actor address.
///
/// Might require lookup in the state tree as well as loading the state of the init actor.
#[inline]
pub fn on_resolve_address(&self) -> GasCharge {
GasCharge::new("OnResolveAddress", Zero::zero(), Zero::zero())
}
/// Returns the gas required for looking up an actor's delegated address.
#[inline]
pub fn on_lookup_delegated_address(&self) -> GasCharge {
GasCharge::new("OnLookupAddress", Zero::zero(), Zero::zero())
}
/// Returns the gas required for getting the CID of the code of an actor.
///
/// Might require looking up the actor in the state tree.
#[inline]
pub fn on_get_actor_code_cid(&self) -> GasCharge {
GasCharge::new("OnGetActorCodeCid", Zero::zero(), Zero::zero())
}
/// Returns the gas required for looking up the type of a builtin actor by CID.
#[inline]
pub fn on_get_builtin_actor_type(&self) -> GasCharge {
GasCharge::new(
"OnGetBuiltinActorType",
self.builtin_actor_manifest_lookup,
Zero::zero(),
)
}
/// Returns the gas required for looking up the CID of a builtin actor by type.
#[inline]
pub fn on_get_code_cid_for_type(&self) -> GasCharge {
GasCharge::new(
"OnGetCodeCidForType",
self.builtin_actor_manifest_lookup,
Zero::zero(),
)
}
/// Returns the gas required for looking up a tipset CID with the given lookback.
#[inline]
pub fn on_tipset_cid(&self, lookback: ChainEpoch) -> GasCharge {
GasCharge::new(
"OnTipsetCid",
Zero::zero(),
self.lookback_cost.apply(lookback as u64),
)
}
/// Returns the gas required for accessing the network context.
#[inline]
pub fn on_network_context(&self) -> GasCharge {
GasCharge::new("OnNetworkContext", self.network_context, Zero::zero())
}
/// Returns the gas required for accessing the message context.
#[inline]
pub fn on_message_context(&self) -> GasCharge {
GasCharge::new("OnMessageContext", self.message_context, Zero::zero())
}
/// Returns the gas required for installing an actor.
pub fn on_install_actor(&self, wasm_size: usize) -> GasCharge {
GasCharge::new(
"OnInstallActor",
self.install_wasm_per_byte_cost * wasm_size,
Zero::zero(),
)
}
#[inline]
pub fn on_actor_event(&self, entries: usize, keysize: usize, valuesize: usize) -> GasCharge {
// Here we estimate per-event overhead given the constraints on event values.
let validate_entries = self.event_per_entry.apply(entries);
let validate_utf8 = self.utf8_validation.apply(keysize);
// Estimate the size, saturating at max-u64. Given how we calculate gas, this will saturate
// the gas maximum at max-u64 milligas.
let estimated_size = EVENT_OVERHEAD
.saturating_add(EVENT_ENTRY_OVERHEAD.saturating_mul(entries as u64))
.saturating_add(keysize as u64)
.saturating_add(valuesize as u64);
// Calculate the cost per copy (one memcpy + one allocation).
let mem =
self.block_memcpy.apply(estimated_size) + self.block_allocate.apply(estimated_size);
// Charge for the hashing on AMT insertion.
let hash = self.hashing_cost[&SupportedHashes::Blake2b256].apply(estimated_size);
GasCharge::new(
"OnActorEvent",
// Charge for validation/storing/serializing events.
mem * 2u32 + validate_entries + validate_utf8,
// Charge for forming the AMT and returning the events to the client.
// one copy into the AMT, one copy to the client.
hash + mem,
)
}
#[inline]
pub fn on_get_root(&self) -> GasCharge {
GasCharge::new("OnActorGetRoot", self.ipld_link_tracked, Gas::zero())
}
#[inline]
pub fn on_set_root(&self) -> GasCharge {
GasCharge::new("OnActorSetRoot", self.ipld_link_checked, Gas::zero())
}
}