forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsui.rs
More file actions
435 lines (393 loc) · 16.4 KB
/
Copy pathsui.rs
File metadata and controls
435 lines (393 loc) · 16.4 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use crate::chains::traits::ChainAdapter;
use crate::chains::validation::validate_sui_address;
use crate::cli::parser::Network;
use anyhow::{Context, Result, anyhow};
use async_trait::async_trait;
use regex::Regex;
use reqwest::Client;
use serde_json::{Value, json};
use std::sync::LazyLock;
/// Matches a candidate SuiNS token (`<label>.sui`). The regex itself is
/// intentionally *not* anchored on the right — the `regex` crate has no
/// lookahead — so `resolve_names_in_value` performs a post-match boundary
/// check: a match is only treated as a SuiNS name when the character
/// immediately following it is absent or is not in `[A-Za-z0-9.-]`. This
/// rejects `alice.sui2` and `alice.sui.evil.com` while still accepting
/// `alice.sui` anywhere it appears as a complete token.
static SUINS_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"[a-zA-Z0-9-]+\.sui").expect("valid literal regex"));
/// Returns `true` when the character at byte position `end` in `s` is a
/// name-continuation character (`[A-Za-z0-9.-]`), meaning the regex match
/// ending there is part of a longer token and should **not** be treated as a
/// SuiNS name.
fn is_name_continuation(s: &str, end: usize) -> bool {
s[end..]
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
}
pub struct SuiAdapter {
client: Client,
rpc_url: String,
}
impl SuiAdapter {
#[allow(dead_code)]
pub fn new() -> Self {
Self::with_rpc(None, Network::Mainnet)
}
pub fn with_rpc(rpc_url: Option<String>, network: Network) -> Self {
let url = rpc_url.unwrap_or_else(|| match network {
Network::Mainnet => "https://fullnode.mainnet.sui.io".to_string(),
Network::Testnet => "https://fullnode.testnet.sui.io".to_string(),
Network::Devnet => "https://fullnode.devnet.sui.io".to_string(),
Network::Localnet => "http://127.0.0.1:9000".to_string(),
});
Self {
client: Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.unwrap_or_else(|_| Client::new()),
rpc_url: url,
}
}
async fn call_rpc_internal(&self, method: &str, params: Value) -> Result<Value> {
let payload = json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params
});
let response = self
.client
.post(&self.rpc_url)
.json(&payload)
.send()
.await?;
let body: Value = response.json().await?;
if let Some(error) = body.get("error") {
let msg = error
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("Unknown RPC Error");
let data = error.get("data").and_then(|d| d.as_str()).unwrap_or("");
let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(0);
let err_str = if data.is_empty() {
format!("{msg} (Code: {code})")
} else {
format!("{msg} - {data} (Code: {code})")
};
return Err(anyhow!("{err_str}"));
}
Ok(body.get("result").cloned().unwrap_or(Value::Null))
}
async fn resolve_names_in_value(&self, value: &mut Value) -> Result<()> {
match value {
Value::String(s) => {
// Collect boundary-validated match spans. Tracking spans (not
// just name strings) lets us rebuild the output by substituting
// only the exact regex-matched positions, which prevents the
// String::replace bug where replacing "alice.sui" also rewrites
// the prefix inside "alice.sui2".
let spans: Vec<(usize, usize, String)> = SUINS_REGEX
.find_iter(s)
.filter(|m| !is_name_continuation(s, m.end()))
.map(|m| (m.start(), m.end(), m.as_str().to_string()))
.collect();
if !spans.is_empty() {
// Resolve each unique name exactly once (dedup for RPC
// efficiency — a name that appears multiple times in the
// same string value should only trigger one resolution call).
let mut name_to_addr: std::collections::HashMap<String, Option<String>> =
std::collections::HashMap::new();
for (_, _, name) in &spans {
if !name_to_addr.contains_key(name) {
let addr = self
.resolve_name(name)
.await
.with_context(|| format!("resolving Sui name {name}"))?;
name_to_addr.insert(name.clone(), addr);
}
}
// Rebuild the string from validated span positions only,
// leaving any non-matched content (including longer names
// like alice.sui2) completely unchanged.
let original = s.clone();
let mut new_string = String::with_capacity(original.len());
let mut last_end = 0usize;
for (start, end, name) in spans {
new_string.push_str(&original[last_end..start]);
match name_to_addr.get(&name) {
Some(Some(addr)) => new_string.push_str(addr),
_ => new_string.push_str(&original[start..end]),
}
last_end = end;
}
new_string.push_str(&original[last_end..]);
*s = new_string;
}
}
Value::Array(arr) => {
for v in arr.iter_mut() {
Box::pin(self.resolve_names_in_value(v)).await?;
}
}
Value::Object(map) => {
for v in map.values_mut() {
Box::pin(self.resolve_names_in_value(v)).await?;
}
}
_ => {}
}
Ok(())
}
}
#[async_trait]
impl ChainAdapter for SuiAdapter {
fn name(&self) -> &'static str {
"Sui"
}
fn default_rpc(&self) -> &'static str {
"https://fullnode.mainnet.sui.io"
}
async fn call_rpc(&self, method: &str, mut params: Value) -> Result<Value> {
self.resolve_names_in_value(&mut params).await?;
self.call_rpc_internal(method, params).await
}
async fn resolve_name(&self, name: &str) -> Result<Option<String>> {
if !name.ends_with(".sui") {
return Ok(None);
}
let params = json!([name]);
let result = self
.call_rpc_internal("suix_resolveNameServiceAddress", params)
.await?;
Ok(result.as_str().map(|s| s.to_string()))
}
async fn get_balance(&self, address: &str) -> Result<Value> {
let address = validate_sui_address(address)?;
let params = json!([address]);
self.call_rpc("suix_getAllBalances", params).await
}
async fn get_transaction(&self, hash: &str) -> Result<Value> {
let params = json!([
hash,
{
"showInput": true,
"showEffects": true,
"showEvents": true,
"showObjectChanges": true,
"showBalanceChanges": true
}
]);
self.call_rpc_internal("sui_getTransactionBlock", params)
.await
}
async fn get_block(&self, block: Option<u64>) -> Result<Value> {
if let Some(seq) = block {
let params = json!([seq.to_string()]);
self.call_rpc_internal("sui_getCheckpoint", params).await
} else {
let seq = self
.call_rpc_internal("sui_getLatestCheckpointSequenceNumber", json!([]))
.await?;
let params = json!([seq]);
self.call_rpc_internal("sui_getCheckpoint", params).await
}
}
async fn get_gas_price(&self) -> Result<Value> {
self.call_rpc_internal("suix_getReferenceGasPrice", json!([]))
.await
}
async fn get_account(&self, id: &str) -> Result<Value> {
let params = json!([
id,
{ "showType": true, "showContent": true, "showOwner": true, "showDisplay": true }
]);
self.call_rpc_internal("sui_getObject", params).await
}
async fn get_history(&self, address: &str, limit: u32) -> Result<Value> {
let address = validate_sui_address(address)?;
let params = json!([
{
"filter": { "FromAddress": address },
"options": { "showInput": true, "showEffects": true }
},
null,
limit,
true
]);
self.call_rpc_internal("suix_queryTransactionBlocks", params)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn suins_regex_matches_name_inside_string() {
assert!(SUINS_REGEX.is_match("send 5 SUI to alice.sui now"));
let matches: Vec<&str> = SUINS_REGEX
.find_iter("move alice.sui to bob.sui")
.map(|m| m.as_str())
.collect();
assert_eq!(matches, vec!["alice.sui", "bob.sui"]);
}
#[test]
fn suins_regex_ignores_non_matching_strings() {
assert!(!SUINS_REGEX.is_match("plain string"));
assert!(!SUINS_REGEX.is_match("no-dot-sui"));
assert!(!SUINS_REGEX.is_match("alice.SUI"));
assert!(!SUINS_REGEX.is_match("0x1234abcd"));
}
/// The regex itself still finds a candidate inside `alice.sui2` and
/// `alice.sui.evil.com`; the boundary helper must reject both.
#[test]
fn boundary_check_rejects_longer_tokens() {
// alice.sui2 — digit follows immediately
let s = "alice.sui2";
let m = SUINS_REGEX.find(s).expect("regex matches the .sui prefix");
assert!(
is_name_continuation(s, m.end()),
"alice.sui2 should be flagged as a longer token"
);
// alice.sui.evil.com — dot follows immediately
let s2 = "alice.sui.evil.com";
let m2 = SUINS_REGEX.find(s2).expect("regex matches the .sui prefix");
assert!(
is_name_continuation(s2, m2.end()),
"alice.sui.evil.com should be flagged as a longer token"
);
}
/// A clean `alice.sui` at end-of-string or followed by whitespace must
/// pass the boundary check.
#[test]
fn boundary_check_accepts_clean_sui_names() {
let s = "alice.sui";
let m = SUINS_REGEX.find(s).expect("regex matches");
assert!(
!is_name_continuation(s, m.end()),
"alice.sui at end-of-string should not be a continuation"
);
let s2 = "send to alice.sui please";
let m2 = SUINS_REGEX.find(s2).expect("regex matches");
assert!(
!is_name_continuation(s2, m2.end()),
"alice.sui followed by space should not be a continuation"
);
}
#[tokio::test]
async fn resolution_error_propagates_with_name_context() {
// Port 1 refuses connections, so the resolver RPC fails. The error must
// surface (not be swallowed by the array/object recursion arms) and must
// name the SuiNS name that failed to resolve.
let adapter =
SuiAdapter::with_rpc(Some("http://127.0.0.1:1".to_string()), Network::Localnet);
let err = adapter
.call_rpc("suix_getAllBalances", json!([{ "address": "hello.sui" }]))
.await
.expect_err("resolution failure must propagate");
assert!(
err.to_string().contains("resolving Sui name hello.sui"),
"unexpected error: {err:#}"
);
}
#[tokio::test]
async fn unresolvable_name_is_left_as_literal() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
// Minimal mock JSON-RPC server. First request is the SuiNS lookup and
// answers `result: null` (name has no record => Ok(None)); the second is
// the real method call, whose params must still carry the literal name.
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let bodies = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let recorded = bodies.clone();
let server = tokio::spawn(async move {
for _ in 0..2 {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buf = vec![0u8; 8192];
let n = socket.read(&mut buf).await.unwrap();
let request = String::from_utf8_lossy(&buf[..n]).to_string();
recorded.lock().unwrap().push(request.clone());
let result = if request.contains("suix_resolveNameServiceAddress") {
"null"
} else {
"\"ok\""
};
let body = format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{result}}}");
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
}
});
let adapter = SuiAdapter::with_rpc(Some(format!("http://{addr}")), Network::Localnet);
let result = adapter
.call_rpc("suix_getAllBalances", json!(["unknown.sui"]))
.await
.unwrap();
assert_eq!(result, json!("ok"));
server.await.unwrap();
let bodies = bodies.lock().unwrap();
assert_eq!(bodies.len(), 2);
assert!(bodies[0].contains("suix_resolveNameServiceAddress"));
assert!(
bodies[1].contains("unknown.sui"),
"literal .sui name must stay in params: {}",
bodies[1]
);
}
/// A string containing the same SuiNS name twice must only trigger a
/// single resolution RPC (the memo/dedup path).
#[tokio::test]
async fn duplicate_name_triggers_single_resolution_rpc() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let resolve_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = resolve_count.clone();
let server = tokio::spawn(async move {
// Accept exactly two requests: one resolve call and one final RPC call.
for _ in 0..2 {
let Ok((mut socket, _)) = listener.accept().await else {
break;
};
let mut buf = vec![0u8; 8192];
let Ok(n) = socket.read(&mut buf).await else {
break;
};
let request = String::from_utf8_lossy(&buf[..n]).to_string();
let (result, is_resolve) = if request.contains("suix_resolveNameServiceAddress") {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
("\"0xdeadbeef\"", true)
} else {
("\"ok\"", false)
};
let _ = is_resolve;
let body = format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{result}}}");
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = socket.write_all(response.as_bytes()).await;
}
});
let adapter = SuiAdapter::with_rpc(Some(format!("http://{addr}")), Network::Localnet);
// alice.sui appears twice in the same string value.
let result = adapter
.call_rpc("suix_getAllBalances", json!(["alice.sui and alice.sui"]))
.await
.unwrap();
assert_eq!(result, json!("ok"));
server.await.unwrap();
assert_eq!(
resolve_count.load(std::sync::atomic::Ordering::SeqCst),
1,
"duplicate name must resolve exactly once"
);
}
}