This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 107
/
py_validator.rs
210 lines (185 loc) · 8.31 KB
/
py_validator.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
use blockifier::execution::call_info::CallInfo;
use blockifier::fee::actual_cost::ActualCost;
use blockifier::fee::fee_checks::PostValidationReport;
use blockifier::state::cached_state::{GlobalContractCache, GLOBAL_CONTRACT_CACHE_SIZE_FOR_TEST};
use blockifier::state::state_api::StateReader;
use blockifier::transaction::account_transaction::AccountTransaction;
use blockifier::transaction::objects::{AccountTransactionContext, TransactionExecutionResult};
use blockifier::transaction::transaction_execution::Transaction;
use blockifier::versioned_constants::VersionedConstants;
use pyo3::prelude::*;
use starknet_api::core::Nonce;
use starknet_api::hash::StarkFelt;
use crate::errors::NativeBlockifierResult;
use crate::py_block_executor::{PyGeneralConfig, TypedTransactionExecutionInfo};
use crate::py_state_diff::PyBlockInfo;
use crate::py_transaction::{py_account_tx, py_tx};
use crate::py_transaction_execution_info::PyBouncerInfo;
use crate::py_utils::{versioned_constants_with_overrides, PyFelt};
use crate::state_readers::py_state_reader::PyStateReader;
use crate::transaction_executor::{RawTransactionExecutionInfo, TransactionExecutor};
/// Manages transaction validation for pre-execution flows.
#[pyclass]
pub struct PyValidator {
pub max_nonce_for_validation_skip: Nonce,
pub tx_executor: TransactionExecutor<PyStateReader>,
}
#[pymethods]
impl PyValidator {
#[new]
#[pyo3(signature = (general_config, state_reader_proxy, next_block_info, max_recursion_depth, global_contract_cache_size, max_nonce_for_validation_skip))]
pub fn create(
general_config: PyGeneralConfig,
state_reader_proxy: &PyAny,
next_block_info: PyBlockInfo,
max_recursion_depth: usize,
global_contract_cache_size: usize,
max_nonce_for_validation_skip: PyFelt,
) -> NativeBlockifierResult<Self> {
let versioned_constants = versioned_constants_with_overrides(max_recursion_depth);
let tx_executor = TransactionExecutor::new(
PyStateReader::new(state_reader_proxy),
&general_config,
// TODO(Gilad): add max_validate_n_steps override argument and override here.
&versioned_constants,
next_block_info,
GlobalContractCache::new(global_contract_cache_size),
)?;
let validator = Self {
max_nonce_for_validation_skip: Nonce(max_nonce_for_validation_skip.0),
tx_executor,
};
Ok(validator)
}
// Transaction Execution API.
#[pyo3(signature = (tx, raw_contract_class, deploy_account_tx_hash))]
pub fn perform_validations(
&mut self,
tx: &PyAny,
raw_contract_class: Option<&str>,
deploy_account_tx_hash: Option<PyFelt>,
) -> NativeBlockifierResult<()> {
let account_tx = py_account_tx(tx, raw_contract_class)?;
let account_tx_context = account_tx.get_account_tx_context();
// Deploy account transactions should be fully executed, since the constructor must run
// before `__validate_deploy__`. The execution already includes all necessary validations,
// so they are skipped here.
if let AccountTransaction::DeployAccount(_deploy_account_tx) = account_tx {
let (_raw_tx_execution_info, _py_bouncer_info) =
self.execute(tx, raw_contract_class)?;
// TODO(Ayelet, 09/11/2023): Check call succeeded.
return Ok(());
}
// First, we check if the transaction should be skipped due to the deploy account not being
// processed. It is done before the pre-validations checks because, in these checks, we
// change the state (more precisely, we increment the nonce).
let skip_validate = self.skip_validate_due_to_unprocessed_deploy_account(
&account_tx_context,
deploy_account_tx_hash,
)?;
self.perform_pre_validation_stage(&account_tx)?;
if skip_validate {
return Ok(());
}
// `__validate__` call.
let (_optional_call_info, actual_cost) =
self.validate(account_tx, Transaction::initial_gas())?;
// Post validations.
// TODO(Ayelet, 09/11/2023): Check call succeeded.
self.perform_post_validation_stage(&account_tx_context, &actual_cost)?;
Ok(())
}
#[cfg(any(feature = "testing", test))]
#[pyo3(signature = (general_config, state_reader_proxy, next_block_info))]
#[staticmethod]
fn create_for_testing(
general_config: PyGeneralConfig,
state_reader_proxy: &PyAny,
next_block_info: PyBlockInfo,
) -> NativeBlockifierResult<Self> {
let tx_executor = TransactionExecutor::new(
PyStateReader::new(state_reader_proxy),
&general_config,
&VersionedConstants::latest_constants().clone(),
next_block_info,
GlobalContractCache::new(GLOBAL_CONTRACT_CACHE_SIZE_FOR_TEST),
)?;
Ok(Self { max_nonce_for_validation_skip: Nonce(StarkFelt::ONE), tx_executor })
}
/// Applicable solely to account deployment transactions: the execution of the constructor
/// is required before they can be validated.
fn execute(
&mut self,
tx: &PyAny,
raw_contract_class: Option<&str>,
) -> NativeBlockifierResult<(RawTransactionExecutionInfo, PyBouncerInfo)> {
let limit_execution_steps_by_resource_bounds = true;
let tx_type: &str = tx.getattr("tx_type")?.getattr("name")?.extract()?;
let tx: Transaction = py_tx(tx, raw_contract_class)?;
let (tx_execution_info, py_bouncer_info) =
self.tx_executor.execute(tx, limit_execution_steps_by_resource_bounds)?;
let typed_tx_execution_info =
TypedTransactionExecutionInfo { info: tx_execution_info, tx_type: tx_type.to_string() };
let raw_tx_execution_info = serde_json::to_vec(&typed_tx_execution_info)?;
Ok((raw_tx_execution_info, py_bouncer_info))
}
}
impl PyValidator {
fn perform_pre_validation_stage(
&mut self,
account_tx: &AccountTransaction,
) -> NativeBlockifierResult<()> {
let account_tx_context = account_tx.get_account_tx_context();
let strict_nonce_check = false;
// Run pre-validation in charge fee mode to perform fee and balance related checks.
let charge_fee = true;
account_tx.perform_pre_validation_stage(
&mut self.tx_executor.state,
&account_tx_context,
&self.tx_executor.block_context,
charge_fee,
strict_nonce_check,
)?;
Ok(())
}
// Check if deploy account was submitted but not processed yet. If so, then skip
// `__validate__` method for subsequent transactions for a better user experience.
// (they will otherwise fail solely because the deploy account hasn't been processed yet).
fn skip_validate_due_to_unprocessed_deploy_account(
&mut self,
account_tx_context: &AccountTransactionContext,
deploy_account_tx_hash: Option<PyFelt>,
) -> NativeBlockifierResult<bool> {
let nonce = self.tx_executor.state.get_nonce_at(account_tx_context.sender_address())?;
let tx_nonce = account_tx_context.nonce();
let deploy_account_not_processed =
deploy_account_tx_hash.is_some() && nonce == Nonce(StarkFelt::ZERO);
let is_post_deploy_nonce = Nonce(StarkFelt::ONE) <= tx_nonce;
let nonce_small_enough_to_qualify_for_validation_skip =
tx_nonce <= self.max_nonce_for_validation_skip;
let skip_validate = deploy_account_not_processed
&& is_post_deploy_nonce
&& nonce_small_enough_to_qualify_for_validation_skip;
Ok(skip_validate)
}
fn validate(
&mut self,
account_tx: AccountTransaction,
remaining_gas: u64,
) -> NativeBlockifierResult<(Option<CallInfo>, ActualCost)> {
let (optional_call_info, actual_cost) =
self.tx_executor.validate(&account_tx, remaining_gas)?;
Ok((optional_call_info, actual_cost))
}
fn perform_post_validation_stage(
&mut self,
account_tx_context: &AccountTransactionContext,
actual_cost: &ActualCost,
) -> TransactionExecutionResult<()> {
PostValidationReport::verify(
&self.tx_executor.block_context,
account_tx_context,
actual_cost,
)
}
}