jam_pvm_common/
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
//! Helpful code used when authoring code for running on the JAM PVM instances (service code and
//! authorizer code).

#![no_std]
#![allow(clippy::unwrap_used)]

extern crate alloc;
#[doc(hidden)]
pub use alloc::{vec, vec::Vec};
#[doc(hidden)]
pub use core::alloc::Layout;
use jam_types::*;
use scale::Output;
use simple_result_code::InvokeOutcomeCode;

#[cfg(any(feature = "authorizer", doc))]
mod authorizer;
#[cfg(any(feature = "authorizer", doc))]
pub use authorizer::Authorizer;

#[cfg(any(feature = "service", doc))]
mod service;
#[cfg(any(feature = "service", doc))]
pub use service::Service;

#[cfg(any(feature = "service", doc))]
pub mod refine;

#[cfg(any(feature = "service", doc))]
pub mod accumulate;

#[cfg(feature = "service")]
pub use accumulate as on_transfer;

pub(crate) mod imports;

// TODO: @gav NOW Move all this stuff into `logging` module.

#[cfg(any(feature = "logging", doc))]
#[macro_export]
macro_rules! error {
	(target=$target:expr,$($arg:tt)*) => {
		$crate::log_target(0, $target, &alloc::format!($($arg)*));
	};
	($($arg:tt)*) => {
		$crate::log(0, &alloc::format!($($arg)*));
	};
}

#[cfg(any(feature = "logging", doc))]
#[macro_export]
macro_rules! warn {
	(target=$target:expr,$($arg:tt)*) => {
		$crate::log_target(1, $target, &alloc::format!($($arg)*));
	};
	($($arg:tt)*) => {
		$crate::log(1, &alloc::format!($($arg)*));
	};
}

#[cfg(any(feature = "logging", doc))]
#[macro_export]
macro_rules! info {
	(target=$target:expr,$($arg:tt)*) => {
		$crate::log_target(2, $target, &alloc::format!($($arg)*));
	};
	($($arg:tt)*) => {
		$crate::log(2, &alloc::format!($($arg)*));
	};
}

#[cfg(any(feature = "logging", doc))]
#[macro_export]
macro_rules! debug {
	(target=$target:expr,$($arg:tt)*) => {
		$crate::log_target(3, $target, &alloc::format!($($arg)*));
	};
	($($arg:tt)*) => {
		$crate::log(3, &alloc::format!($($arg)*));
	};
}

#[cfg(any(feature = "logging", doc))]
#[macro_export]
macro_rules! trace {
	(target=$target:expr,$($arg:tt)*) => {
		$crate::log_target(4, $target, &alloc::format!($($arg)*));
	};
	($($arg:tt)*) => {
		$crate::log(4, &alloc::format!($($arg)*));
	};
}

#[cfg(not(any(feature = "logging", doc)))]
#[macro_export]
macro_rules! error {
	($($arg:tt)*) => {
		()
	};
}
#[cfg(not(any(feature = "logging", doc)))]
#[macro_export]
macro_rules! warn {
	($($arg:tt)*) => {
		()
	};
}
#[cfg(not(any(feature = "logging", doc)))]
#[macro_export]
macro_rules! info {
	($($arg:tt)*) => {
		()
	};
}
#[cfg(not(any(feature = "logging", doc)))]
#[macro_export]
macro_rules! debug {
	($($arg:tt)*) => {
		()
	};
}
#[cfg(not(any(feature = "logging", doc)))]
#[macro_export]
macro_rules! trace {
	($($arg:tt)*) => {
		()
	};
}

#[cfg(any(feature = "logging", doc))]
#[doc(hidden)]
pub fn log_target(level: u64, target: &str, msg: &str) {
	let t = target.as_bytes();
	let m = msg.as_bytes();
	unsafe { imports::log(level, t.as_ptr(), t.len() as u64, m.as_ptr(), m.len() as u64) }
}

#[cfg(any(feature = "logging", doc))]
#[doc(hidden)]
pub fn log(level: u64, msg: &str) {
	let m = msg.as_bytes();
	unsafe { imports::log(level, core::ptr::null(), 0u64, m.as_ptr(), m.len() as u64) }
}

#[cfg(not(any(feature = "logging", doc)))]
pub fn log_target(_: u64, _: &str, _: &str) {}

#[cfg(not(any(feature = "logging", doc)))]
pub fn log(_: u64, _: &str) {}

pub fn gas() -> Gas {
	unsafe { imports::gas() }
}

#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
#[global_allocator]
static ALLOCATOR: polkavm_derive::LeakingAllocator = polkavm_derive::LeakingAllocator;

#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
	unsafe {
		core::arch::asm!("unimp", options(noreturn));
	}
}

// TODO: @gav NOW Move all this stuff into `alloc` module.

#[doc(hidden)]
pub fn alloc(size: u32) -> u32 {
	let ptr = unsafe { alloc::alloc::alloc(Layout::from_size_align(size as usize, 4).unwrap()) };
	ptr as u32
}

#[doc(hidden)]
pub fn dealloc(ptr: u32, size: u32) {
	unsafe {
		alloc::alloc::dealloc(ptr as *mut u8, Layout::from_size_align(size as usize, 4).unwrap())
	};
}

#[doc(hidden)]
pub struct BufferOutput<'a>(&'a mut [u8], usize);
impl<'a> Output for BufferOutput<'a> {
	/// Write to the output.
	fn write(&mut self, bytes: &[u8]) {
		let (_, rest) = self.0.split_at_mut(self.1);
		let len = bytes.len().min(rest.len());
		rest[..len].copy_from_slice(&bytes[..len]);
		self.1 += len;
	}
}

#[doc(hidden)]
pub fn decode_buf<T: Decode>(ptr: u32, size: u32) -> T {
	let slice = unsafe { core::slice::from_raw_parts(ptr as *const u8, size as usize) };
	let params = T::decode(&mut &slice[..]);
	dealloc(ptr, size);
	params.unwrap()
}

#[doc(hidden)]
pub fn encode_to_buf<T: Encode>(value: T) -> (u32, u32) {
	// TODO: @gav wish avoid extra copy
	let size = value.encoded_size();
	let ptr = alloc(size as u32);
	let slice = unsafe { core::slice::from_raw_parts_mut(ptr as *mut u8, size) };
	value.encode_to(&mut BufferOutput(&mut slice[..], 0));
	(ptr, size as u32)
}

// TODO: @gav NOW Move all this stuff into `result` module.

#[derive(Debug)]
pub enum ApiError {
	/// `OOB` Invalid memory access.
	OutOfBounds,
	/// `WHO` Target service is unknown.
	IndexUnknown,
	/// `FULL` Too much storage is used by the service for its holdings.
	StorageFull,
	/// `CORE` Bad core index given.
	BadCore,
	/// `CASH` The caller has too little funding.
	NoCash,
	/// `LOW` The gas limit provided is too low (lower than the amount of gas required for the
	/// transfer).
	GasLimitTooLow,
	/// `HIGH` The gas limit provided is too high (higher than the amount of gas remaining).
	GasLimitTooHigh,
	/// `HUH` The hash is already solicited or forgotten.
	ActionInvalid,
}

impl From<u64> for ApiError {
	fn from(code: SimpleResult) -> Self {
		match code {
			c if c == SimpleResultCode::OutOfBounds as u64 => ApiError::OutOfBounds,
			c if c == SimpleResultCode::IndexUnknown as u64 => ApiError::IndexUnknown,
			c if c == SimpleResultCode::StorageFull as u64 => ApiError::StorageFull,
			c if c == SimpleResultCode::BadCore as u64 => ApiError::BadCore,
			c if c == SimpleResultCode::NoCash as u64 => ApiError::NoCash,
			c if c == SimpleResultCode::GasLimitTooLow as u64 => ApiError::GasLimitTooLow,
			c if c == SimpleResultCode::GasLimitTooHigh as u64 => ApiError::GasLimitTooHigh,
			c if c == SimpleResultCode::ActionInvalid as u64 => ApiError::ActionInvalid,
			_ => panic!("unknown error code: {}", code),
		}
	}
}

pub type ApiResult<T> = Result<T, ApiError>;

/// Simple conversion trait for types which can be converted to a regular host-call API result.
pub trait IntoApiResult<T> {
	fn into_api_result(self) -> ApiResult<T>;
}

impl IntoApiResult<()> for SimpleResult {
	fn into_api_result(self) -> ApiResult<()> {
		if self == SimpleResultCode::Ok as u64 {
			Ok(())
		} else {
			Err(self.into())
		}
	}
}
impl IntoApiResult<u64> for SimpleResult {
	fn into_api_result(self) -> ApiResult<u64> {
		if self < LOWEST_ERROR {
			Ok(self)
		} else {
			Err(self.into())
		}
	}
}
impl IntoApiResult<u32> for SimpleResult {
	fn into_api_result(self) -> ApiResult<u32> {
		if self <= u32::MAX as _ {
			Ok(self as u32)
		} else if self < LOWEST_ERROR {
			panic!("Our own API impl has resulted in success value which is out of range.");
		} else {
			Err(self.into())
		}
	}
}
impl IntoApiResult<Option<()>> for SimpleResult {
	fn into_api_result(self) -> ApiResult<Option<()>> {
		if self < LOWEST_ERROR {
			Ok(Some(()))
		} else if self == SimpleResultCode::Nothing as u64 {
			Ok(None)
		} else {
			Err(self.into())
		}
	}
}
impl IntoApiResult<Option<u64>> for SimpleResult {
	fn into_api_result(self) -> ApiResult<Option<u64>> {
		if self < LOWEST_ERROR {
			Ok(Some(self))
		} else if self == SimpleResultCode::Nothing as u64 {
			Ok(None)
		} else {
			Err(self.into())
		}
	}
}

/// The result of inner PVM invocations assuming no errors.
pub enum InvokeOutcome {
	/// `HALT` Completed normally.
	Halt,
	/// `FAULT` Completed with a page fault.
	PageFault(u64),
	/// `HOST` Completed with a host-call fault.
	HostCallFault(u64),
	/// `PANIC` Completed with a panic.
	Panic,
	/// `OOG` Completed by running out of gas.
	OutOfGas,
}

/// The result of inner PVM invocations.
pub type InvokeResult = ApiResult<InvokeOutcome>;

/// Simple trait to convert to `InvokeResult`.
pub trait IntoInvokeResult {
	/// Convert `self` to `InvokeResult`.
	fn into_invoke_result(self) -> InvokeResult;
}

impl IntoInvokeResult for [u64; 2] {
	fn into_invoke_result(self) -> InvokeResult {
		const STATUS_HALT: u64 = InvokeOutcomeCode::Halt as u64;
		const STATUS_PANIC: u64 = InvokeOutcomeCode::Panic as u64;
		const STATUS_FAULT: u64 = InvokeOutcomeCode::PageFault as u64;
		const STATUS_HOST: u64 = InvokeOutcomeCode::HostCallFault as u64;
		const STATUS_OOG: u64 = InvokeOutcomeCode::OutOfGas as u64;
		// Convert `invoke` return value to `Result`.
		match self {
			[STATUS_HALT, _] => Ok(InvokeOutcome::Halt),
			[STATUS_FAULT, address] => Ok(InvokeOutcome::PageFault(address)),
			[STATUS_HOST, index] => Ok(InvokeOutcome::HostCallFault(index)),
			[STATUS_PANIC, _] => Ok(InvokeOutcome::Panic),
			[STATUS_OOG, _] => Ok(InvokeOutcome::OutOfGas),
			[code, _] => Err(code.into()),
		}
	}
}

// TODO: @gav Remove once https://github.com/paritytech/polkavm/issues/231 is resolved.
impl IntoInvokeResult for SimpleResult {
	fn into_invoke_result(self) -> InvokeResult {
		const STATUS_HALT: u64 = InvokeOutcomeCode::Halt as u64;
		const STATUS_PANIC: u64 = InvokeOutcomeCode::Panic as u64;
		const STATUS_FAULT: u64 = InvokeOutcomeCode::PageFault as u64;
		const STATUS_HOST: u64 = InvokeOutcomeCode::HostCallFault as u64;
		const STATUS_OOG: u64 = InvokeOutcomeCode::OutOfGas as u64;
		// Convert `invoke` return value to `Result`.
		match (self % (1 << 32), self / (1 << 32)) {
			(STATUS_HALT, _) => Ok(InvokeOutcome::Halt),
			(STATUS_FAULT, address) => Ok(InvokeOutcome::PageFault(address)),
			(STATUS_HOST, index) => Ok(InvokeOutcome::HostCallFault(index)),
			(STATUS_PANIC, _) => Ok(InvokeOutcome::Panic),
			(STATUS_OOG, _) => Ok(InvokeOutcome::OutOfGas),
			(code, _) => Err(code.into()),
		}
	}
}