neo3/neo_clients/rpc/transports/
common.rs

1// Code adapted from: https://github.com/althea-net/guac_rs/tree/master/web3/src/jsonrpc
2
3use std::fmt;
4
5use base64::{engine::general_purpose, Engine};
6use jsonwebtoken::{encode, errors::Error, get_current_timestamp, Algorithm, EncodingKey, Header};
7use primitive_types::U256;
8use serde::{
9	de::{self, MapAccess, Unexpected, Visitor},
10	Deserialize, Serialize,
11};
12use serde_json::{value::RawValue, Value};
13use thiserror::Error;
14
15use neo3::prelude::Bytes;
16
17/// A JSON-RPC 2.0 error
18#[derive(Deserialize, Debug, Clone, Error, PartialEq)]
19pub struct JsonRpcError {
20	/// The error code
21	pub code: i64,
22	/// The error message
23	pub message: String,
24	/// Additional data
25	pub data: Option<Value>,
26}
27
28/// Recursively traverses the value, looking for hex data that it can extract.
29///
30/// Inspired by neo-js logic:
31/// <https://github.com/neo-io/neo.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
32fn spelunk_revert(value: &Value) -> Option<Bytes> {
33	match value {
34		Value::String(s) => Some(s.as_bytes().to_vec()),
35		Value::Object(o) => o.values().flat_map(spelunk_revert).next(),
36		_ => None,
37	}
38}
39
40impl JsonRpcError {
41	/// Determine if the error output of the `neo_call` RPC request is a revert
42	///
43	/// Note that this may return false positives if called on an error from
44	/// other RPC requests
45	pub fn is_revert(&self) -> bool {
46		// Ganache says "revert" not "reverted"
47		self.message.contains("revert")
48	}
49
50	/// Attempt to extract revert data from the JsonRpcError be recursively
51	/// traversing the error's data field
52	///
53	/// This returns the first hex it finds in the data object, and its
54	/// behavior may change with `serde_json` internal changes.
55	///
56	/// If no hex object is found, it will return an empty bytes IFF the error
57	/// is a revert
58	///
59	/// Inspired by neo-js logic:
60	/// <https://github.com/neo-io/neo.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
61	pub fn as_revert_data(&self) -> Option<Bytes> {
62		self.is_revert()
63			.then(|| self.data.as_ref().and_then(spelunk_revert).unwrap_or_default())
64	}
65
66	// Decode revert data (if any) into a decodeable type
67	// pub fn decode_revert_data<E: AbiDecode>(&self) -> Option<E> {
68	// 	E::decode(&self.as_revert_data()?).ok()
69	// }
70}
71
72impl fmt::Display for JsonRpcError {
73	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74		write!(f, "(code: {}, message: {}, data: {:?})", self.code, self.message, self.data)
75	}
76}
77
78fn is_zst<T>(_t: &T) -> bool {
79	std::mem::size_of::<T>() == 0
80}
81
82#[derive(Serialize, Deserialize, Debug)]
83/// A JSON-RPC request
84pub struct Request<'a, T> {
85	id: u64,
86	jsonrpc: &'a str,
87	method: &'a str,
88	#[serde(skip_serializing_if = "is_zst")]
89	params: T,
90}
91
92impl<'a, T> Request<'a, T> {
93	/// Creates a new JSON RPC request
94	pub fn new(id: u64, method: &'a str, params: T) -> Self {
95		Self { id, jsonrpc: "2.0", method, params }
96	}
97}
98
99/// A JSON-RPC response
100#[derive(Debug)]
101pub enum Response<'a> {
102	Success { id: u64, result: &'a RawValue },
103	Error { id: u64, error: JsonRpcError },
104	Notification { method: &'a str, params: Params<'a> },
105}
106
107#[derive(Deserialize, Debug)]
108pub struct Params<'a> {
109	pub subscription: U256,
110	#[serde(borrow)]
111	pub result: &'a RawValue,
112}
113
114// Note: Custom deserialization is required because serde's untagged enum support
115// has limitations with borrowing (see https://github.com/serde-rs/serde/issues/1183)
116impl<'de: 'a, 'a> Deserialize<'de> for Response<'a> {
117	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118	where
119		D: serde::Deserializer<'de>,
120	{
121		struct ResponseVisitor<'a>(&'a ());
122		impl<'de: 'a, 'a> Visitor<'de> for ResponseVisitor<'a> {
123			type Value = Response<'a>;
124
125			fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
126				formatter.write_str("a valid jsonrpc 2.0 response object")
127			}
128
129			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
130			where
131				A: MapAccess<'de>,
132			{
133				let mut jsonrpc = false;
134
135				// response & error
136				let mut id = None;
137				// only response
138				let mut result = None;
139				// only error
140				let mut error = None;
141				// only notification
142				let mut method = None;
143				let mut params = None;
144
145				while let Some(key) = map.next_key()? {
146					match key {
147						"jsonrpc" => {
148							if jsonrpc {
149								return Err(de::Error::duplicate_field("jsonrpc"));
150							}
151
152							let value = map.next_value()?;
153							if value != "2.0" {
154								return Err(de::Error::invalid_value(
155									Unexpected::Str(value),
156									&"2.0",
157								));
158							}
159
160							jsonrpc = true;
161						},
162						"id" => {
163							if id.is_some() {
164								return Err(de::Error::duplicate_field("id"));
165							}
166
167							let value: u64 = map.next_value()?;
168							id = Some(value);
169						},
170						"result" => {
171							if result.is_some() {
172								return Err(de::Error::duplicate_field("result"));
173							}
174
175							let value: &RawValue = map.next_value()?;
176							result = Some(value);
177						},
178						"error" => {
179							if error.is_some() {
180								return Err(de::Error::duplicate_field("error"));
181							}
182
183							let value: JsonRpcError = map.next_value()?;
184							error = Some(value);
185						},
186						"method" => {
187							if method.is_some() {
188								return Err(de::Error::duplicate_field("method"));
189							}
190
191							let value: &str = map.next_value()?;
192							method = Some(value);
193						},
194						"params" => {
195							if params.is_some() {
196								return Err(de::Error::duplicate_field("params"));
197							}
198
199							let value: Params = map.next_value()?;
200							params = Some(value);
201						},
202						key =>
203							return Err(de::Error::unknown_field(
204								key,
205								&["id", "jsonrpc", "result", "error", "params", "method"],
206							)),
207					}
208				}
209
210				// jsonrpc version must be present in all responses
211				if !jsonrpc {
212					return Err(de::Error::missing_field("jsonrpc"));
213				}
214
215				match (id, result, error, method, params) {
216					(Some(id), Some(result), None, None, None) =>
217						Ok(Response::Success { id, result }),
218					(Some(id), None, Some(error), None, None) => Ok(Response::Error { id, error }),
219					(None, None, None, Some(method), Some(params)) =>
220						Ok(Response::Notification { method, params }),
221					_ => Err(de::Error::custom(
222						"response must be either a success/error or notification object",
223					)),
224				}
225			}
226		}
227
228		deserializer.deserialize_map(ResponseVisitor(&()))
229	}
230}
231
232/// Basic or bearer authentication in http or websocket transport
233///
234/// Use to inject username and password or an auth token into requests
235#[derive(Clone, Debug)]
236pub enum Authorization {
237	/// HTTP Basic Auth
238	Basic(String),
239	/// Bearer Auth
240	Bearer(String),
241	/// If you need to override the Authorization header value
242	Raw(String),
243}
244
245impl Authorization {
246	/// Make a new basic auth
247	pub fn basic(username: impl AsRef<str>, password: impl AsRef<str>) -> Self {
248		let username = username.as_ref();
249		let password = password.as_ref();
250		let auth_secret = general_purpose::STANDARD.encode(format!("{username}:{password}"));
251		Self::Basic(auth_secret)
252	}
253
254	/// Make a new bearer auth
255	pub fn bearer(token: impl Into<String>) -> Self {
256		Self::Bearer(token.into())
257	}
258
259	/// Override the Authorization header with your own string
260	pub fn raw(token: impl Into<String>) -> Self {
261		Self::Raw(token.into())
262	}
263}
264
265impl fmt::Display for Authorization {
266	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267		match self {
268			Authorization::Basic(auth_secret) => write!(f, "Basic {auth_secret}"),
269			Authorization::Bearer(token) => write!(f, "Bearer {token}"),
270			Authorization::Raw(s) => write!(f, "{s}"),
271		}
272	}
273}
274
275/// Default algorithm used for JWT token signing.
276const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
277
278/// JWT secret length in bytes.
279pub const JWT_SECRET_LENGTH: usize = 32;
280
281/// Generates a bearer token from a JWT secret
282pub struct JwtKey([u8; JWT_SECRET_LENGTH]);
283
284impl JwtKey {
285	/// Wrap given slice in `Self`. Returns an error if slice.len() != `JWT_SECRET_LENGTH`.
286	pub fn from_slice(key: &[u8]) -> Result<Self, String> {
287		if key.len() != JWT_SECRET_LENGTH {
288			return Err(format!(
289				"Invalid key length. Expected {} got {}",
290				JWT_SECRET_LENGTH,
291				key.len()
292			));
293		}
294		let mut res = [0; JWT_SECRET_LENGTH];
295		res.copy_from_slice(key);
296		Ok(Self(res))
297	}
298
299	/// Decode the given string from hex (no 0x prefix), and attempt to create a key from it.
300	pub fn from_hex(hex: &str) -> Result<Self, String> {
301		let bytes = hex::decode(hex).map_err(|e| format!("Invalid hex: {}", e))?;
302		Self::from_slice(&bytes)
303	}
304
305	/// Returns a reference to the underlying byte array.
306	pub fn as_bytes(&self) -> &[u8; JWT_SECRET_LENGTH] {
307		&self.0
308	}
309
310	/// Consumes the key, returning its underlying byte array.
311	pub fn into_bytes(self) -> [u8; JWT_SECRET_LENGTH] {
312		self.0
313	}
314}
315
316/// Contains the JWT secret and claims parameters.
317pub struct JwtAuth {
318	key: EncodingKey,
319	id: Option<String>,
320	clv: Option<String>,
321}
322
323impl JwtAuth {
324	/// Create a new [JwtAuth] from a secret key, and optional `id` and `clv` claims.
325	pub fn new(secret: JwtKey, id: Option<String>, clv: Option<String>) -> Self {
326		Self { key: EncodingKey::from_secret(secret.as_bytes()), id, clv }
327	}
328
329	/// Generate a JWT token with `claims.iat` set to current time.
330	pub fn generate_token(&self) -> Result<String, Error> {
331		let claims = self.generate_claims_at_timestamp();
332		self.generate_token_with_claims(&claims)
333	}
334
335	/// Generate a JWT token with the given claims.
336	fn generate_token_with_claims(&self, claims: &Claims) -> Result<String, Error> {
337		let header = Header::new(DEFAULT_ALGORITHM);
338		encode(&header, claims, &self.key)
339	}
340
341	/// Generate a `Claims` struct with `iat` set to current time
342	fn generate_claims_at_timestamp(&self) -> Claims {
343		Claims { iat: get_current_timestamp(), id: self.id.clone(), clv: self.clv.clone() }
344	}
345
346	/// Validate a JWT token given the secret key and return the originally signed `TokenData`.
347	pub fn validate_token(
348		token: &str,
349		secret: &JwtKey,
350	) -> Result<jsonwebtoken::TokenData<Claims>, Error> {
351		let mut validation = jsonwebtoken::Validation::new(DEFAULT_ALGORITHM);
352		validation.validate_exp = false;
353		validation.required_spec_claims.remove("exp");
354
355		jsonwebtoken::decode::<Claims>(
356			token,
357			&jsonwebtoken::DecodingKey::from_secret(secret.as_bytes()),
358			&validation,
359		)
360		.map_err(Into::into)
361	}
362}
363
364/// Claims struct as defined in <https://github.com/neo/execution-apis/blob/main/src/engine/authentication.md#jwt-claims>
365#[derive(Debug, Serialize, Deserialize, PartialEq)]
366pub struct Claims {
367	/// issued-at claim. Represented as seconds passed since UNIX_EPOCH.
368	iat: u64,
369	/// Optional unique identifier for the CL node.
370	id: Option<String>,
371	/// Optional client version for the CL node.
372	clv: Option<String>,
373}
374
375#[cfg(test)]
376mod tests {
377	use super::*;
378
379	#[test]
380	fn deser_response() {
381		let _ =
382			serde_json::from_str::<Response<'_>>(r#"{"jsonrpc":"2.0","result":19}"#).unwrap_err();
383		let _ = serde_json::from_str::<Response<'_>>(r#"{"jsonrpc":"3.0","result":19,"id":1}"#)
384			.unwrap_err();
385
386		let response: Response<'_> =
387			serde_json::from_str(r#"{"jsonrpc":"2.0","result":19,"id":1}"#).unwrap();
388
389		match response {
390			Response::Success { id, result } => {
391				assert_eq!(id, 1);
392				let result: u64 = serde_json::from_str(result.get()).unwrap();
393				assert_eq!(result, 19);
394			},
395			_ => {
396				assert!(false, "Expected Success response but got: {:?}", response);
397			},
398		}
399
400		let response: Response<'_> = serde_json::from_str(
401			r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"error occurred"},"id":2}"#,
402		)
403		.unwrap();
404
405		match response {
406			Response::Error { id, error } => {
407				assert_eq!(id, 2);
408				assert_eq!(error.code, -32000);
409				assert_eq!(error.message, "error occurred");
410				assert!(error.data.is_none());
411			},
412			_ => {
413				assert!(false, "Expected Error response but got: {:?}", response);
414			},
415		}
416
417		let response: Response<'_> =
418			serde_json::from_str(r#"{"jsonrpc":"2.0","result":"0xfa","id":0}"#).unwrap();
419
420		match response {
421			Response::Success { id, result } => {
422				assert_eq!(id, 0);
423				let result: String = serde_json::from_str(result.get()).unwrap();
424				assert_eq!(i64::from_str_radix(result.trim_start_matches("0x"), 16).unwrap(), 250);
425			},
426			_ => {
427				assert!(false, "Expected Success response but got: {:?}", response);
428			},
429		}
430	}
431
432	#[test]
433	fn ser_request() {
434		let request: Request<()> = Request::new(0, "neo_chainId", ());
435		assert_eq!(
436			&serde_json::to_string(&request).unwrap(),
437			r#"{"id":0,"jsonrpc":"2.0","method":"neo_chainId"}"#
438		);
439
440		let request: Request<()> = Request::new(300, "method_name", ());
441		assert_eq!(
442			&serde_json::to_string(&request).unwrap(),
443			r#"{"id":300,"jsonrpc":"2.0","method":"method_name"}"#
444		);
445
446		let request: Request<u32> = Request::new(300, "method_name", 1);
447		assert_eq!(
448			&serde_json::to_string(&request).unwrap(),
449			r#"{"id":300,"jsonrpc":"2.0","method":"method_name","params":1}"#
450		);
451	}
452
453	#[test]
454	fn test_roundtrip() {
455		let jwt_secret = [42; 32];
456		let auth = JwtAuth::new(
457			JwtKey::from_slice(&jwt_secret).unwrap(),
458			Some("42".into()),
459			Some("Lighthouse".into()),
460		);
461		let claims = auth.generate_claims_at_timestamp();
462		let token = auth.generate_token_with_claims(&claims).unwrap();
463
464		assert_eq!(
465			JwtAuth::validate_token(&token, &JwtKey::from_slice(&jwt_secret).unwrap())
466				.unwrap()
467				.claims,
468			claims
469		);
470	}
471}