1use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
2use reqwest::{
3 StatusCode,
4 header::{CONTENT_LENGTH, CONTENT_TYPE},
5};
6use serde::{Deserialize, Serialize, de::DeserializeOwned};
7use uuid::Uuid;
8
9use crate::{
10 chain::SOLANA_CHAIN_ID,
11 error::Error,
12 mix_address::{MixAddress, new_uuid_mix_address},
13 request::{ApiError, HTTP_CLIENT},
14 safe::SafeUser,
15 safe_transaction::{SafeTransactionRecipient, send_safe_transaction},
16 transaction::TransactionView,
17 utils::unique_object_id,
18};
19
20pub const COMPUTER_URI: &str = "https://computer.mixin.one";
21pub const MAX_SOLANA_TX_SIZE: usize = 1232;
22
23pub const OPERATION_TYPE_ADD_USER: u8 = 1;
24pub const OPERATION_TYPE_SYSTEM_CALL: u8 = 2;
25pub const OPERATION_TYPE_USER_DEPOSIT: u8 = 3;
26
27#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
28pub struct ComputerInfo {
29 pub observer: String,
30 pub payer: String,
31 pub height: i64,
32 pub members: ComputerMembers,
33 pub params: ComputerParams,
34}
35
36#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
37pub struct ComputerMembers {
38 pub app_id: String,
39 pub members: Vec<String>,
40 pub threshold: u8,
41}
42
43#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
44pub struct ComputerParams {
45 pub operation: ComputerOperationParams,
46}
47
48#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
49pub struct ComputerOperationParams {
50 pub asset: String,
51 pub price: String,
52}
53
54#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
55pub struct ComputerUser {
56 pub id: String,
57 pub chain_address: String,
58 pub mix_address: String,
59}
60
61#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
62pub struct ComputerDeployedAsset {
63 pub asset_id: String,
64 pub chain_id: String,
65 pub address: String,
66 pub name: String,
67 pub symbol: String,
68 pub decimals: i64,
69 pub price_usd: String,
70 #[serde(rename = "uri")]
71 pub icon_url: String,
72}
73
74impl ComputerDeployedAsset {
75 pub fn solana_asset_id(&self) -> String {
76 unique_object_id([SOLANA_CHAIN_ID, self.address.as_str()])
77 }
78}
79
80#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
81pub struct ComputerSystemCall {
82 #[serde(default)]
83 pub id: String,
84 #[serde(default, rename = "type")]
85 pub type_name: String,
86 #[serde(default)]
87 pub user_id: String,
88 #[serde(default)]
89 pub nonce_account: String,
90 #[serde(default)]
91 pub raw: String,
92 #[serde(default)]
93 pub state: String,
94 #[serde(default)]
95 pub hash: String,
96}
97
98#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
99pub struct ComputerSystemCallResponse {
100 #[serde(flatten)]
101 pub call: ComputerSystemCall,
102 #[serde(default)]
103 pub reason: String,
104 #[serde(default, rename = "subs")]
105 pub sub_calls: Vec<ComputerSystemCall>,
106 #[serde(default)]
107 pub refund_traces: Vec<String>,
108}
109
110#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
111pub struct ComputerNonceAccount {
112 pub mix: String,
113 pub nonce_address: String,
114 pub nonce_hash: String,
115}
116
117#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
118pub struct ComputerFee {
119 pub fee_id: String,
120 pub xin_amount: String,
121}
122
123#[derive(Debug, Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
124pub struct ComputerRegisterPreview {
125 pub mix_address: String,
126 pub trace_id: String,
127 pub mtg_extra: String,
128 pub operation_asset: String,
129 pub operation_price: String,
130 pub mtg_app_id: String,
131 pub mtg_members: Vec<String>,
132 pub mtg_threshold: u8,
133}
134
135#[derive(Debug, Serialize)]
136struct LockNonceAccountRequest<'a> {
137 mix: &'a str,
138}
139
140#[derive(Debug, Serialize)]
141struct FeeRequest<'a> {
142 sol_amount: &'a str,
143}
144
145pub async fn get_computer_info() -> Result<ComputerInfo, Error> {
146 let (status, body) = computer_request("GET", "/", &[]).await?;
147 parse_computer_response(status, &body, "computer info")
148}
149
150pub async fn get_computer_user(address: &str) -> Result<Option<ComputerUser>, Error> {
151 let path = format!("/users/{address}");
152 let (status, body) = computer_request("GET", &path, &[]).await?;
153 match parse_computer_response(status, &body, "computer user") {
154 Ok(user) => Ok(Some(user)),
155 Err(Error::Api(error)) if is_not_found(&error) => Ok(None),
156 Err(error) => Err(error),
157 }
158}
159
160pub async fn get_computer_deployed_assets() -> Result<Vec<ComputerDeployedAsset>, Error> {
161 let (status, body) = computer_request("GET", "/deployed_assets", &[]).await?;
162 parse_computer_response(status, &body, "computer deployed assets")
163}
164
165pub async fn get_computer_system_call(
166 id: &str,
167) -> Result<Option<ComputerSystemCallResponse>, Error> {
168 let path = format!("/system_calls/{id}");
169 let (status, body) = computer_request("GET", &path, &[]).await?;
170 match parse_computer_response(status, &body, "computer system call") {
171 Ok(call) => Ok(Some(call)),
172 Err(Error::Api(error)) if is_not_found(&error) => Ok(None),
173 Err(error) => Err(error),
174 }
175}
176
177pub async fn computer_deploy_external_assets(asset_ids: &[String]) -> Result<(), Error> {
178 for asset_id in asset_ids {
179 if asset_id == SOLANA_CHAIN_ID {
180 return Err(Error::Input(format!(
181 "cannot deploy asset from Solana: {asset_id}"
182 )));
183 }
184 }
185 let body = serde_json::to_vec(asset_ids)?;
186 let (status, body) = computer_request("POST", "/deployed_assets", &body).await?;
187 parse_computer_empty_response(status, &body)
188}
189
190pub async fn lock_computer_nonce_account(mix: &str) -> Result<ComputerNonceAccount, Error> {
191 let body = serde_json::to_vec(&LockNonceAccountRequest { mix })?;
192 let (status, body) = computer_request("POST", "/nonce_accounts", &body).await?;
193 parse_computer_response(status, &body, "computer nonce account")
194}
195
196pub async fn get_fee_on_xin_based_on_sol(sol_amount: &str) -> Result<ComputerFee, Error> {
197 let body = serde_json::to_vec(&FeeRequest { sol_amount })?;
198 let (status, body) = computer_request("POST", "/fee", &body).await?;
199 parse_computer_response(status, &body, "computer fee")
200}
201
202pub fn computer_mix_address_for_user(user_id: &str) -> Result<String, Error> {
203 Ok(new_uuid_mix_address(vec![user_id.to_string()], 1)?.to_string())
204}
205
206pub fn computer_register_trace(mix_address: &str) -> String {
207 unique_object_id([mix_address, "computer_register"])
208}
209
210pub fn build_computer_register_preview(
211 info: &ComputerInfo,
212 safe_user: &SafeUser,
213) -> Result<ComputerRegisterPreview, Error> {
214 let mix_address = computer_mix_address_for_user(&safe_user.user_id)?;
215 let memo = encode_operation_memo(OPERATION_TYPE_ADD_USER, mix_address.as_bytes());
216 let mtg_extra = encode_mtg_extra(&info.members.app_id, &memo)?;
217 Ok(ComputerRegisterPreview {
218 trace_id: computer_register_trace(&mix_address),
219 mix_address,
220 mtg_extra,
221 operation_asset: info.params.operation.asset.clone(),
222 operation_price: info.params.operation.price.clone(),
223 mtg_app_id: info.members.app_id.clone(),
224 mtg_members: info.members.members.clone(),
225 mtg_threshold: info.members.threshold,
226 })
227}
228
229pub async fn preview_register_computer(
230 safe_user: &SafeUser,
231) -> Result<ComputerRegisterPreview, Error> {
232 let info = get_computer_info().await?;
233 build_computer_register_preview(&info, safe_user)
234}
235
236pub async fn register_computer(safe_user: &SafeUser) -> Result<TransactionView, Error> {
237 let info = get_computer_info().await?;
238 let preview = build_computer_register_preview(&info, safe_user)?;
239 let mtg_mix_address =
240 MixAddress::new_uuid(info.members.members.clone(), info.members.threshold)?;
241 let recipient =
242 SafeTransactionRecipient::mix_address(mtg_mix_address, info.params.operation.price);
243 send_safe_transaction(
244 &info.params.operation.asset,
245 &[recipient],
246 &preview.trace_id,
247 preview.mtg_extra.into_bytes(),
248 Vec::new(),
249 safe_user,
250 )
251 .await
252}
253
254pub fn check_system_call_size(tx: &[u8]) -> bool {
255 tx.len() <= MAX_SOLANA_TX_SIZE
256}
257
258pub fn computer_user_id_to_bytes(id: &str) -> Result<[u8; 8], Error> {
259 let value = id
260 .parse::<u64>()
261 .map_err(|err| Error::Input(format!("invalid computer user id {id}: {err}")))?;
262 Ok(value.to_be_bytes())
263}
264
265pub fn build_system_call_extra(
266 uid: &str,
267 call_id: &str,
268 skip_process: bool,
269 fee_id: Option<&str>,
270) -> Result<Vec<u8>, Error> {
271 let mut extra = Vec::with_capacity(8 + 16 + 1 + fee_id.map_or(0, |_| 16));
272 extra.extend_from_slice(&computer_user_id_to_bytes(uid)?);
273 extra.extend_from_slice(
274 Uuid::parse_str(call_id)
275 .map_err(|err| Error::Input(format!("invalid call id {call_id}: {err}")))?
276 .as_bytes(),
277 );
278 extra.push(u8::from(skip_process));
279 if let Some(fee_id) = fee_id {
280 extra.extend_from_slice(
281 Uuid::parse_str(fee_id)
282 .map_err(|err| Error::Input(format!("invalid fee id {fee_id}: {err}")))?
283 .as_bytes(),
284 );
285 }
286 Ok(extra)
287}
288
289pub fn encode_operation_memo(operation: u8, extra: &[u8]) -> Vec<u8> {
290 let mut memo = Vec::with_capacity(1 + extra.len());
291 memo.push(operation);
292 memo.extend_from_slice(extra);
293 memo
294}
295
296pub fn encode_mtg_extra(app_id: &str, extra: &[u8]) -> Result<String, Error> {
297 let mut data = Vec::with_capacity(16 + extra.len());
298 data.extend_from_slice(
299 Uuid::parse_str(app_id)
300 .map_err(|err| Error::Input(format!("invalid computer app id {app_id}: {err}")))?
301 .as_bytes(),
302 );
303 data.extend_from_slice(extra);
304 Ok(URL_SAFE_NO_PAD.encode(data))
305}
306
307pub fn decode_computer_extra_base64(extra: &str) -> Result<(String, Vec<u8>), Error> {
308 let data = URL_SAFE_NO_PAD
309 .decode(extra)
310 .map_err(|err| Error::Input(format!("invalid computer extra base64: {err}")))?;
311 if data.len() < 16 {
312 return Err(Error::Input(format!(
313 "invalid computer extra length: {}",
314 data.len()
315 )));
316 }
317 let app_id = Uuid::from_slice(&data[..16])
318 .map_err(|err| Error::Input(format!("invalid computer app id bytes: {err}")))?
319 .to_string();
320 Ok((app_id, data[16..].to_vec()))
321}
322
323async fn computer_request(
324 method: &str,
325 path: &str,
326 body: &[u8],
327) -> Result<(StatusCode, Vec<u8>), Error> {
328 let uri = format!("{COMPUTER_URI}{path}");
329 let method = reqwest::Method::from_bytes(method.as_bytes())?;
330 let mut request_builder = HTTP_CLIENT
331 .request(method.clone(), &uri)
332 .header(CONTENT_TYPE, "application/json");
333 if method != reqwest::Method::GET {
334 request_builder = request_builder.header(CONTENT_LENGTH, body.len());
335 }
336 let response = request_builder.body(body.to_vec()).send().await?;
337 let status = response.status();
338 let body = response.bytes().await?.to_vec();
339 if status.is_server_error() {
340 return Err(Error::Api(computer_http_error(status, &body)));
341 }
342 Ok((status, body))
343}
344
345fn parse_computer_response<T>(status: StatusCode, body: &[u8], label: &str) -> Result<T, Error>
346where
347 T: DeserializeOwned,
348{
349 let value = parse_computer_json(status, body, label)?;
350 if let Some(error) = computer_error_from_value(status, &value) {
351 return Err(Error::Api(error));
352 }
353 Ok(serde_json::from_value(value)?)
354}
355
356fn parse_computer_empty_response(status: StatusCode, body: &[u8]) -> Result<(), Error> {
357 if body.iter().all(|byte| byte.is_ascii_whitespace()) {
358 return if status.is_success() {
359 Ok(())
360 } else {
361 Err(Error::Api(computer_http_error(status, body)))
362 };
363 }
364 let value = parse_computer_json(status, body, "computer response")?;
365 if let Some(error) = computer_error_from_value(status, &value) {
366 return Err(Error::Api(error));
367 }
368 if status.is_success() {
369 Ok(())
370 } else {
371 Err(Error::Api(computer_http_error(status, body)))
372 }
373}
374
375fn parse_computer_json(
376 status: StatusCode,
377 body: &[u8],
378 label: &str,
379) -> Result<serde_json::Value, Error> {
380 if body.iter().all(|byte| byte.is_ascii_whitespace()) {
381 if status.is_success() {
382 return Err(Error::DataNotFound(label.to_string()));
383 }
384 return Err(Error::Api(computer_http_error(status, body)));
385 }
386 match serde_json::from_slice(body) {
387 Ok(value) => Ok(value),
388 Err(err) if status.is_success() => Err(Error::Json(err)),
389 Err(_) => Err(Error::Api(computer_http_error(status, body))),
390 }
391}
392
393fn computer_error_from_value(status: StatusCode, value: &serde_json::Value) -> Option<ApiError> {
394 if let Some(error_value) = value.get("error").filter(|value| !value.is_null()) {
395 if let Ok(mut error) = serde_json::from_value::<ApiError>(error_value.clone())
396 && has_api_error(&error)
397 {
398 if error.status == 0 {
399 error.status = status.as_u16() as i32;
400 }
401 return Some(error);
402 }
403 if let Some(description) = error_value.as_str() {
404 return Some(ApiError {
405 status: status.as_u16() as i32,
406 code: status.as_u16() as i32,
407 description: description.to_string(),
408 });
409 }
410 }
411
412 let code = value
413 .get("code")
414 .and_then(serde_json::Value::as_i64)
415 .unwrap_or_default() as i32;
416 let status_field = value
417 .get("status")
418 .and_then(serde_json::Value::as_i64)
419 .unwrap_or_default() as i32;
420 if code > 0 || status_field >= 400 || !status.is_success() {
421 let description = value
422 .get("description")
423 .or_else(|| value.get("message"))
424 .and_then(serde_json::Value::as_str)
425 .unwrap_or_else(|| status.canonical_reason().unwrap_or("Computer API error"))
426 .to_string();
427 return Some(ApiError {
428 status: if status_field > 0 {
429 status_field
430 } else {
431 status.as_u16() as i32
432 },
433 code: if code > 0 {
434 code
435 } else {
436 status.as_u16() as i32
437 },
438 description,
439 });
440 }
441 None
442}
443
444fn computer_http_error(status: StatusCode, body: &[u8]) -> ApiError {
445 if let Ok(value) = serde_json::from_slice::<serde_json::Value>(body)
446 && let Some(error) = computer_error_from_value(status, &value)
447 {
448 return error;
449 }
450 let description = String::from_utf8_lossy(body).trim().to_string();
451 ApiError {
452 status: status.as_u16() as i32,
453 code: status.as_u16() as i32,
454 description: if description.is_empty() {
455 status
456 .canonical_reason()
457 .unwrap_or("Computer API error")
458 .to_string()
459 } else {
460 description
461 },
462 }
463}
464
465fn has_api_error(error: &ApiError) -> bool {
466 error.code > 0 || error.status >= 400 || !error.description.is_empty()
467}
468
469fn is_not_found(error: &ApiError) -> bool {
470 error.code == 404 || error.status == 404
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476 use crate::safe::SafeUser;
477
478 #[test]
479 fn test_computer_user_id_to_bytes() {
480 assert_eq!(
481 computer_user_id_to_bytes("1").unwrap(),
482 [0, 0, 0, 0, 0, 0, 0, 1]
483 );
484 assert_eq!(
485 computer_user_id_to_bytes("18446744073709551615").unwrap(),
486 [255; 8]
487 );
488 assert!(computer_user_id_to_bytes("-1").is_err());
489 }
490
491 #[test]
492 fn test_build_system_call_extra() {
493 let extra = build_system_call_extra(
494 "1",
495 "00000000-0000-0000-0000-000000000002",
496 true,
497 Some("00000000-0000-0000-0000-000000000003"),
498 )
499 .unwrap();
500 assert_eq!(extra.len(), 41);
501 assert_eq!(&extra[..8], &[0, 0, 0, 0, 0, 0, 0, 1]);
502 assert_eq!(extra[24], 1);
503 }
504
505 #[test]
506 fn test_encode_decode_mtg_extra() {
507 let app_id = "00000000-0000-0000-0000-000000000001";
508 let memo = encode_operation_memo(OPERATION_TYPE_SYSTEM_CALL, &[1, 2, 3]);
509 let encoded = encode_mtg_extra(app_id, &memo).unwrap();
510 let (decoded_app_id, decoded_memo) = decode_computer_extra_base64(&encoded).unwrap();
511 assert_eq!(decoded_app_id, app_id);
512 assert_eq!(decoded_memo, memo);
513 }
514
515 #[test]
516 fn test_check_system_call_size() {
517 assert!(check_system_call_size(&vec![0; MAX_SOLANA_TX_SIZE]));
518 assert!(!check_system_call_size(&vec![0; MAX_SOLANA_TX_SIZE + 1]));
519 }
520
521 #[test]
522 fn test_deployed_asset_solana_asset_id() {
523 let asset = ComputerDeployedAsset {
524 address: "So11111111111111111111111111111111111111112".to_string(),
525 ..Default::default()
526 };
527 assert_eq!(
528 asset.solana_asset_id(),
529 unique_object_id([
530 SOLANA_CHAIN_ID,
531 "So11111111111111111111111111111111111111112"
532 ])
533 );
534 }
535
536 #[test]
537 fn test_register_preview_matches_go_layout() {
538 let safe_user = SafeUser {
539 user_id: "67a87828-18f5-46a1-b6cc-c72a97a77c43".to_string(),
540 session_id: "session-id".to_string(),
541 session_private_key: "session-private-key".to_string(),
542 server_public_key: "server-public-key".to_string(),
543 spend_private_key: "spend-private-key".to_string(),
544 is_spend_private_sum: false,
545 };
546 let info = ComputerInfo {
547 members: ComputerMembers {
548 app_id: "00000000-0000-0000-0000-000000000001".to_string(),
549 members: vec!["00000000-0000-0000-0000-000000000002".to_string()],
550 threshold: 1,
551 },
552 params: ComputerParams {
553 operation: ComputerOperationParams {
554 asset: "asset".to_string(),
555 price: "0.01".to_string(),
556 },
557 },
558 ..Default::default()
559 };
560
561 let preview = build_computer_register_preview(&info, &safe_user).unwrap();
562 let (app_id, memo) = decode_computer_extra_base64(&preview.mtg_extra).unwrap();
563 assert_eq!(app_id, info.members.app_id);
564 assert_eq!(memo[0], OPERATION_TYPE_ADD_USER);
565 assert_eq!(
566 String::from_utf8(memo[1..].to_vec()).unwrap(),
567 preview.mix_address
568 );
569 assert_eq!(
570 preview.trace_id,
571 unique_object_id([preview.mix_address.as_str(), "computer_register"])
572 );
573 }
574}