-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathview_function.rs
More file actions
237 lines (219 loc) · 8.31 KB
/
Copy pathview_function.rs
File metadata and controls
237 lines (219 loc) · 8.31 KB
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
// Copyright (c) Aptos Foundation
// Licensed pursuant to the Innovation-Enabling Source Code License, available at https://github.com/aptos-labs/aptos-core/blob/main/LICENSE
use crate::{
accept_type::AcceptType,
bcs_payload::Bcs,
context::{api_spawn_blocking, FunctionStats},
failpoint::fail_point_poem,
response::{
BadRequestError, BasicErrorWith404, BasicResponse, BasicResponseStatus, BasicResultWith404,
ForbiddenError, InternalError,
},
ApiTags, Context,
};
use anyhow::Context as anyhowContext;
use aptos_api_types::{
AptosErrorCode, AsConverter, MoveValue, ViewFunction, ViewRequest, MAX_RECURSIVE_TYPES_ALLOWED,
U64,
};
use aptos_bcs_utils::serialize_uleb128;
use aptos_types::{state_store::StateView, transaction::ViewFunctionError, vm_status::StatusCode};
use aptos_vm::AptosVM;
use itertools::Itertools;
use move_core_types::language_storage::TypeTag;
use poem_openapi::{param::Query, payload::Json, ApiRequest, OpenApi};
use std::sync::Arc;
/// API for executing Move view function.
#[derive(Clone)]
pub struct ViewFunctionApi {
pub context: Arc<Context>,
}
pub fn convert_view_function_error(
error: &ViewFunctionError,
state_view: &impl StateView,
context: &Context,
) -> (String, Option<StatusCode>) {
match error {
ViewFunctionError::MoveAbort(status, vm_error_code) => {
let vm_status = state_view
.as_converter(context.db.clone(), context.indexer_reader.clone())
.explain_vm_status(status, None);
(vm_status, *vm_error_code)
},
ViewFunctionError::ErrorMessage(message, vm_error_code) => {
(message.clone(), *vm_error_code)
},
}
}
#[derive(ApiRequest, Debug)]
pub enum ViewFunctionRequest {
#[oai(content_type = "application/json")]
Json(Json<ViewRequest>),
#[oai(content_type = "application/x.aptos.view_function+bcs")]
Bcs(Bcs),
}
#[OpenApi]
impl ViewFunctionApi {
/// Execute view function of a module
///
/// Execute the Move function with the given parameters and return its execution result.
///
/// The Aptos nodes prune account state history, via a configurable time window.
/// If the requested ledger version has been pruned, the server responds with a 410.
#[oai(
path = "/view",
method = "post",
operation_id = "view",
tag = "ApiTags::View"
)]
async fn view_function(
&self,
accept_type: AcceptType,
/// View function request with type and position arguments
request: ViewFunctionRequest,
/// Ledger version to get state of account
///
/// If not provided, it will be the latest version
ledger_version: Query<Option<U64>>,
) -> BasicResultWith404<Vec<MoveValue>> {
fail_point_poem("endpoint_view_function")?;
self.context
.check_api_output_enabled("View function", &accept_type)?;
let context = self.context.clone();
api_spawn_blocking(move || view_request(context, accept_type, request, ledger_version))
.await
}
}
fn view_request(
context: Arc<Context>,
accept_type: AcceptType,
request: ViewFunctionRequest,
ledger_version: Query<Option<U64>>,
) -> BasicResultWith404<Vec<MoveValue>> {
// Retrieve the current state of the chain
let (ledger_info, requested_version) = context
.get_latest_ledger_info_and_verify_lookup_version(ledger_version.map(|inner| inner.0))?;
let state_view = context
.state_view_at_version(requested_version)
.map_err(|err| {
BasicErrorWith404::bad_request_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?;
let view_function: ViewFunction = match request {
ViewFunctionRequest::Json(data) => state_view
.as_converter(context.db.clone(), context.indexer_reader.clone())
.convert_view_function(data.0)
.map_err(|err| {
BasicErrorWith404::bad_request_with_code(
err,
AptosErrorCode::InvalidInput,
&ledger_info,
)
})?,
ViewFunctionRequest::Bcs(data) => {
bcs::from_bytes_with_limit(data.0.as_slice(), MAX_RECURSIVE_TYPES_ALLOWED as usize)
.context("Failed to deserialize input into ViewRequest")
.map_err(|err| {
BasicErrorWith404::bad_request_with_code(
err,
AptosErrorCode::InvalidInput,
&ledger_info,
)
})?
},
};
// Reject the request if it's not allowed by the filter.
if !context.node_config.api.view_filter.allows(
view_function.module.address(),
view_function.module.name().as_str(),
view_function.function.as_str(),
) {
return Err(BasicErrorWith404::forbidden_with_code_no_info(
format!(
"Function {}::{} is not allowed",
view_function.module, view_function.function
),
AptosErrorCode::InvalidInput,
));
}
let output = AptosVM::execute_view_function(
&state_view,
view_function.module.clone(),
view_function.function.clone(),
view_function.ty_args.clone(),
view_function.args.clone(),
context.node_config.api.max_gas_view_function,
);
let values = output.values.map_err(|status| {
let (err_string, vm_error_code) =
convert_view_function_error(&status, &state_view, &context);
BasicErrorWith404::bad_request_with_optional_vm_status_and_ledger_info(
anyhow::anyhow!(err_string),
AptosErrorCode::InvalidInput,
vm_error_code,
Some(&ledger_info),
)
})?;
let result = match accept_type {
AcceptType::Bcs => {
// The return values are already BCS encoded, but we still need to encode the outside
// vector without re-encoding the inside values
let num_vals = values.len();
// Push the length of the return values
let mut length = vec![];
serialize_uleb128(&mut length, num_vals as u64).map_err(|err| {
BasicErrorWith404::internal_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?;
// Combine all of the return values
let values = values.into_iter().concat();
let ret = [length, values].concat();
BasicResponse::try_from_encoded((ret, &ledger_info, BasicResponseStatus::Ok))
},
AcceptType::Json => {
let return_types = state_view
.as_converter(context.db.clone(), context.indexer_reader.clone())
.function_return_types(&view_function)
.and_then(|tys| {
tys.iter()
.map(TypeTag::try_from)
.collect::<anyhow::Result<Vec<_>>>()
})
.map_err(|err| {
BasicErrorWith404::bad_request_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?;
let move_vals = values
.into_iter()
.zip(return_types.into_iter())
.map(|(v, ty)| {
state_view
.as_converter(context.db.clone(), context.indexer_reader.clone())
.try_into_move_value(&ty, &v)
})
.collect::<anyhow::Result<Vec<_>>>()
.map_err(|err| {
BasicErrorWith404::bad_request_with_code(
err,
AptosErrorCode::InternalError,
&ledger_info,
)
})?;
BasicResponse::try_from_json((move_vals, &ledger_info, BasicResponseStatus::Ok))
},
};
context.view_function_stats().increment(
FunctionStats::function_to_key(&view_function.module, &view_function.function),
output.gas_used,
);
result.map(|r| r.with_gas_used(Some(output.gas_used)))
}