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
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Max size of the query path (soft-deprecated)
const QUERY_DATA_MAX_SIZE: usize = 10 * 1024;

#[derive(Serialize, Deserialize)]
pub struct RpcQueryRequest {
    #[serde(flatten)]
    pub block_reference: near_primitives_v01::types::BlockReference,
    #[serde(flatten)]
    pub request: near_primitives_v01::views::QueryRequest,
}

#[derive(thiserror::Error, Debug, Serialize, Deserialize)]
#[serde(tag = "name", content = "info", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RpcQueryError {
    #[error("There are no fully synchronized blocks on the node yet")]
    NoSyncedBlocks,
    #[error("The node does not track the shard ID {requested_shard_id}")]
    UnavailableShard { requested_shard_id: near_primitives_v01::types::ShardId },
    #[error("Block either has never been observed on the node or has been garbage collected: {block_reference:?}")]
    UnknownBlock { block_reference: near_primitives_v01::types::BlockReference },
    #[error("Account ID {requested_account_id} is invalid")]
    InvalidAccount {
        requested_account_id: near_primitives_v01::types::AccountId,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error("account {requested_account_id} does not exist while viewing")]
    UnknownAccount {
        requested_account_id: near_primitives_v01::types::AccountId,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error(
        "Contract code for contract ID #{contract_account_id} has never been observed on the node"
    )]
    NoContractCode {
        contract_account_id: near_primitives_v01::types::AccountId,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error("State of contract {contract_account_id} is too large to be viewed")]
    TooLargeContractState {
        contract_account_id: near_primitives_v01::types::AccountId,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error("Access key for public key {public_key} has never been observed on the node")]
    UnknownAccessKey {
        public_key: near_crypto_v01::PublicKey,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error("Function call returned an error: {vm_error}")]
    ContractExecutionError {
        vm_error: String,
        block_height: near_primitives_v01::types::BlockHeight,
        block_hash: near_primitives_v01::hash::CryptoHash,
    },
    #[error("The node reached its limits. Try again later. More details: {error_message}")]
    InternalError { error_message: String },
}

#[derive(Serialize, Deserialize)]
pub struct RpcQueryResponse {
    #[serde(flatten)]
    pub kind: QueryResponseKind,
    pub block_height: near_primitives_v01::types::BlockHeight,
    pub block_hash: near_primitives_v01::hash::CryptoHash,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum QueryResponseKind {
    ViewAccount(near_primitives_v01::views::AccountView),
    ViewCode(near_primitives_v01::views::ContractCodeView),
    ViewState(near_primitives_v01::views::ViewStateResult),
    CallResult(near_primitives_v01::views::CallResult),
    AccessKey(near_primitives_v01::views::AccessKeyView),
    AccessKeyList(near_primitives_v01::views::AccessKeyList),
}

impl RpcQueryRequest {
    pub fn parse(value: Option<Value>) -> Result<RpcQueryRequest, crate::errors::RpcParseError> {
        let query_request = if let Ok((path, data)) =
            crate::utils::parse_params::<(String, String)>(value.clone())
        {
            // Handle a soft-deprecated version of the query API, which is based on
            // positional arguments with a "path"-style first argument.
            //
            // This whole block can be removed one day, when the new API is 100% adopted.
            let data = near_primitives_core_v01::serialize::from_base(&data)
                .map_err(|err| crate::errors::RpcParseError(err.to_string()))?;
            let query_data_size = path.len() + data.len();
            if query_data_size > QUERY_DATA_MAX_SIZE {
                return Err(crate::errors::RpcParseError(format!(
                    "Query data size {} is too large",
                    query_data_size
                )));
            }

            let mut path_parts = path.splitn(3, '/');
            let make_err =
                || crate::errors::RpcParseError("Not enough query parameters provided".to_string());
            let query_command = path_parts.next().ok_or_else(make_err)?;
            let account_id = path_parts
                .next()
                .ok_or_else(make_err)?
                .parse()
                .map_err(|err| crate::errors::RpcParseError(format!("{}", err)))?;
            let maybe_extra_arg = path_parts.next();

            let request = match query_command {
                "account" => near_primitives_v01::views::QueryRequest::ViewAccount { account_id },
                "access_key" => match maybe_extra_arg {
                    None => {
                        near_primitives_v01::views::QueryRequest::ViewAccessKeyList { account_id }
                    }
                    Some(pk) => near_primitives_v01::views::QueryRequest::ViewAccessKey {
                        account_id,
                        public_key: pk.parse().map_err(|_| {
                            crate::errors::RpcParseError("Invalid public key".to_string())
                        })?,
                    },
                },
                "code" => near_primitives_v01::views::QueryRequest::ViewCode { account_id },
                "contract" => near_primitives_v01::views::QueryRequest::ViewState {
                    account_id,
                    prefix: data.into(),
                },
                "call" => match maybe_extra_arg {
                    Some(method_name) => near_primitives_v01::views::QueryRequest::CallFunction {
                        account_id,
                        method_name: method_name.to_string(),
                        args: data.into(),
                    },
                    None => {
                        return Err(crate::errors::RpcParseError(
                            "Method name is missing".to_string(),
                        ))
                    }
                },
                _ => {
                    return Err(crate::errors::RpcParseError(format!(
                        "Unknown path {}",
                        query_command
                    )))
                }
            };
            // Use Finality::None here to make backward compatibility tests work
            RpcQueryRequest {
                request,
                block_reference: near_primitives_v01::types::BlockReference::latest(),
            }
        } else {
            crate::utils::parse_params::<RpcQueryRequest>(value)?
        };
        Ok(query_request)
    }
}

impl From<near_client_primitives::types::QueryError> for RpcQueryError {
    fn from(error: near_client_primitives::types::QueryError) -> Self {
        match error {
            near_client_primitives::types::QueryError::InternalError { error_message } => {
                Self::InternalError { error_message }
            }
            near_client_primitives::types::QueryError::NoSyncedBlocks => Self::NoSyncedBlocks,
            near_client_primitives::types::QueryError::UnavailableShard { requested_shard_id } => {
                Self::UnavailableShard { requested_shard_id }
            }
            near_client_primitives::types::QueryError::UnknownBlock { block_reference } => {
                Self::UnknownBlock { block_reference }
            }
            near_client_primitives::types::QueryError::InvalidAccount {
                requested_account_id,
                block_height,
                block_hash,
            } => Self::InvalidAccount { requested_account_id, block_height, block_hash },
            near_client_primitives::types::QueryError::UnknownAccount {
                requested_account_id,
                block_height,
                block_hash,
            } => Self::UnknownAccount { requested_account_id, block_height, block_hash },
            near_client_primitives::types::QueryError::NoContractCode {
                contract_account_id,
                block_height,
                block_hash,
            } => Self::NoContractCode { contract_account_id, block_height, block_hash },
            near_client_primitives::types::QueryError::UnknownAccessKey {
                public_key,
                block_height,
                block_hash,
            } => Self::UnknownAccessKey { public_key, block_height, block_hash },
            near_client_primitives::types::QueryError::ContractExecutionError {
                vm_error,
                block_height,
                block_hash,
            } => Self::ContractExecutionError { vm_error, block_height, block_hash },
            near_client_primitives::types::QueryError::Unreachable { ref error_message } => {
                tracing::warn!(target: "jsonrpc", "Unreachable error occurred: {}", &error_message);
                near_metrics::inc_counter_vec(
                    &crate::metrics::RPC_UNREACHABLE_ERROR_COUNT,
                    &["RpcQueryError"],
                );
                Self::InternalError { error_message: error.to_string() }
            }
            near_client_primitives::types::QueryError::TooLargeContractState {
                contract_account_id,
                block_height,
                block_hash,
            } => Self::TooLargeContractState { contract_account_id, block_height, block_hash },
        }
    }
}

impl From<near_primitives_v01::views::QueryResponse> for RpcQueryResponse {
    fn from(query_response: near_primitives_v01::views::QueryResponse) -> Self {
        Self {
            kind: query_response.kind.into(),
            block_hash: query_response.block_hash,
            block_height: query_response.block_height,
        }
    }
}

impl From<near_primitives_v01::views::QueryResponseKind> for QueryResponseKind {
    fn from(query_response_kind: near_primitives_v01::views::QueryResponseKind) -> Self {
        match query_response_kind {
            near_primitives_v01::views::QueryResponseKind::ViewAccount(account_view) => {
                Self::ViewAccount(account_view)
            }
            near_primitives_v01::views::QueryResponseKind::ViewCode(contract_code_view) => {
                Self::ViewCode(contract_code_view)
            }
            near_primitives_v01::views::QueryResponseKind::ViewState(view_state_result) => {
                Self::ViewState(view_state_result)
            }
            near_primitives_v01::views::QueryResponseKind::CallResult(call_result) => {
                Self::CallResult(call_result)
            }
            near_primitives_v01::views::QueryResponseKind::AccessKey(access_key_view) => {
                Self::AccessKey(access_key_view)
            }
            near_primitives_v01::views::QueryResponseKind::AccessKeyList(access_key_list) => {
                Self::AccessKeyList(access_key_list)
            }
        }
    }
}

impl From<RpcQueryError> for crate::errors::RpcError {
    fn from(error: RpcQueryError) -> Self {
        let error_data = Some(serde_json::Value::String(error.to_string()));
        let error_data_value = match serde_json::to_value(error) {
            Ok(value) => value,
            Err(err) => {
                return Self::new_internal_error(
                    None,
                    format!("Failed to serialize RpcQueryError: {:?}", err),
                )
            }
        };
        Self::new_internal_or_handler_error(error_data, error_data_value)
    }
}

impl From<actix::MailboxError> for RpcQueryError {
    fn from(error: actix::MailboxError) -> Self {
        Self::InternalError { error_message: error.to_string() }
    }
}