-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathlib.rs
430 lines (379 loc) · 14.8 KB
/
lib.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
use fil_actors_evm_shared::address::EthAddress;
use fil_actors_runtime::{
actor_dispatch_unrestricted, actor_error, ActorError, AsActorError, WithCodec, EAM_ACTOR_ADDR,
INIT_ACTOR_ADDR,
};
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::ipld_block::IpldBlock;
use fvm_ipld_encoding::{BytesSer, DAG_CBOR};
use fvm_shared::address::Address;
use fvm_shared::econ::TokenAmount;
use fvm_shared::error::ExitCode;
use crate::interpreter::Outcome;
use crate::interpreter::{execute, Bytecode, ExecutionState, System};
use crate::reader::ValueReader;
use cid::Cid;
use fil_actors_runtime::runtime::{ActorCode, Runtime};
use fvm_shared::METHOD_CONSTRUCTOR;
use num_derive::FromPrimitive;
pub use types::*;
#[doc(hidden)]
pub mod ext;
pub mod interpreter;
pub(crate) mod reader;
mod state;
mod types;
pub use state::*;
#[cfg(feature = "fil-actor")]
fil_actors_runtime::wasm_trampoline!(EvmContractActor);
pub const EVM_CONTRACT_REVERTED: ExitCode = ExitCode::new(33);
pub const EVM_CONTRACT_INVALID_INSTRUCTION: ExitCode = ExitCode::new(34);
pub const EVM_CONTRACT_UNDEFINED_INSTRUCTION: ExitCode = ExitCode::new(35);
pub const EVM_CONTRACT_STACK_UNDERFLOW: ExitCode = ExitCode::new(36);
pub const EVM_CONTRACT_STACK_OVERFLOW: ExitCode = ExitCode::new(37);
pub const EVM_CONTRACT_ILLEGAL_MEMORY_ACCESS: ExitCode = ExitCode::new(38);
pub const EVM_CONTRACT_BAD_JUMPDEST: ExitCode = ExitCode::new(39);
pub const EVM_CONTRACT_SELFDESTRUCT_FAILED: ExitCode = ExitCode::new(40);
const EVM_MAX_RESERVED_METHOD: u64 = 1023;
pub const NATIVE_METHOD_SIGNATURE: &str = "handle_filecoin_method(uint64,uint64,bytes)";
pub const NATIVE_METHOD_SELECTOR: [u8; 4] = [0x86, 0x8e, 0x10, 0xc4];
const EVM_WORD_SIZE: usize = 32;
#[test]
fn test_method_selector() {
// We could just _generate_ this method selector with a proc macro, but this is easier.
use cid::multihash::MultihashDigest;
let hash = cid::multihash::Code::Keccak256.digest(NATIVE_METHOD_SIGNATURE.as_bytes());
let computed_selector = &hash.digest()[..4];
assert_eq!(computed_selector, NATIVE_METHOD_SELECTOR);
}
#[derive(FromPrimitive)]
#[repr(u64)]
pub enum Method {
Constructor = METHOD_CONSTRUCTOR,
Resurrect = 2,
GetBytecode = 3,
GetBytecodeHash = 4,
GetStorageAt = 5,
InvokeContractDelegate = 6,
InvokeContract = frc42_dispatch::method_hash!("InvokeEVM"),
}
pub struct EvmContractActor;
/// Returns a tombstone for the currently executing message.
pub(crate) fn current_tombstone(rt: &impl Runtime) -> Tombstone {
Tombstone { origin: rt.message().origin().id().unwrap(), nonce: rt.message().nonce() }
}
/// Returns true if the contract is "dead". A contract is dead if:
///
/// 1. It has a tombstone.
/// 2. It's tombstone is not from the current message execution (the nonce/origin don't match the
/// currently executing message).
///
/// Specifically, this lets us mark the contract as "self-destructed" but keep it alive until the
/// current top-level message finishes executing.
pub(crate) fn is_dead(rt: &impl Runtime, state: &State) -> bool {
state.tombstone.map_or(false, |t| t != current_tombstone(rt))
}
fn load_bytecode(bs: &impl Blockstore, cid: &Cid) -> Result<Option<Bytecode>, ActorError> {
let bytecode = bs
.get(cid)
.context_code(ExitCode::USR_NOT_FOUND, "failed to read bytecode")?
.expect("bytecode not in state tree");
if bytecode.is_empty() {
Ok(None)
} else {
Ok(Some(Bytecode::new(bytecode)))
}
}
fn initialize_evm_contract(
system: &mut System<impl Runtime>,
caller: EthAddress,
initcode: Vec<u8>,
) -> Result<(), ActorError> {
// Lookup our Ethereum address.
let receiver_fil_addr = system.rt.message().receiver();
let receiver_eth_addr = system.resolve_ethereum_address(&receiver_fil_addr).context_code(
ExitCode::USR_ASSERTION_FAILED,
"failed to resolve the contracts ETH address",
)?;
// Make sure we have an actual Ethereum address (assigned by the EAM). This is how we make sure
// an EVM actor may only be constructed by the EAM.
if receiver_eth_addr.as_id().is_some() {
return Err(ActorError::forbidden(format!(
"contract {} doesn't have an eth address",
receiver_fil_addr,
)));
}
// If we have no code, save the state and return.
if initcode.is_empty() {
return system.flush();
}
// create a new execution context
let value_received = system.rt.message().value_received();
let mut exec_state = ExecutionState::new(caller, receiver_eth_addr, value_received, Vec::new());
// identify bytecode valid jump destinations
let initcode = Bytecode::new(initcode);
// invoke the contract constructor
let output = execute(&initcode, &mut exec_state, system)?;
match output.outcome {
Outcome::Return => {
system.set_bytecode(&output.return_data)?;
system.flush()
}
Outcome::Revert => Err(ActorError::unchecked_with_data(
EVM_CONTRACT_REVERTED,
"constructor reverted".to_string(),
IpldBlock::serialize_cbor(&BytesSer(&output.return_data)).unwrap(),
)),
}
}
fn invoke_contract_inner<RT>(
system: &mut System<RT>,
input_data: Vec<u8>,
bytecode_cid: &Cid,
caller: &EthAddress,
value_received: TokenAmount,
) -> Result<Vec<u8>, ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
let bytecode = match load_bytecode(system.rt.store(), bytecode_cid)? {
Some(bytecode) => bytecode,
// an EVM contract with no code returns immediately
None => return Ok(Vec::new()),
};
// Resolve the receiver's ethereum address.
let receiver_fil_addr = system.rt.message().receiver();
let receiver_eth_addr = system.resolve_ethereum_address(&receiver_fil_addr).unwrap();
let mut exec_state =
ExecutionState::new(*caller, receiver_eth_addr, value_received, input_data);
let output = execute(&bytecode, &mut exec_state, system)?;
match output.outcome {
Outcome::Return => {
system.flush()?;
Ok(output.return_data.to_vec())
}
Outcome::Revert => Err(ActorError::unchecked_with_data(
EVM_CONTRACT_REVERTED,
"contract reverted".to_string(),
IpldBlock::serialize_cbor(&BytesSer(&output.return_data)).unwrap(),
)),
}
}
impl EvmContractActor {
pub fn constructor<RT>(rt: &RT, params: ConstructorParams) -> Result<(), ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
rt.validate_immediate_caller_is(&[INIT_ACTOR_ADDR])?;
initialize_evm_contract(&mut System::create(rt)?, params.creator, params.initcode.into())
}
pub fn resurrect<RT>(rt: &RT, params: ResurrectParams) -> Result<(), ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
rt.validate_immediate_caller_is(&[EAM_ACTOR_ADDR])?;
initialize_evm_contract(&mut System::resurrect(rt)?, params.creator, params.initcode.into())
}
/// Invoke the contract with some _alternative_ bytecode. This can only be called by the
/// contract itself and is used to implement the EVM's DELEGATECALL opcode.
///
/// This method expects DAG_CBOR encoded parameters (the linked `params.code` needs to be
/// reachable).
pub fn invoke_contract_delegate<RT>(
rt: &RT,
params: WithCodec<DelegateCallParams, DAG_CBOR>,
) -> Result<DelegateCallReturn, ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
let params = params.0;
rt.validate_immediate_caller_is(&[rt.message().receiver()])?;
let mut system = System::load(rt).map_err(|e| {
ActorError::unspecified(format!("failed to create execution abstraction layer: {e:?}"))
})?;
let return_data = invoke_contract_inner(
&mut system,
params.input,
¶ms.code,
¶ms.caller,
params.value,
)?;
Ok(DelegateCallReturn { return_data })
}
pub fn invoke_contract<RT>(
rt: &RT,
params: InvokeContractParams,
) -> Result<InvokeContractReturn, ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
rt.validate_immediate_caller_accept_any()?;
let mut system = System::load(rt).map_err(|e| {
ActorError::unspecified(format!("failed to create execution abstraction layer: {e:?}"))
})?;
let bytecode_cid = match system.get_bytecode() {
Some(bytecode_cid) => bytecode_cid,
// an EVM contract with no code returns immediately
None => return Ok(InvokeContractReturn { output_data: Vec::new() }),
};
let received_value = system.rt.message().value_received();
let caller = system.resolve_ethereum_address(&system.rt.message().caller()).unwrap();
let data = invoke_contract_inner(
&mut system,
params.input_data,
&bytecode_cid,
&caller,
received_value,
)?;
Ok(InvokeContractReturn { output_data: data })
}
pub fn handle_filecoin_method<RT>(
rt: &RT,
method: u64,
args: Option<IpldBlock>,
) -> Result<Option<IpldBlock>, ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
if method <= EVM_MAX_RESERVED_METHOD {
return Err(actor_error!(unhandled_message; "Invalid method"));
}
let params = args.unwrap_or(IpldBlock { codec: 0, data: vec![] });
let input = handle_filecoin_method_input(method, params.codec, params.data.as_slice());
let output = Self::invoke_contract(rt, InvokeContractParams { input_data: input })?;
handle_filecoin_method_output(&output.output_data)
}
/// Returns the contract's EVM bytecode, or `None` if the contract has been deleted (has called
/// SELFDESTRUCT).
///
/// Return value is "dag cbor" as we need the linked bytecode (if present) to be reachable.
pub fn bytecode(rt: &impl Runtime) -> Result<WithCodec<BytecodeReturn, DAG_CBOR>, ActorError> {
// Any caller can fetch the bytecode of a contract; this is now EXT* opcodes work.
rt.validate_immediate_caller_accept_any()?;
let state: State = rt.state()?;
if is_dead(rt, &state) {
Ok(BytecodeReturn { code: None }.into())
} else {
Ok(BytecodeReturn { code: Some(state.bytecode) }.into())
}
}
pub fn bytecode_hash(rt: &impl Runtime) -> Result<BytecodeHash, ActorError> {
// Any caller can fetch the bytecode hash of a contract; this is where EXTCODEHASH gets it's value for EVM contracts.
rt.validate_immediate_caller_accept_any()?;
// return value must be either keccak("") or keccak(bytecode)
let state: State = rt.state()?;
if is_dead(rt, &state) {
Ok(BytecodeHash::EMPTY)
} else {
Ok(state.bytecode_hash)
}
}
pub fn storage_at<RT>(
rt: &RT,
params: GetStorageAtParams,
) -> Result<GetStorageAtReturn, ActorError>
where
RT: Runtime,
RT::Blockstore: Clone,
{
// This method cannot be called on-chain; other on-chain logic should not be able to
// access arbitrary storage keys from a contract.
rt.validate_immediate_caller_is([&Address::new_id(0)])?;
// If the contract is dead, this will always return "0".
let val = System::load(rt)?
.get_storage(params.storage_key)
.context_code(ExitCode::USR_ASSERTION_FAILED, "failed to get storage key")?;
Ok(GetStorageAtReturn { storage: val })
}
}
/// Format "filecoin_native_method" input parameters.
fn handle_filecoin_method_input(method: u64, codec: u64, params: &[u8]) -> Vec<u8> {
let static_args =
[method, codec, EVM_WORD_SIZE as u64 * 3 /* start of params */, params.len() as u64];
let total_words =
static_args.len() + (params.len() / EVM_WORD_SIZE) + (params.len() % 32 > 0) as usize;
let len = 4 + total_words * EVM_WORD_SIZE;
let mut buf = Vec::with_capacity(len);
buf.extend_from_slice(&NATIVE_METHOD_SELECTOR);
for n in static_args {
// Left-pad to 32 bytes, then be-encode the value.
let encoded = n.to_be_bytes();
buf.resize(buf.len() + (EVM_WORD_SIZE - encoded.len()), 0);
buf.extend_from_slice(&encoded);
}
// Extend with the params, then right-pad with zeros.
buf.extend_from_slice(params);
buf.resize(len, 0);
buf
}
/// Decode the response from "filecoin_native_method". We expect:
///
/// 1. The exit code (u32).
/// 2. The codec (u64).
/// 3. The data (bytes).
///
/// According to the solidity ABI.
fn handle_filecoin_method_output(output: &[u8]) -> Result<Option<IpldBlock>, ActorError> {
// Short-circuit if empty.
if output.is_empty() {
return Ok(None);
}
let mut output = ValueReader::new(output);
let exit_code: ExitCode =
output.read_value().context_code(ExitCode::USR_SERIALIZATION, "exit code not a u32")?;
let codec: u64 = output
.read_value()
.context_code(ExitCode::USR_SERIALIZATION, "returned codec not a u64")?;
let len_offset: u32 = output
.read_value()
.context_code(ExitCode::USR_SERIALIZATION, "invalid return value offset")?;
output.seek(len_offset as usize);
let length: u32 = output
.read_value()
.context_code(ExitCode::USR_SERIALIZATION, "return length is too large")?;
let return_data = output.read_padded(length as usize);
let return_block = match codec {
// Empty return values.
0 if length == 0 => None,
0 => {
return Err(ActorError::serialization(format!(
"codec 0 is only valid for empty returns, got a return value of length {length}"
)));
}
// Supported codecs.
fvm_ipld_encoding::CBOR => Some(IpldBlock { codec, data: return_data.into() }),
// Everything else.
_ => return Err(ActorError::serialization(format!("unsupported codec: {codec}"))),
};
if exit_code.is_success() {
Ok(return_block)
} else {
Err(ActorError::unchecked_with_data(
exit_code,
"EVM contract explicitly exited with a non-zero exit code".to_string(),
return_block,
))
}
}
impl ActorCode for EvmContractActor {
type Methods = Method;
fn name() -> &'static str {
"EVMContract"
}
actor_dispatch_unrestricted! {
Constructor => constructor,
InvokeContract => invoke_contract [default_params],
GetBytecode => bytecode,
GetBytecodeHash => bytecode_hash,
GetStorageAt => storage_at,
InvokeContractDelegate => invoke_contract_delegate,
Resurrect => resurrect,
_ => handle_filecoin_method,
}
}