Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: audit #174

Merged
merged 5 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/e2e-move-tests/src/tests/move_unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ use initia_move_types::metadata;

use move_cli::base::test::{run_move_unit_tests_with_factory, UnitTestResult};
use move_core_types::effects::ChangeSet;
use move_model::metadata::{CompilerVersion, LanguageVersion};
use move_unit_test::UnitTestingConfig;
use move_vm_runtime::native_extensions::NativeContextExtensions;
use move_model::metadata::{CompilerVersion, LanguageVersion};

use once_cell::sync::Lazy;
use std::path::PathBuf;
Expand Down
2 changes: 1 addition & 1 deletion crates/natives/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ fn native_test_only_set_block_info(
let height = safely_pop_arg!(arguments, u64);

let block_context = context.extensions_mut().get_mut::<NativeBlockContext>();
NativeBlockContext::set_block_info(block_context, height, timestamp);
block_context.set_block_info(height, timestamp);

Ok(smallvec![])
}
Expand Down
63 changes: 44 additions & 19 deletions crates/storage/src/module_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,18 @@ impl WithHash for BytesWithHash {
pub struct NoVersion;

pub struct InitiaModuleCache {
pub capacity: usize,
#[allow(clippy::type_complexity)]
pub(crate) module_cache: Mutex<CLruCache<Checksum, ModuleWrapper, RandomState, ModuleScale>>,
}

impl InitiaModuleCache {
pub fn new(cache_capacity: usize) -> Arc<InitiaModuleCache> {
let capacity = NonZeroUsize::new(cache_capacity * 1024 * 1024).unwrap();
let capacity = cache_capacity * 1024 * 1024;
Arc::new(InitiaModuleCache {
capacity,
module_cache: Mutex::new(CLruCache::with_config(
CLruCacheConfig::new(capacity).with_scale(ModuleScale),
CLruCacheConfig::new(NonZeroUsize::new(capacity).unwrap()).with_scale(ModuleScale),
)),
})
}
Expand All @@ -77,6 +79,16 @@ impl InitiaModuleCache {
extension: Arc<BytesWithHash>,
version: NoVersion,
) -> VMResult<()> {
// cache is too small to hold this module
if self.capacity < allocated_size {
beer-1 marked this conversation as resolved.
Show resolved Hide resolved
eprintln!(
"Module cache is too small to hold module with size {}",
allocated_size
);

return Ok(());
}

let mut module_cache = self.module_cache.lock();

match module_cache.get(&key) {
Expand All @@ -89,12 +101,12 @@ impl InitiaModuleCache {
extension,
version,
));

// NOTE: We are not handling the error here, because we are sure that the
// allocated size is less than the capacity.
module_cache
.put_with_weight(key, ModuleWrapper::new(module, allocated_size))
.unwrap_or_else(|_| {
eprintln!("WARNING: failed to insert module {:?} into cache; cache capacity might be too small", module_id.short_str_lossless().to_string());
None
});
.unwrap_or_else(|_| None);
Ok(())
}
}
Expand All @@ -114,14 +126,20 @@ impl InitiaModuleCache {
Ok(module_wrapper.module_code.clone())
}
_ => {
let module_id = verified_code.self_id();
let module = Arc::new(ModuleCode::from_verified(verified_code, extension, version));
module_cache
.put_with_weight(key, ModuleWrapper::new(module.clone(), allocated_size))
.unwrap_or_else(|_| {
eprintln!("WARNING: failed to insert module {:?} into cache; cache capacity might be too small", module_id.short_str_lossless().to_string());
None
});
if self.capacity >= allocated_size {
// NOTE: We are not handling the error here, because we are sure that the
// allocated size is less than the capacity.
module_cache
.put_with_weight(key, ModuleWrapper::new(module.clone(), allocated_size))
.unwrap_or_else(|_| None);
} else {
eprintln!(
"Module cache is too small to hold module with size {}",
allocated_size
);
}

Ok(module)
}
}
Expand Down Expand Up @@ -156,12 +174,19 @@ impl InitiaModuleCache {
}

let code_wrapper = ModuleWrapper::new(Arc::new(code), allocated_size);
module_cache
.put_with_weight(*checksum, code_wrapper.clone())
.unwrap_or_else(|_| {
eprintln!("WARNING: failed to insert module {:?} into cache; cache capacity might be too small", id.short_str_lossless().to_string());
None
});
if self.capacity >= allocated_size {
// NOTE: We are not handling the error here, because we are sure that the
// allocated size is less than the capacity.
module_cache
.put_with_weight(*checksum, code_wrapper.clone())
.unwrap_or_else(|_| None);
} else {
eprintln!(
"Module cache is too small to hold module with size {}",
allocated_size
);
}

Some(code_wrapper)
}
None => None,
Expand Down
43 changes: 28 additions & 15 deletions crates/storage/src/script_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ use crate::{
};

pub struct InitiaScriptCache {
pub capacity: usize,
pub(crate) script_cache: Mutex<CLruCache<Checksum, ScriptWrapper, RandomState, ScriptScale>>,
}

impl InitiaScriptCache {
pub fn new(cache_capacity: usize) -> Arc<InitiaScriptCache> {
let capacity = cache_capacity * 1024 * 1024;
Arc::new(InitiaScriptCache {
capacity,
script_cache: Mutex::new(CLruCache::with_config(
CLruCacheConfig::new(NonZeroUsize::new(cache_capacity * 1024 * 1024).unwrap())
.with_scale(ScriptScale),
CLruCacheConfig::new(NonZeroUsize::new(capacity).unwrap()).with_scale(ScriptScale),
)),
})
}
Expand All @@ -42,13 +44,18 @@ impl InitiaScriptCache {
let new_script = Code::from_deserialized(deserialized_script);
let deserialized_script = new_script.deserialized().clone();

// error occurs when the new script has a weight greater than the cache capacity
script_cache
.put_with_weight(key, ScriptWrapper::new(new_script, allocated_size))
.unwrap_or_else(|_| {
eprintln!("WARNING: failed to insert script into cache; cache capacity might be too small");
None
});
if self.capacity >= allocated_size {
// NOTE: We are not handling the error here, because we are sure that the
// allocated size is less than the capacity.
let _ = script_cache
.put_with_weight(key, ScriptWrapper::new(new_script, allocated_size))
beer-1 marked this conversation as resolved.
Show resolved Hide resolved
.unwrap_or_else(|_| None);
} else {
eprintln!(
"Script cache is too small to hold module with size {}",
allocated_size
);
}

Ok(deserialized_script)
}
Expand Down Expand Up @@ -81,12 +88,18 @@ impl InitiaScriptCache {
};

if let Some(new_script) = new_script {
script_cache
.put_with_weight(key, ScriptWrapper::new(new_script, allocated_size))
.unwrap_or_else(|_| {
eprintln!("WARNING: failed to insert script into cache; cache capacity might be too small");
None
});
if self.capacity >= allocated_size {
// NOTE: We are not handling the error here, because we are sure that the
// allocated size is less than the capacity.
let _ = script_cache
.put_with_weight(key, ScriptWrapper::new(new_script, allocated_size))
.unwrap_or_else(|_| None);
} else {
eprintln!(
"Script cache is too small to hold module with size {}",
allocated_size
);
}
}
Ok(verified_script)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/types/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl ModuleBundle {

pub fn singleton(code: Vec<u8>) -> Self {
Self {
codes: vec![Module::new(code.clone())],
codes: vec![Module::new(code)],
}
}

Expand Down
12 changes: 12 additions & 0 deletions precompile/modules/initia_stdlib/sources/bigdecimal.move
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ module initia_std::bigdecimal {
}

public fun rev(num: BigDecimal): BigDecimal {
assert!(
!biguint::is_zero(num.scaled),
error::invalid_argument(EDIVISION_BY_ZERO)
);

let fractional = f();
BigDecimal {
scaled: biguint::div(biguint::mul(fractional, fractional), num.scaled)
Expand Down Expand Up @@ -618,6 +623,13 @@ module initia_std::bigdecimal {
div_by_u256(num1, 0);
}

#[test]
#[expected_failure(abort_code = 0x10065, location = Self)]
fun test_bigdecimal_rev_zero() {
let num = zero();
rev(num);
}

#[test]
fun test_bigdecimal_scaled_le_bytes() {
let num1 = from_ratio(biguint::from_u64(1), biguint::from_u64(3));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ module initia_std::ed25519 {
public fun public_key_from_bytes(bytes: vector<u8>): PublicKey {
assert!(
std::vector::length(&bytes) == PUBLIC_KEY_SIZE,
std::error::invalid_argument(PUBLIC_KEY_SIZE)
std::error::invalid_argument(E_WRONG_PUBKEY_SIZE)
);
PublicKey { bytes }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,8 @@ module initia_std::secp256k1 {

// Test with an incorrect signature
let invalid_sig_bytes = sig_bytes;
*std::vector::borrow_mut(&mut invalid_sig_bytes, 0) = *std::vector::borrow(
&invalid_sig_bytes, 0
) ^ 0x1; // Corrupt the signature
*std::vector::borrow_mut(&mut invalid_sig_bytes, 0) =
*std::vector::borrow(&invalid_sig_bytes, 0) ^ 0x1; // Corrupt the signature
let invalid_sig = ecdsa_signature_from_bytes(invalid_sig_bytes);
assert!(!verify(msg, &pk, &invalid_sig), 3);
}
Expand Down
Loading
Loading