-
Notifications
You must be signed in to change notification settings - Fork 990
/
Copy pathnative_vp.rs
401 lines (364 loc) · 12.8 KB
/
native_vp.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
//! Native validity predicate interface associated with internal accounts such
//! as the PoS and IBC modules.
use std::cell::RefCell;
use std::collections::BTreeSet;
use borsh::BorshDeserialize;
use eyre::Context;
use thiserror::Error;
use crate::ledger::gas::VpGasMeter;
use crate::ledger::storage::write_log::WriteLog;
use crate::ledger::storage::{Storage, StorageHasher};
use crate::ledger::{storage, vp_env};
use crate::proto::Tx;
use crate::types::address::{Address, InternalAddress};
use crate::types::storage::{BlockHash, BlockHeight, Epoch, Key};
use crate::vm::prefix_iter::PrefixIterators;
use crate::vm::WasmCacheAccess;
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum Error {
#[error("Host context error: {0}")]
ContextError(vp_env::RuntimeError),
}
/// Native VP function result
pub type Result<T> = std::result::Result<T, Error>;
/// A native VP module should implement its validation logic using this trait.
pub trait NativeVp {
/// The address of this VP
const ADDR: InternalAddress;
/// Error type for the methods' results.
type Error: std::error::Error;
/// Run the validity predicate
fn validate_tx(
&self,
tx_data: &[u8],
keys_changed: &BTreeSet<Key>,
verifiers: &BTreeSet<Address>,
) -> std::result::Result<bool, Self::Error>;
}
/// A validity predicate's host context.
///
/// This is similar to [`crate::vm::host_env::VpCtx`], but without the VM
/// wrapper types and `eval_runner` field. The references must not be changed
/// when [`Ctx`] is mutable.
#[derive(Debug)]
pub struct Ctx<'a, DB, H, CA>
where
DB: storage::DB + for<'iter> storage::DBIter<'iter>,
H: StorageHasher,
CA: WasmCacheAccess,
{
/// Storage prefix iterators.
pub iterators: RefCell<PrefixIterators<'a, DB>>,
/// VP gas meter.
pub gas_meter: RefCell<VpGasMeter>,
/// Read-only access to the storage.
pub storage: &'a Storage<DB, H>,
/// Read-only access to the write log.
pub write_log: &'a WriteLog,
/// The transaction code is used for signature verification
pub tx: &'a Tx,
/// VP WASM compilation cache
#[cfg(feature = "wasm-runtime")]
pub vp_wasm_cache: crate::vm::wasm::VpCache<CA>,
/// To avoid unused parameter without "wasm-runtime" feature
#[cfg(not(feature = "wasm-runtime"))]
pub cache_access: std::marker::PhantomData<CA>,
}
impl<'a, DB, H, CA> Ctx<'a, DB, H, CA>
where
DB: 'static + storage::DB + for<'iter> storage::DBIter<'iter>,
H: 'static + StorageHasher,
CA: 'static + WasmCacheAccess,
{
/// Initialize a new context for native VP call
pub fn new(
storage: &'a Storage<DB, H>,
write_log: &'a WriteLog,
tx: &'a Tx,
gas_meter: VpGasMeter,
#[cfg(feature = "wasm-runtime")]
vp_wasm_cache: crate::vm::wasm::VpCache<CA>,
) -> Self {
Self {
iterators: RefCell::new(PrefixIterators::default()),
gas_meter: RefCell::new(gas_meter),
storage,
write_log,
tx,
#[cfg(feature = "wasm-runtime")]
vp_wasm_cache,
#[cfg(not(feature = "wasm-runtime"))]
cache_access: std::marker::PhantomData,
}
}
/// Add a gas cost incured in a validity predicate
pub fn add_gas(&self, used_gas: u64) -> Result<()> {
vp_env::add_gas(&mut *self.gas_meter.borrow_mut(), used_gas)
.map_err(Error::ContextError)
}
/// Storage read prior state (before tx execution). It will try to read from
/// the storage.
pub fn read_pre(&self, key: &Key) -> Result<Option<Vec<u8>>> {
vp_env::read_pre(
&mut *self.gas_meter.borrow_mut(),
self.storage,
self.write_log,
key,
)
.map_err(Error::ContextError)
}
/// Storage read posterior state (after tx execution). It will try to read
/// from the write log first and if no entry found then from the
/// storage.
pub fn read_post(&self, key: &Key) -> Result<Option<Vec<u8>>> {
vp_env::read_post(
&mut *self.gas_meter.borrow_mut(),
self.storage,
self.write_log,
key,
)
.map_err(Error::ContextError)
}
/// Storage read temporary state (after tx execution). It will try to read
/// from only the write log.
pub fn read_temp(&self, key: &Key) -> Result<Option<Vec<u8>>> {
vp_env::read_temp(
&mut *self.gas_meter.borrow_mut(),
self.write_log,
key,
)
.map_err(Error::ContextError)
}
/// Storage `has_key` in prior state (before tx execution). It will try to
/// read from the storage.
pub fn has_key_pre(&self, key: &Key) -> Result<bool> {
vp_env::has_key_pre(
&mut *self.gas_meter.borrow_mut(),
self.storage,
key,
)
.map_err(Error::ContextError)
}
/// Storage `has_key` in posterior state (after tx execution). It will try
/// to check the write log first and if no entry found then the storage.
pub fn has_key_post(&self, key: &Key) -> Result<bool> {
vp_env::has_key_post(
&mut *self.gas_meter.borrow_mut(),
self.storage,
self.write_log,
key,
)
.map_err(Error::ContextError)
}
/// Getting the chain ID.
pub fn get_chain_id(&self) -> Result<String> {
vp_env::get_chain_id(&mut *self.gas_meter.borrow_mut(), self.storage)
.map_err(Error::ContextError)
}
/// Getting the block height. The height is that of the block to which the
/// current transaction is being applied.
pub fn get_block_height(&self) -> Result<BlockHeight> {
vp_env::get_block_height(
&mut *self.gas_meter.borrow_mut(),
self.storage,
)
.map_err(Error::ContextError)
}
/// Getting the block hash. The height is that of the block to which the
/// current transaction is being applied.
pub fn get_block_hash(&self) -> Result<BlockHash> {
vp_env::get_block_hash(&mut *self.gas_meter.borrow_mut(), self.storage)
.map_err(Error::ContextError)
}
/// Getting the block epoch. The epoch is that of the block to which the
/// current transaction is being applied.
pub fn get_block_epoch(&self) -> Result<Epoch> {
vp_env::get_block_epoch(&mut *self.gas_meter.borrow_mut(), self.storage)
.map_err(Error::ContextError)
}
/// Storage prefix iterator. It will try to get an iterator from the
/// storage.
pub fn iter_prefix(
&self,
prefix: &Key,
) -> Result<<DB as storage::DBIter<'a>>::PrefixIter> {
vp_env::iter_prefix(
&mut *self.gas_meter.borrow_mut(),
self.storage,
prefix,
)
.map_err(Error::ContextError)
}
/// Storage prefix iterator for prior state (before tx execution). It will
/// try to read from the storage.
pub fn iter_pre_next(
&self,
iter: &mut <DB as storage::DBIter<'_>>::PrefixIter,
) -> Result<Option<(String, Vec<u8>)>> {
vp_env::iter_pre_next::<DB>(&mut *self.gas_meter.borrow_mut(), iter)
.map_err(Error::ContextError)
}
/// Storage prefix iterator next for posterior state (after tx execution).
/// It will try to read from the write log first and if no entry found
/// then from the storage.
pub fn iter_post_next(
&self,
iter: &mut <DB as storage::DBIter<'_>>::PrefixIter,
) -> Result<Option<(String, Vec<u8>)>> {
vp_env::iter_post_next::<DB>(
&mut *self.gas_meter.borrow_mut(),
self.write_log,
iter,
)
.map_err(Error::ContextError)
}
/// Evaluate a validity predicate with given data. The address, changed
/// storage keys and verifiers will have the same values as the input to
/// caller's validity predicate.
///
/// If the execution fails for whatever reason, this will return `false`.
/// Otherwise returns the result of evaluation.
pub fn eval(
&mut self,
address: &Address,
keys_changed: &BTreeSet<Key>,
verifiers: &BTreeSet<Address>,
vp_code: Vec<u8>,
input_data: Vec<u8>,
) -> bool {
#[cfg(feature = "wasm-runtime")]
{
use std::marker::PhantomData;
use crate::vm::host_env::VpCtx;
use crate::vm::wasm::run::VpEvalWasm;
let eval_runner = VpEvalWasm {
db: PhantomData,
hasher: PhantomData,
cache_access: PhantomData,
};
let mut iterators: PrefixIterators<'_, DB> =
PrefixIterators::default();
let mut result_buffer: Option<Vec<u8>> = None;
let ctx = VpCtx::new(
address,
self.storage,
self.write_log,
&mut *self.gas_meter.borrow_mut(),
self.tx,
&mut iterators,
verifiers,
&mut result_buffer,
keys_changed,
&eval_runner,
&mut self.vp_wasm_cache,
);
match eval_runner.eval_native_result(ctx, vp_code, input_data) {
Ok(result) => result,
Err(err) => {
tracing::warn!(
"VP eval from a native VP failed with: {}",
err
);
false
}
}
}
#[cfg(not(feature = "wasm-runtime"))]
{
let _ = (address, keys_changed, verifiers, vp_code, input_data);
unimplemented!(
"The \"wasm-runtime\" feature must be enabled to use the \
`eval` function."
)
}
}
}
/// A convenience trait for reading and automatically deserializing a value from
/// storage
pub trait StorageReader {
/// If `maybe_bytes` is not empty, return an `Option<T>` containing the
/// deserialization of the bytes inside `maybe_bytes`.
fn deserialize_if_present<T: BorshDeserialize>(
maybe_bytes: Option<Vec<u8>>,
) -> eyre::Result<Option<T>> {
maybe_bytes
.map(|ref bytes| {
T::try_from_slice(bytes)
.wrap_err_with(|| "couldn't deserialize".to_string())
})
.transpose()
}
/// Storage read prior state (before tx execution). It will try to read from
/// the storage.
fn read_pre_value<T: BorshDeserialize>(
&self,
key: &Key,
) -> eyre::Result<Option<T>>;
/// Storage read posterior state (after tx execution). It will try to read
/// from the write log first and if no entry found then from the
/// storage.
fn read_post_value<T: BorshDeserialize>(
&self,
key: &Key,
) -> eyre::Result<Option<T>>;
}
impl<'a, DB, H, CA> StorageReader for &Ctx<'a, DB, H, CA>
where
DB: 'static + storage::DB + for<'iter> storage::DBIter<'iter>,
H: 'static + StorageHasher,
CA: 'static + WasmCacheAccess,
{
/// Helper function. After reading posterior state,
/// borsh deserialize to specified type
fn read_post_value<T>(&self, key: &Key) -> eyre::Result<Option<T>>
where
T: BorshDeserialize,
{
let maybe_bytes = Ctx::read_post(self, key)
.wrap_err_with(|| format!("couldn't read_post {}", key))?;
Self::deserialize_if_present(maybe_bytes)
}
/// Helper function. After reading prior state,
/// borsh deserialize to specified type
fn read_pre_value<T>(&self, key: &Key) -> eyre::Result<Option<T>>
where
T: BorshDeserialize,
{
let maybe_bytes = Ctx::read_pre(self, key)
.wrap_err_with(|| format!("couldn't read_pre {}", key))?;
Self::deserialize_if_present(maybe_bytes)
}
}
#[cfg(any(test, feature = "testing"))]
pub(super) mod testing {
use std::collections::HashMap;
use super::*;
#[derive(Debug, Default)]
pub(in super::super) struct FakeStorageReader {
pre: HashMap<Key, Vec<u8>>,
post: HashMap<Key, Vec<u8>>,
}
impl StorageReader for FakeStorageReader {
fn read_pre_value<T: BorshDeserialize>(
&self,
key: &Key,
) -> eyre::Result<Option<T>> {
let bytes = match self.pre.get(key) {
Some(bytes) => bytes.to_owned(),
None => return Ok(None),
};
Self::deserialize_if_present(Some(bytes))
}
fn read_post_value<T: BorshDeserialize>(
&self,
key: &Key,
) -> eyre::Result<Option<T>> {
let bytes = match self.post.get(key) {
Some(bytes) => bytes.to_owned(),
None => return Ok(None),
};
Self::deserialize_if_present(Some(bytes))
}
}
}