actors_runtime/runtime/mod.rs
1// Copyright 2019-2022 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use cid::Cid;
5use fvm_shared::actor::builtin::Type;
6use fvm_shared::address::Address;
7use fvm_shared::blockstore::Blockstore;
8use fvm_shared::clock::ChainEpoch;
9use fvm_shared::consensus::ConsensusFault;
10use fvm_shared::crypto::randomness::DomainSeparationTag;
11use fvm_shared::crypto::signature::Signature;
12use fvm_shared::econ::TokenAmount;
13use fvm_shared::encoding::{de, Cbor, RawBytes};
14use fvm_shared::error::ExitCode;
15use fvm_shared::piece::PieceInfo;
16use fvm_shared::randomness::Randomness;
17use fvm_shared::sector::{
18 AggregateSealVerifyProofAndInfos, RegisteredSealProof, SealVerifyInfo, WindowPoStVerifyInfo,
19};
20use fvm_shared::version::NetworkVersion;
21use fvm_shared::{ActorID, MethodNum};
22
23pub use self::actor_code::*;
24use crate::ActorError;
25
26mod actor_code;
27
28#[cfg(target_arch = "wasm32")]
29pub mod fvm;
30
31#[cfg(target_arch = "wasm32")]
32mod actor_blockstore;
33
34/// Runtime is the VM's internal runtime object.
35/// this is everything that is accessible to actors, beyond parameters.
36pub trait Runtime<BS: Blockstore>: Syscalls {
37 /// The network protocol version number at the current epoch.
38 fn network_version(&self) -> NetworkVersion;
39
40 /// Information related to the current message being executed.
41 fn message(&self) -> &dyn MessageInfo;
42
43 /// The current chain epoch number. The genesis block has epoch zero.
44 fn curr_epoch(&self) -> ChainEpoch;
45
46 /// Validates the caller against some predicate.
47 /// Exported actor methods must invoke at least one caller validation before returning.
48 fn validate_immediate_caller_accept_any(&mut self) -> Result<(), ActorError>;
49 fn validate_immediate_caller_is<'a, I>(&mut self, addresses: I) -> Result<(), ActorError>
50 where
51 I: IntoIterator<Item = &'a Address>;
52 fn validate_immediate_caller_type<'a, I>(&mut self, types: I) -> Result<(), ActorError>
53 where
54 I: IntoIterator<Item = &'a Type>;
55
56 /// The balance of the receiver.
57 fn current_balance(&self) -> TokenAmount;
58
59 /// Resolves an address of any protocol to an ID address (via the Init actor's table).
60 /// This allows resolution of externally-provided SECP, BLS, or actor addresses to the canonical form.
61 /// If the argument is an ID address it is returned directly.
62 fn resolve_address(&self, address: &Address) -> Option<Address>;
63
64 /// Look up the code ID at an actor address.
65 fn get_actor_code_cid(&self, addr: &Address) -> Option<Cid>;
66
67 /// Randomness returns a (pseudo)random byte array drawing from the latest
68 /// ticket chain from a given epoch and incorporating requisite entropy.
69 /// This randomness is fork dependant but also biasable because of this.
70 fn get_randomness_from_tickets(
71 &self,
72 personalization: DomainSeparationTag,
73 rand_epoch: ChainEpoch,
74 entropy: &[u8],
75 ) -> Result<Randomness, ActorError>;
76
77 /// Randomness returns a (pseudo)random byte array drawing from the latest
78 /// beacon from a given epoch and incorporating requisite entropy.
79 /// This randomness is not tied to any fork of the chain, and is unbiasable.
80 fn get_randomness_from_beacon(
81 &self,
82 personalization: DomainSeparationTag,
83 rand_epoch: ChainEpoch,
84 entropy: &[u8],
85 ) -> Result<Randomness, ActorError>;
86
87 /// Initializes the state object.
88 /// This is only valid in a constructor function and when the state has not yet been initialized.
89 fn create<C: Cbor>(&mut self, obj: &C) -> Result<(), ActorError>;
90
91 /// Loads a readonly copy of the state of the receiver into the argument.
92 ///
93 /// Any modification to the state is illegal and will result in an abort.
94 fn state<C: Cbor>(&self) -> Result<C, ActorError>;
95
96 /// Loads a mutable version of the state into the `obj` argument and protects
97 /// the execution from side effects (including message send).
98 ///
99 /// The second argument is a function which allows the caller to mutate the state.
100 /// The return value from that function will be returned from the call to Transaction().
101 ///
102 /// If the state is modified after this function returns, execution will abort.
103 ///
104 /// The gas cost of this method is that of a Store.Put of the mutated state object.
105 fn transaction<C, RT, F>(&mut self, f: F) -> Result<RT, ActorError>
106 where
107 C: Cbor,
108 F: FnOnce(&mut C, &mut Self) -> Result<RT, ActorError>;
109
110 /// Returns reference to blockstore
111 fn store(&self) -> &BS;
112
113 /// Sends a message to another actor, returning the exit code and return value envelope.
114 /// If the invoked method does not return successfully, its state changes
115 /// (and that of any messages it sent in turn) will be rolled back.
116 fn send(
117 &self,
118 to: Address,
119 method: MethodNum,
120 params: RawBytes,
121 value: TokenAmount,
122 ) -> Result<RawBytes, ActorError>;
123
124 /// Computes an address for a new actor. The returned address is intended to uniquely refer to
125 /// the actor even in the event of a chain re-org (whereas an ID-address might refer to a
126 /// different actor after messages are re-ordered).
127 /// Always an ActorExec address.
128 fn new_actor_address(&mut self) -> Result<Address, ActorError>;
129
130 /// Creates an actor with code `codeID` and address `address`, with empty state.
131 /// May only be called by Init actor.
132 fn create_actor(&mut self, code_id: Cid, address: ActorID) -> Result<(), ActorError>;
133
134 /// Deletes the executing actor from the state tree, transferring any balance to beneficiary.
135 /// Aborts if the beneficiary does not exist.
136 /// May only be called by the actor itself.
137 fn delete_actor(&mut self, beneficiary: &Address) -> Result<(), ActorError>;
138
139 /// Returns whether the specified CodeCID belongs to a built-in actor.
140 fn resolve_builtin_actor_type(&self, code_id: &Cid) -> Option<Type>;
141
142 /// Returns the CodeCID for a built-in actor type. The kernel will abort
143 /// if the supplied type is invalid.
144 fn get_code_cid_for_type(&self, typ: Type) -> Cid;
145
146 /// Returns the total token supply in circulation at the beginning of the current epoch.
147 /// The circulating supply is the sum of:
148 /// - rewards emitted by the reward actor,
149 /// - funds vested from lock-ups in the genesis state,
150 /// less the sum of:
151 /// - funds burnt,
152 /// - pledge collateral locked in storage miner actors (recorded in the storage power actor)
153 /// - deal collateral locked by the storage market actor
154 fn total_fil_circ_supply(&self) -> TokenAmount;
155
156 /// ChargeGas charges specified amount of `gas` for execution.
157 /// `name` provides information about gas charging point
158 fn charge_gas(&mut self, name: &'static str, compute: i64);
159
160 /// This function is a workaround for go-implementation's faulty exit code handling of
161 /// parameters before version 7
162 fn deserialize_params<O: de::DeserializeOwned>(
163 &self,
164 params: &RawBytes,
165 ) -> Result<O, ActorError> {
166 params.deserialize().map_err(|e| {
167 if self.network_version() < NetworkVersion::V7 {
168 ActorError::new(
169 ExitCode::SysErrSenderInvalid,
170 format!("failed to decode parameters: {}", e),
171 )
172 } else {
173 ActorError::from(e).wrap("failed to decode parameters")
174 }
175 })
176 }
177
178 fn base_fee(&self) -> TokenAmount;
179}
180
181/// Message information available to the actor about executing message.
182pub trait MessageInfo {
183 /// The address of the immediate calling actor. Always an ID-address.
184 fn caller(&self) -> Address;
185
186 /// The address of the actor receiving the message. Always an ID-address.
187 fn receiver(&self) -> Address;
188
189 /// The value attached to the message being processed, implicitly
190 /// added to current_balance() before method invocation.
191 fn value_received(&self) -> TokenAmount;
192}
193
194/// Pure functions implemented as primitives by the runtime.
195pub trait Syscalls {
196 /// Verifies that a signature is valid for an address and plaintext.
197 fn verify_signature(
198 &self,
199 signature: &Signature,
200 signer: &Address,
201 plaintext: &[u8],
202 ) -> Result<(), anyhow::Error>;
203
204 /// Hashes input data using blake2b with 256 bit output.
205 fn hash_blake2b(&self, data: &[u8]) -> [u8; 32];
206
207 /// Computes an unsealed sector CID (CommD) from its constituent piece CIDs (CommPs) and sizes.
208 fn compute_unsealed_sector_cid(
209 &self,
210 proof_type: RegisteredSealProof,
211 pieces: &[PieceInfo],
212 ) -> Result<Cid, anyhow::Error>;
213
214 /// Verifies a sector seal proof.
215 fn verify_seal(&self, vi: &SealVerifyInfo) -> Result<(), anyhow::Error>;
216
217 /// Verifies a window proof of spacetime.
218 fn verify_post(&self, verify_info: &WindowPoStVerifyInfo) -> Result<(), anyhow::Error>;
219
220 /// Verifies that two block headers provide proof of a consensus fault:
221 /// - both headers mined by the same actor
222 /// - headers are different
223 /// - first header is of the same or lower epoch as the second
224 /// - at least one of the headers appears in the current chain at or after epoch `earliest`
225 /// - the headers provide evidence of a fault (see the spec for the different fault types).
226 /// The parameters are all serialized block headers. The third "extra" parameter is consulted only for
227 /// the "parent grinding fault", in which case it must be the sibling of h1 (same parent tipset) and one of the
228 /// blocks in the parent of h2 (i.e. h2's grandparent).
229 /// Returns nil and an error if the headers don't prove a fault.
230 fn verify_consensus_fault(
231 &self,
232 h1: &[u8],
233 h2: &[u8],
234 extra: &[u8],
235 ) -> Result<Option<ConsensusFault>, anyhow::Error>;
236
237 fn batch_verify_seals(&self, batch: &[SealVerifyInfo]) -> anyhow::Result<Vec<bool>> {
238 Ok(batch
239 .iter()
240 .map(|si| self.verify_seal(si).is_ok())
241 .collect())
242 }
243 fn verify_aggregate_seals(
244 &self,
245 aggregate: &AggregateSealVerifyProofAndInfos,
246 ) -> Result<(), anyhow::Error>;
247}