-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathsignatures.rs
More file actions
750 lines (652 loc) · 27.5 KB
/
Copy pathsignatures.rs
File metadata and controls
750 lines (652 loc) · 27.5 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! This module contains the logic for resolving signatures from
//! 4-byte function selector or a 32-byte event selector.
use std::path::PathBuf;
use alloy_dyn_abi::{DynSolType, DynSolValue};
use alloy_json_abi::JsonAbi;
use async_trait::async_trait;
use crate::{
ether::types::{dyn_sol_types_to_strings, inputs_to_abi_format, parse_function_parameters},
utils::{
http::get_json_from_url,
io::{logging::TraceFactory, types::display},
},
};
use eyre::{OptionExt, Result};
use heimdall_cache::{store_cache, with_cache};
use serde::{
ser::{SerializeMap, Serializer},
Deserialize, Serialize,
};
use tracing::{debug, trace};
use super::types::DynSolValueExt;
/// A resolved function signature. May contain decoded inputs.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct ResolvedFunction {
/// The name of the function. For example, `transfer`.
pub name: String,
/// The function signature. For example, `transfer(address,uint256)`.
pub signature: String,
/// The inputs of the function. For example, `["address", "uint256"]`.
pub inputs: Vec<String>,
/// The decoded inputs of the function. For example, `[DynSolValue::Address("0x1234"),
/// DynSolValue::Uint(123)]`.
#[serde(skip)]
pub decoded_inputs: Option<Vec<DynSolValue>>,
}
impl ResolvedFunction {
/// Returns the inputs of the function as a vector of [`DynSolType`]s.
pub fn inputs(&self) -> Vec<DynSolType> {
parse_function_parameters(&self.signature).expect("invalid signature")
}
/// A helper function to convert the struct into a JSON string.
/// We use this because `decoded_inputs` cannot be serialized by serde.
pub fn to_json(&self) -> Result<String> {
Ok(format!(
r#"{{
"name": "{}",
"signature": "{}",
"inputs": {},
"decoded_inputs": [{}]
}}"#,
&self.name,
&self.signature,
serde_json::to_string(&inputs_to_abi_format(&self.inputs))?,
if let Some(decoded_inputs) = &self.decoded_inputs {
decoded_inputs
.iter()
.map(|input| input.serialize().to_string())
.collect::<Vec<String>>()
.join(", ")
} else {
"".to_string()
}
))
}
}
impl Serialize for ResolvedFunction {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer, {
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("name", &self.name)?;
map.serialize_entry("signature", &self.signature)?;
map.serialize_entry("inputs", &inputs_to_abi_format(&self.inputs))?;
// Skip decoded_inputs since it's marked with #[serde(skip)]
map.end()
}
}
/// A resolved error signature.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ResolvedError {
/// The name of the error. For example, `revert`.
pub name: String,
/// The error signature. For example, `revert(string)`.
pub signature: String,
/// The inputs of the error. For example, `["string"]`.
pub inputs: Vec<String>,
}
impl ResolvedError {
/// Returns the inputs of the error as a vector of [`DynSolType`]s.
pub fn inputs(&self) -> Vec<DynSolType> {
parse_function_parameters(&self.signature).expect("invalid signature")
}
}
impl Serialize for ResolvedError {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer, {
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("name", &self.name)?;
map.serialize_entry("signature", &self.signature)?;
map.serialize_entry("inputs", &inputs_to_abi_format(&self.inputs))?;
map.end()
}
}
/// A resolved log signature.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct ResolvedLog {
/// The name of the log. For example, `Transfer`.
pub name: String,
/// The log signature. For example, `Transfer(address,address,uint256)`.
pub signature: String,
/// The inputs of the log. For example, `["address", "address", "uint256"]`.
pub inputs: Vec<String>,
}
impl ResolvedLog {
/// Returns the inputs of the log as a vector of [`DynSolType`]s.
pub fn inputs(&self) -> Vec<DynSolType> {
parse_function_parameters(&self.signature).expect("invalid signature")
}
}
impl Serialize for ResolvedLog {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer, {
let mut map = serializer.serialize_map(Some(3))?;
map.serialize_entry("name", &self.name)?;
map.serialize_entry("signature", &self.signature)?;
map.serialize_entry("inputs", &inputs_to_abi_format(&self.inputs))?;
map.end()
}
}
/// A trait for resolving a selector into a vector of [`ResolvedFunction`]s, [`ResolvedError`]s, or
#[async_trait]
pub trait ResolveSelector {
/// Resolves a selector into a vector of [`ResolvedFunction`]s, [`ResolvedError`]s, or
/// [`ResolvedLog`]s.
async fn resolve(selector: &str) -> Result<Option<Vec<Self>>>
where
Self: Sized;
}
#[async_trait]
impl ResolveSelector for ResolvedError {
async fn resolve(selector: &str) -> Result<Option<Vec<Self>>> {
with_cache(&format!("selector.{selector}"), || async {
// normalize selector
let selector = match selector.strip_prefix("0x") {
Some(selector) => selector,
None => selector,
};
trace!("resolving error selector {}", &selector);
// get function possibilities from openchain
let signatures = match get_json_from_url(
&format!(
"https://api.openchain.xyz/signature-database/v1/lookup?filter=false&function=0x{}",
&selector
),
10,
)
.await?
{
Some(signatures) => signatures,
None => return Ok(None),
};
// convert the serde value into a vec of possible functions
let results = signatures
.get("result")
.and_then(|result| result.get("function"))
.and_then(|function| function.get(format!("0x{selector}")))
.and_then(|item| item.as_array())
.map(|array| array.to_vec())
.ok_or_eyre("error parsing signatures from openchain")?;
trace!("found {} possible functions for selector: {}", &results.len(), &selector);
let mut signature_list: Vec<ResolvedError> = Vec::new();
for signature in results {
// get the function text signature and unwrap it into a string
let text_signature = match signature.get("name") {
Some(text_signature) => text_signature.to_string().replace('"', ""),
None => continue,
};
// safely split the text signature into name and inputs
let function_parts = match text_signature.split_once('(') {
Some(function_parts) => function_parts,
None => continue,
};
// Parse the inputs using parse_function_parameters
let parsed_inputs = match parse_function_parameters(&text_signature) {
Ok(inputs) => inputs,
Err(_) => continue,
};
signature_list.push(ResolvedError {
name: function_parts.0.to_string(),
signature: text_signature.to_string(),
inputs: dyn_sol_types_to_strings(&parsed_inputs),
});
}
Ok(match signature_list.len() {
0 => None,
_ => Some(signature_list),
})
})
.await
}
}
#[async_trait]
impl ResolveSelector for ResolvedLog {
async fn resolve(selector: &str) -> Result<Option<Vec<Self>>> {
with_cache(&format!("selector.{selector}"), || async {
// normalize selector
let selector = match selector.strip_prefix("0x") {
Some(selector) => selector,
None => selector,
};
trace!("resolving event selector {}", &selector);
// get function possibilities from openchain
let signatures = match get_json_from_url(
&format!(
"https://api.openchain.xyz/signature-database/v1/lookup?filter=false&event=0x{}",
&selector
),
10,
)
.await?
{
Some(signatures) => signatures,
None => return Ok(None),
};
// convert the serde value into a vec of possible functions
let results = signatures
.get("result")
.and_then(|result| result.get("event"))
.and_then(|function| function.get(format!("0x{selector}")))
.and_then(|item| item.as_array())
.map(|array| array.to_vec())
.ok_or_eyre("error parsing signatures from openchain")?;
trace!("found {} possible functions for selector: {}", &results.len(), &selector);
let mut signature_list: Vec<ResolvedLog> = Vec::new();
for signature in results {
// get the function text signature and unwrap it into a string
let text_signature = match signature.get("name") {
Some(text_signature) => text_signature.to_string().replace('"', ""),
None => continue,
};
// safely split the text signature into name and inputs
let function_parts = match text_signature.split_once('(') {
Some(function_parts) => function_parts,
None => continue,
};
// Parse the inputs using parse_function_parameters
let parsed_inputs = match parse_function_parameters(&text_signature) {
Ok(inputs) => inputs,
Err(_) => continue,
};
signature_list.push(ResolvedLog {
name: function_parts.0.to_string(),
signature: text_signature.to_string(),
inputs: dyn_sol_types_to_strings(&parsed_inputs),
});
}
Ok(match signature_list.len() {
0 => None,
_ => Some(signature_list),
})
})
.await
}
}
#[async_trait]
impl ResolveSelector for ResolvedFunction {
async fn resolve(selector: &str) -> Result<Option<Vec<Self>>> {
with_cache(&format!("selector.{selector}"), || async {
// normalize selector
let selector = match selector.strip_prefix("0x") {
Some(selector) => selector,
None => selector,
};
trace!("resolving function selector {}", &selector);
// get function possibilities from openchain
let signatures = match get_json_from_url(
&format!(
"https://api.openchain.xyz/signature-database/v1/lookup?filter=false&function=0x{}",
&selector
),
10,
)
.await?
{
Some(signatures) => signatures,
None => return Ok(None),
};
// convert the serde value into a vec of possible functions
let results = signatures
.get("result")
.and_then(|result| result.get("function"))
.and_then(|function| function.get(format!("0x{selector}")))
.and_then(|item| item.as_array())
.map(|array| array.to_vec())
.ok_or_eyre("error parsing signatures from openchain")?;
trace!("found {} possible functions for selector: {}", &results.len(), &selector);
let mut signature_list: Vec<ResolvedFunction> = Vec::new();
for signature in results {
// get the function text signature and unwrap it into a string
let text_signature = match signature.get("name") {
Some(text_signature) => text_signature.to_string().replace('"', ""),
None => continue,
};
// safely split the text signature into name and inputs
let function_parts = match text_signature.split_once('(') {
Some(function_parts) => function_parts,
None => continue,
};
// Parse the inputs using parse_function_parameters
let parsed_inputs = match parse_function_parameters(&text_signature) {
Ok(inputs) => inputs,
Err(_) => continue,
};
signature_list.push(ResolvedFunction {
name: function_parts.0.to_string(),
signature: text_signature.to_string(),
inputs: dyn_sol_types_to_strings(&parsed_inputs),
decoded_inputs: None,
});
}
Ok(match signature_list.len() {
0 => None,
_ => Some(signature_list),
})
})
.await
}
}
/// Given the path to an ABI file, parses all [`ResolvedFunction`]s, [`ResolvedError`]s, and
/// [`ResolvedLog`]s from the ABI and saves them to the cache.
pub fn cache_signatures_from_abi(path: PathBuf) -> Result<()> {
let abi = std::fs::read_to_string(&path)?;
let json_abi = JsonAbi::from_json_str(&abi)?;
debug!("caching signatures from abi: {}", path.display());
json_abi.functions().for_each(|function| {
let selector = function.selector().to_string().trim_start_matches("0x").to_string();
let signature = function.signature();
// Parse inputs using parse_function_parameters for consistency
let inputs = match parse_function_parameters(&signature) {
Ok(parsed) => dyn_sol_types_to_strings(&parsed),
Err(_) => {
// Fallback to original method if parsing fails
function.inputs.iter().map(|input| input.ty.clone()).collect()
}
};
let resolved_function = ResolvedFunction {
name: function.name.clone(),
signature,
inputs,
decoded_inputs: None,
};
store_cache(&format!("selector.{selector}"), Some(vec![resolved_function]), None).ok();
});
json_abi.events().for_each(|event| {
let selector = event.selector().to_string().trim_start_matches("0x").to_string();
let signature = event.signature();
// Parse inputs using parse_function_parameters for consistency
let inputs = match parse_function_parameters(&signature) {
Ok(parsed) => dyn_sol_types_to_strings(&parsed),
Err(_) => {
// Fallback to original method if parsing fails
event.inputs.iter().map(|input| input.ty.clone()).collect()
}
};
let resolved_log = ResolvedLog { name: event.name.clone(), signature, inputs };
store_cache(&format!("selector.{selector}"), Some(vec![resolved_log]), None).ok();
});
json_abi.errors().for_each(|error| {
let selector = error.selector().to_string().trim_start_matches("0x").to_string();
let signature = error.signature();
// Parse inputs using parse_function_parameters for consistency
let inputs = match parse_function_parameters(&signature) {
Ok(parsed) => dyn_sol_types_to_strings(&parsed),
Err(_) => {
// Fallback to original method if parsing fails
error.inputs.iter().map(|input| input.ty.clone()).collect()
}
};
let resolved_error = ResolvedError { name: error.name.clone(), signature, inputs };
store_cache(&format!("selector.{selector}"), Some(vec![resolved_error]), None).ok();
});
debug!(
"cached {} functions, {} logs, and {} errors from provided abi",
json_abi.functions().count(),
json_abi.events().count(),
json_abi.errors().count(),
);
Ok(())
}
/// Heuristic to score a function signature based on its spamminess.
pub fn score_signature(signature: &str, num_words: Option<usize>) -> u32 {
// the score starts at 1000
let mut score = 1000;
// remove the length of the signature from the score
// this will prioritize shorter signatures, which are typically less spammy
score -= signature.len() as u32;
// prioritize signatures with less numbers
score -= (signature.split('(').next().unwrap_or("").matches(|c: char| c.is_numeric()).count()
as u32) *
3;
// prioritize signatures with parameters
let num_params = signature.matches(',').count() + 1;
score += num_params as u32 * 10;
// count the number of parameters in the signature, if enabled
if let Some(num_words) = num_words {
let num_dyn_params = signature.matches("bytes").count() +
signature.matches("string").count() +
signature.matches('[').count();
let num_static_params = num_params.saturating_sub(num_dyn_params);
// reduce the score if the signature has less static parameters than there are words in the
// calldata
if num_static_params < num_words {
score = score.saturating_sub((num_words.saturating_sub(num_static_params)) as u32 * 10);
}
}
score
}
/// trait impls
/// trait impls
/// trait impls
impl TryFrom<&ResolvedFunction> for TraceFactory {
// eyre
type Error = eyre::Report;
fn try_from(function: &ResolvedFunction) -> Result<Self, Self::Error> {
let mut trace = TraceFactory::default();
let decode_call = trace.add_call(
0,
line!(),
"heimdall".to_string(),
"decode".to_string(),
vec![],
"()".to_string(),
);
trace.br(decode_call);
trace.add_message(decode_call, line!(), vec![format!("signature: {}", function.signature)]);
trace.br(decode_call);
// build inputs
for (i, input) in function.decoded_inputs.as_ref().unwrap_or(&Vec::new()).iter().enumerate()
{
let mut decoded_inputs_as_message = display(vec![input.to_owned()], " ");
if decoded_inputs_as_message.is_empty() {
break;
}
if i == 0 {
decoded_inputs_as_message[0] = format!(
"input {}:{}{}",
i,
" ".repeat(4 - i.to_string().len()),
decoded_inputs_as_message[0].replacen(" ", "", 1)
)
} else {
decoded_inputs_as_message[0] = format!(
" {}:{}{}",
i,
" ".repeat(4 - i.to_string().len()),
decoded_inputs_as_message[0].replacen(" ", "", 1)
)
}
// add to trace and decoded string
trace.add_message(decode_call, 1, decoded_inputs_as_message);
}
Ok(trace)
}
}
/// tests
/// tests
/// tests
#[cfg(test)]
mod tests {
use heimdall_cache::delete_cache;
use crate::ether::{
signatures::{
dyn_sol_types_to_strings, score_signature, ResolveSelector, ResolvedError,
ResolvedFunction, ResolvedLog,
},
types::parse_function_parameters,
};
#[tokio::test]
async fn resolve_function_signature_nominal() {
let signature = String::from("095ea7b3");
let _ = delete_cache(&format!("selector.{}", &signature));
let result = ResolvedFunction::resolve(&signature)
.await
.expect("failed to resolve signature")
.expect("failed to resolve signature");
assert!(!result.is_empty());
}
#[tokio::test]
async fn resolve_multicall_signature() {
let signature = String::from("1749e1e3");
let _ = delete_cache(&format!("selector.{}", &signature));
let result = ResolvedFunction::resolve(&signature)
.await
.expect("failed to resolve signature")
.expect("failed to resolve signature");
// Find the multicall function
let multicall = result.iter().find(|f| f.name == "multicall");
assert!(multicall.is_some(), "multicall function not found");
let multicall = multicall.unwrap();
// The inputs should be ["tuple[]"] not ["(address", "uint256", "bytes)[]"]
assert_eq!(multicall.inputs, vec!["tuple[]"]);
}
#[tokio::test]
async fn resolve_error_signature_nominal() {
let signature = String::from("30cd7471");
let _ = delete_cache(&format!("selector.{}", &signature));
let result = ResolvedError::resolve(&signature)
.await
.expect("failed to resolve signature")
.expect("failed to resolve signature");
assert!(!result.is_empty());
}
#[tokio::test]
async fn resolve_event_signature_nominal() {
let signature =
String::from("ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef");
let _ = delete_cache(&format!("selector.{}", &signature));
let result = ResolvedLog::resolve(&signature)
.await
.expect("failed to resolve signature")
.expect("failed to resolve signature");
assert!(!result.is_empty());
}
#[tokio::test]
async fn resolve_function_signature_should_return_none_when_cached_results_not_found() {
let signature = String::from("test_signature_nocache");
let result = ResolvedFunction::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_function_signature_should_return_none_when_json_url_returns_empty_signatures()
{
let _ = delete_cache(&format!("selector.{}", "test_signature"));
let signature = String::from("test_signature");
let result = ResolvedFunction::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_error_signature_should_return_none_when_cached_results_not_found() {
let signature = String::from("test_signature_notfound");
let result = ResolvedError::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_error_signature_should_return_none_when_json_url_returns_none() {
let signature = String::from("test_signature_notfound");
let result = ResolvedError::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_error_signature_should_return_none_when_json_url_returns_empty_signatures() {
let signature = String::from("test_signature_notfound");
let result = ResolvedError::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_event_signature_should_return_none_when_cached_results_not_found() {
let signature = String::from("test_signature_notfound");
let result = ResolvedLog::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_event_signature_should_return_none_when_json_url_returns_none() {
let signature = String::from("test_signature_notfound");
let result = ResolvedLog::resolve(&signature).await;
assert!(result.is_err());
}
#[tokio::test]
async fn resolve_event_signature_should_return_none_when_json_url_returns_empty_signatures() {
let signature = String::from("test_signature_notfound");
let result = ResolvedLog::resolve(&signature).await;
assert!(result.is_err());
}
#[test]
fn score_signature_should_return_correct_score() {
let signature = String::from("test_signature");
let score = score_signature(&signature, None);
assert_eq!(score, 996);
}
#[test]
fn test_complex_signature_parsing() {
// Test that we correctly parse complex signatures with nested tuples
let test_cases = vec![
("function((uint256,address)[])", vec!["tuple[]"]),
("function(address,(uint256,uint256))", vec!["address", "tuple"]),
(
"function(uint256[],bytes32,(address,uint256)[])",
vec!["uint256[]", "bytes32", "tuple[]"],
),
(
// This is the problematic multicall signature
"multicall((address,uint256,bytes)[])",
vec!["tuple[]"],
),
(
// More complex nested structures
"function((address,uint256,bytes)[],(uint256,bool))",
vec!["tuple[]", "tuple"],
),
];
for (signature, expected_inputs) in test_cases {
let parsed = parse_function_parameters(signature).unwrap();
let string_inputs = dyn_sol_types_to_strings(&parsed);
assert_eq!(string_inputs, expected_inputs, "Failed for signature: {}", signature);
}
}
#[test]
fn test_score_signature_handles_overflow_in_num_static_params() {
// Test case where num_dyn_params > num_params, which would cause underflow
// This signature has more dynamic param matches than actual params (due to counting)
let signature = "bytes(bytes[])"; // 1 param, but matches "bytes" twice and has 1 bracket
// num_params = 1, num_dyn_params = 2 + 1 = 3
// Without saturating_sub: 1 - 3 would underflow
// With saturating_sub: 1.saturating_sub(3) = 0
let score = score_signature(signature, Some(0));
// Should not panic, should return a valid score (greater than 0)
assert!(score > 0);
}
#[test]
fn test_score_signature_handles_overflow_in_score_reduction() {
// Test case where num_words > num_static_params
let signature = "func()"; // 1 param (count from commas + 1), 0 dynamic params
// num_params = 1, num_dyn_params = 0, num_static_params = 1
// If num_words = 10, then num_words - num_static_params = 9
// This would reduce score by 90
let score = score_signature(signature, Some(10));
// Should not panic and should be reduced appropriately
// Initial score calculation:
// - Start: 1000
// - signature length (6): 994
// - no numbers in name: 994
// - 1 param: 1004
// - penalty for num_words (10) > num_static_params (1): 1004 - 90 = 914
assert_eq!(score, 914);
}
#[test]
fn test_score_signature_saturating_sub_prevents_underflow() {
// Test case where dynamic params exceed total params
// This signature has "bytes" and "string" keywords plus array brackets
let signature = "bytes(bytes,string,bytes[])";
// num_params = 3 (counting commas + 1)
// num_dyn_params = bytes(3) + string(1) + [(1) = 5
// Without saturating_sub: 3 - 5 would underflow
// With saturating_sub: 3.saturating_sub(5) = 0
let score = score_signature(signature, Some(2));
// Should not panic and should return a valid score
// The score should be positive since we add 10 per param
assert!(score > 0);
}
}