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
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Tetsy Vapory.

// Tetsy Vapory is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Tetsy Vapory is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.

//! Wasm Interpreter

extern crate byteorder;
extern crate vapory_types;
#[macro_use] extern crate log;
extern crate libc;
extern crate tetsy_wasm;
extern crate tetsy_vm;
extern crate twasm_utils as wasm_utils;
extern crate twasmi;

#[cfg(test)]
extern crate env_logger;

mod env;
mod panic_payload;
mod parser;
mod runtime;

#[cfg(test)]
mod tests;


use tetsy_vm::{GasLeft, ReturnData, ActionParams};
use twasmi::{Error as InterpreterError, Trap};

use runtime::{Runtime, RuntimeContext};

use vapory_types::U256;

/// Wrapped interpreter error
#[derive(Debug)]
pub enum Error {
	Interpreter(InterpreterError),
	Trap(Trap),
}

impl From<InterpreterError> for Error {
	fn from(e: InterpreterError) -> Self {
		Error::Interpreter(e)
	}
}

impl From<Trap> for Error {
	fn from(e: Trap) -> Self {
		Error::Trap(e)
	}
}

impl From<Error> for tetsy_vm::Error {
	fn from(e: Error) -> Self {
		match e {
			Error::Interpreter(e) => tetsy_vm::Error::Wasm(format!("Wasm runtime error: {:?}", e)),
			Error::Trap(e) => tetsy_vm::Error::Wasm(format!("Wasm contract trap: {:?}", e)),
		}
	}
}

/// Wasm interpreter instance
pub struct WasmInterpreter {
	params: ActionParams,
}

impl WasmInterpreter {
	pub fn new(params: ActionParams) -> Self {
		WasmInterpreter { params }
	}
}

impl From<runtime::Error> for tetsy_vm::Error {
	fn from(e: runtime::Error) -> Self {
		tetsy_vm::Error::Wasm(format!("Wasm runtime error: {:?}", e))
	}
}

enum ExecutionOutcome {
	Suicide,
	Return,
	NotSpecial,
}

impl WasmInterpreter {
	pub fn run(self: Box<WasmInterpreter>, ext: &mut dyn tetsy_vm::Ext) -> tetsy_vm::Result<GasLeft> {
		let (module, data) = parser::payload(&self.params, ext.schedule().wasm())?;

		let loaded_module = twasmi::Module::from_tetsy_wasm_module(module).map_err(Error::Interpreter)?;

		let instantiation_resolver = env::ImportResolver::with_limit(16, ext.schedule().wasm());

		let module_instance = twasmi::ModuleInstance::new(
			&loaded_module,
			&twasmi::ImportsBuilder::new().with_resolver("env", &instantiation_resolver)
		).map_err(Error::Interpreter)?;

		let adjusted_gas = self.params.gas * U256::from(ext.schedule().wasm().opcodes_div) /
			U256::from(ext.schedule().wasm().opcodes_mul);

		if adjusted_gas > ::std::u64::MAX.into()
		{
			return Err(tetsy_vm::Error::Wasm("Wasm interpreter cannot run contracts with gas (wasm adjusted) >= 2^64".to_owned()));
		}

		let initial_memory = instantiation_resolver.memory_size().map_err(Error::Interpreter)?;
		trace!(target: "wasm", "Contract requested {:?} pages of initial memory", initial_memory);

		let (gas_left, result) = {
			let mut runtime = Runtime::with_params(
				ext,
				instantiation_resolver.memory_ref(),
				// cannot overflow, checked above
				adjusted_gas.low_u64(),
				data.to_vec(),
				RuntimeContext {
					address: self.params.address,
					sender: self.params.sender,
					origin: self.params.origin,
					code_address: self.params.code_address,
					code_version: self.params.code_version,
					value: self.params.value.value(),
				},
			);

			// cannot overflow if static_region < 2^16,
			// initial_memory ∈ [0..2^32)
			// total_charge <- static_region * 2^32 * 2^16
			// total_charge ∈ [0..2^64) if static_region ∈ [0..2^16)
			// qed
			assert!(runtime.schedule().wasm().initial_mem < 1 << 16);
			runtime.charge(|s| initial_memory as u64 * s.wasm().initial_mem as u64)?;

			let module_instance = module_instance.run_start(&mut runtime).map_err(Error::Trap)?;

			let invoke_result = module_instance.invoke_export("call", &[], &mut runtime);

			let mut execution_outcome = ExecutionOutcome::NotSpecial;
			if let Err(InterpreterError::Trap(ref trap)) = invoke_result {
				if let twasmi::TrapKind::Host(ref boxed) = *trap.kind() {
					let ref runtime_err = boxed.downcast_ref::<runtime::Error>()
						.expect("Host errors other than runtime::Error never produced; qed");

					match **runtime_err {
						runtime::Error::Suicide => { execution_outcome = ExecutionOutcome::Suicide; },
						runtime::Error::Return => { execution_outcome = ExecutionOutcome::Return; },
						_ => {}
					}
				}
			}

			if let (ExecutionOutcome::NotSpecial, Err(e)) = (execution_outcome, invoke_result) {
				trace!(target: "wasm", "Error executing contract: {:?}", e);
				return Err(tetsy_vm::Error::from(Error::from(e)));
			}

			(
				runtime.gas_left().expect("Cannot fail since it was not updated since last charge"),
				runtime.into_result(),
			)
		};

		let gas_left =
			U256::from(gas_left) * U256::from(ext.schedule().wasm().opcodes_mul)
				/ U256::from(ext.schedule().wasm().opcodes_div);

		if result.is_empty() {
			trace!(target: "wasm", "Contract execution result is empty.");
			Ok(GasLeft::Known(gas_left))
		} else {
			let len = result.len();
			Ok(GasLeft::NeedsReturn {
				gas_left: gas_left,
				data: ReturnData::new(
					result,
					0,
					len,
				),
				apply_state: true,
			})
		}
	}
}

impl tetsy_vm::Exec for WasmInterpreter {
	fn exec(self: Box<WasmInterpreter>, ext: &mut dyn tetsy_vm::Ext) -> tetsy_vm::ExecTrapResult<GasLeft> {
		Ok(self.run(ext))
	}
}