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

fix: audit #174

merged 5 commits into from
Feb 3, 2025

Conversation

beer-1
Copy link
Member

@beer-1 beer-1 commented Jan 31, 2025

Description

  • S-63

Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Release Notes

  • New Features

    • Added to_simple_map function in both initia_std::table and minitia_std::table modules to convert tables to simple maps.
    • Introduced a new public field capacity in both InitiaModuleCache and InitiaScriptCache to manage cache limits.
  • Bug Fixes

    • Prevented potential division by zero in BigDecimal's reciprocal calculation.
    • Improved error reporting for public key size validation in cryptographic modules.
  • Code Improvements

    • Refined code formatting and readability across multiple modules.
    • Updated proposal expiration logic in multisig module.
    • Simplified method calls and removed unnecessary cloning in module handling.

@beer-1 beer-1 self-assigned this Jan 31, 2025
@beer-1 beer-1 requested a review from a team as a code owner January 31, 2025 03:36
Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

This pull request encompasses multiple modifications across various modules in the Initia and Minitia standard libraries. The changes primarily focus on improving code readability, error handling, and introducing new utility functions. Key modifications include updating method calls in Rust, refactoring code formatting, enhancing error reporting in cryptographic modules, and adding new conversion methods for data structures like tables. Additionally, new fields for cache capacities have been introduced in cache-related structs.

Changes

File Change Summary
crates/natives/src/block.rs Updated native_test_only_set_block_info to use instance method call instead of static method
crates/types/src/module.rs Removed unnecessary .clone() when creating ModuleBundle singleton
precompile/modules/*/sources/bigdecimal.move Added zero check in rev function to prevent division by zero
precompile/modules/*/sources/crypto/ed25519.move Updated error handling to use specific error code constant
precompile/modules/*/sources/crypto/secp256k1.move Minor formatting changes in test function
precompile/modules/*/sources/multisig.move Inverted proposal expiration logic
precompile/modules/*/sources/table.move Added to_simple_map function to convert tables to simple maps
crates/storage/src/module_cache.rs Added capacity field to InitiaModuleCache and updated insertion logic
crates/storage/src/script_cache.rs Added capacity field to InitiaScriptCache and updated insertion logic
crates/e2e-move-tests/src/tests/move_unit.rs Updated import statement for CompilerVersion and LanguageVersion

Sequence Diagram

sequenceDiagram
    participant Table
    participant SimpleMap
    Note over Table: Create Table
    Table->>SimpleMap: Convert using to_simple_map()
    SimpleMap-->>Table: Returns populated SimpleMap
Loading

Suggested reviewers

  • sh-cha

Poem

🐰 Hopping through code with glee,
Refactoring lines, setting functions free!
From tables to crypto, we dance and we play,
Improving our system in a rabbity way! 🌟
Bugs beware, our changes are neat! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94c7d01 and 6404824.

📒 Files selected for processing (3)
  • crates/e2e-move-tests/src/tests/move_unit.rs (1 hunks)
  • crates/storage/src/module_cache.rs (5 hunks)
  • crates/storage/src/script_cache.rs (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/e2e-move-tests/src/tests/move_unit.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/storage/src/script_cache.rs
  • crates/storage/src/module_cache.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Rust libmovevm

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
precompile/modules/initia_stdlib/sources/table.move (1)

237-248: LGTM! Consider reserving capacity for the simple map.

The implementation is correct and follows a clean pattern for converting a Table to a SimpleMap. However, since we know the size of the table upfront, we could optimize the conversion by reserving capacity in the simple map.

Consider adding a capacity hint to the simple map creation:

-        let map = std::simple_map::new();
+        let map = std::simple_map::create_with_capacity(table::length(table));
precompile/modules/minitia_stdlib/sources/multisig.move (1)

490-490: LGTM! Fixed proposal expiration logic.

The conditions have been correctly inverted to properly check if the current height/timestamp has exceeded the expiration height/timestamp.

Consider adding a test case that specifically verifies the boundary conditions of the expiration logic:

#[test]
fun test_proposal_expiration_boundary() {
    let max_period = Period {
        height: option::some(10),
        timestamp: option::some(10)
    };
    
    // Test height boundary
    assert!(!is_proposal_expired(&max_period, 100, 100, 109, 100), 1); // Not expired
    assert!(is_proposal_expired(&max_period, 100, 100, 110, 100), 2);  // Expired
    
    // Test timestamp boundary
    assert!(!is_proposal_expired(&max_period, 100, 100, 100, 109), 3); // Not expired
    assert!(is_proposal_expired(&max_period, 100, 100, 100, 110), 4);  // Expired
}

Also applies to: 496-496

precompile/modules/minitia_stdlib/sources/table.move (1)

237-248: Implementation looks correct but consider performance implications.

The implementation correctly converts a Table to a SimpleMap by iterating through all entries. However, be aware that this operation:

  1. Copies all values due to the copy constraint on type V
  2. Requires memory proportional to the table size

Consider documenting the performance characteristics in the function comment, especially for large tables. You might want to add:

+    /// Converts a Table to a SimpleMap by copying all entries.
+    /// Note: This operation requires memory proportional to the table size
+    /// and copies all values. Use with caution for large tables.
     public fun to_simple_map<K: store + copy + drop, V: store + copy>(
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7096b76 and 086cc8a.

📒 Files selected for processing (14)
  • crates/natives/src/block.rs (1 hunks)
  • crates/types/src/module.rs (1 hunks)
  • precompile/modules/initia_stdlib/sources/bigdecimal.move (2 hunks)
  • precompile/modules/initia_stdlib/sources/crypto/ed25519.move (1 hunks)
  • precompile/modules/initia_stdlib/sources/crypto/secp256k1.move (1 hunks)
  • precompile/modules/initia_stdlib/sources/minitswap.move (15 hunks)
  • precompile/modules/initia_stdlib/sources/multisig.move (1 hunks)
  • precompile/modules/initia_stdlib/sources/stableswap.move (3 hunks)
  • precompile/modules/initia_stdlib/sources/table.move (1 hunks)
  • precompile/modules/minitia_stdlib/sources/bigdecimal.move (2 hunks)
  • precompile/modules/minitia_stdlib/sources/crypto/ed25519.move (1 hunks)
  • precompile/modules/minitia_stdlib/sources/crypto/secp256k1.move (1 hunks)
  • precompile/modules/minitia_stdlib/sources/multisig.move (1 hunks)
  • precompile/modules/minitia_stdlib/sources/table.move (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • precompile/modules/minitia_stdlib/sources/crypto/secp256k1.move
  • precompile/modules/initia_stdlib/sources/crypto/secp256k1.move
  • precompile/modules/initia_stdlib/sources/stableswap.move
  • precompile/modules/initia_stdlib/sources/minitswap.move
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Rust libmovevm
  • GitHub Check: rust lint
🔇 Additional comments (10)
crates/natives/src/block.rs (1)

63-63: LGTM! More idiomatic method call.

The change from static to instance method call style improves readability while maintaining the same functionality.

crates/types/src/module.rs (1)

61-61: LGTM! Removed unnecessary clone.

Good optimization by removing the redundant clone() call since code is already owned and can be moved directly into Module::new().

precompile/modules/initia_stdlib/sources/crypto/ed25519.move (1)

47-47: LGTM! Improved error handling clarity.

Good improvement by using the semantic error code E_WRONG_PUBKEY_SIZE instead of PUBLIC_KEY_SIZE. This makes the error more descriptive and aligns with best practices for error handling.

precompile/modules/minitia_stdlib/sources/crypto/ed25519.move (1)

47-47: LGTM! Maintains consistency with initia_stdlib.

Good improvement by using the semantic error code E_WRONG_PUBKEY_SIZE, maintaining consistency with the parallel change in initia_stdlib.

precompile/modules/initia_stdlib/sources/bigdecimal.move (2)

120-123: LGTM! Added division by zero check.

The assertion correctly prevents division by zero when calculating the reciprocal of a BigDecimal.


626-631: LGTM! Added test for division by zero check.

The test verifies that calling rev with a zero BigDecimal correctly triggers the expected failure.

precompile/modules/minitia_stdlib/sources/bigdecimal.move (2)

120-123: LGTM! Added division by zero check.

The assertion correctly prevents division by zero when calculating the reciprocal of a BigDecimal.


626-631: LGTM! Added test for division by zero check.

The test verifies that calling rev with a zero BigDecimal correctly triggers the expected failure.

precompile/modules/initia_stdlib/sources/multisig.move (1)

490-490: Verify the expiration logic change.

The expiration logic has been inverted to check if the current height/timestamp is greater than or equal to the sum of max period and proposal height/timestamp. This change appears to be correct as it properly determines if a proposal has expired by checking if we've moved past the voting window.

Let's verify the expiration logic by checking test cases:

Also applies to: 496-496

✅ Verification successful

Expiration logic is correctly implemented

The implementation height >= (max_voting_period_height + proposal_height) is correct as it properly determines if the current block height has moved past the voting window (proposal_height + max_voting_period_height). This ensures proposals expire exactly when intended, neither too early nor too late.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test cases that verify proposal expiration logic.

# Test: Search for test cases that verify proposal expiration.
rg -A 10 'vote_after_(height|timestamp)_expired' --type move

Length of output: 91


Script:

#!/bin/bash
# Search for test cases and implementation of proposal expiration
rg -l "is_proposal_expired" .

# Get the full context of the is_proposal_expired function
rg -B 10 -A 10 "is_proposal_expired" .

# Search for test files related to proposal expiration
fd ".*test.*\.move$"

Length of output: 29384

precompile/modules/minitia_stdlib/sources/table.move (1)

237-248: Add unit tests for the new function.

Please add test cases to verify:

  1. Converting an empty table
  2. Converting a table with a single entry
  3. Converting a table with multiple entries
  4. Preserving the order of entries

Here's a suggested test implementation:

#[test(account = @0x1)]
fun test_to_simple_map(account: &signer) {
    let t = new<u64, u8>();
    
    // Test empty table
    let map = to_simple_map(&t);
    assert!(std::simple_map::length(&map) == 0, 1);
    
    // Test single entry
    add(&mut t, 1, 10);
    let map = to_simple_map(&t);
    assert!(std::simple_map::length(&map) == 1, 2);
    assert!(*std::simple_map::borrow(&map, 1) == 10, 3);
    
    // Test multiple entries
    add(&mut t, 2, 20);
    add(&mut t, 3, 30);
    let map = to_simple_map(&t);
    assert!(std::simple_map::length(&map) == 3, 4);
    assert!(*std::simple_map::borrow(&map, 1) == 10, 5);
    assert!(*std::simple_map::borrow(&map, 2) == 20, 6);
    assert!(*std::simple_map::borrow(&map, 3) == 30, 7);
    
    move_to(account, TableHolder { t });
}
✅ Verification successful

Add unit tests for the new to_simple_map function

The verification confirms that there are no existing tests for the to_simple_map function in the codebase. The suggested test cases in the review comment are appropriate and should be implemented to ensure the function's correctness.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find test files in the module directory
fd -e move . precompile/modules/minitia_stdlib/sources/

# Search for existing tests of to_simple_map
rg "to_simple_map" precompile/modules/minitia_stdlib/sources/ -B 2 -A 2

Length of output: 3893


Script:

#!/bin/bash
# Look for test module and test cases in table.move
rg "#\[test\]" precompile/modules/minitia_stdlib/sources/table.move -B 2 -A 10

# Also check for any test module declarations
rg "module.*tests" precompile/modules/minitia_stdlib/sources/table.move -A 5

Length of output: 159

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
crates/storage/src/script_cache.rs (2)

47-55: Consider enhancing the error message with size information.

While the capacity check is correctly implemented, the error message could be more informative by including the script size and cache capacity.

-                            eprintln!("WARNING: failed to insert script into cache");
+                            eprintln!(
+                                "WARNING: failed to insert script into cache (size: {} bytes, capacity: {} bytes)",
+                                allocated_size,
+                                self.capacity
+                            );

88-96: Consider enhancing the error message with size information (similar to previous comment).

For consistency with the previous suggestion, enhance the error message here as well.

-                        eprintln!("WARNING: failed to insert script into cache");
+                        eprintln!(
+                            "WARNING: failed to insert script into cache (size: {} bytes, capacity: {} bytes)",
+                            allocated_size,
+                            self.capacity
+                        );
crates/storage/src/module_cache.rs (3)

82-85: Consider adding size information to the error message.

The error message includes module ID, which is helpful. Consider also adding size information for better debugging.

                        eprintln!(
-                            "WARNING: failed to insert module {:?} into cache",
+                            "WARNING: failed to insert module {:?} into cache (size: {} bytes, capacity: {} bytes)",
                            module_id.short_str_lossless().to_string(),
+                            allocated_size,
+                            self.capacity
                        );

Also applies to: 102-106


130-141: Consider adding size information to the error message (similar to previous comment).

For consistency, enhance the error message with size information here as well.

                            eprintln!(
-                                "WARNING: failed to insert module {:?} into cache",
+                                "WARNING: failed to insert module {:?} into cache (size: {} bytes, capacity: {} bytes)",
                                module_id.short_str_lossless().to_string(),
+                                allocated_size,
+                                self.capacity
                            );

177-189: Consider adding size information to the error message (similar to previous comments).

For consistency across all methods, enhance the error message with size information here as well.

                                    eprintln!(
-                                        "WARNING: failed to insert module {:?} into cache",
+                                        "WARNING: failed to insert module {:?} into cache (size: {} bytes, capacity: {} bytes)",
                                        id.short_str_lossless().to_string(),
+                                        allocated_size,
+                                        self.capacity
                                    );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 086cc8a and 94c7d01.

📒 Files selected for processing (2)
  • crates/storage/src/module_cache.rs (6 hunks)
  • crates/storage/src/script_cache.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Rust libmovevm
🔇 Additional comments (2)
crates/storage/src/script_cache.rs (1)

15-15: LGTM! Capacity field addition and initialization look good.

The capacity field is correctly initialized in megabytes and converted to bytes. The same value is consistently used for CLruCache configuration.

Also applies to: 22-22

crates/storage/src/module_cache.rs (1)

54-54: LGTM! Capacity field addition and initialization are consistent.

The implementation matches the approach in script_cache.rs, maintaining consistency across cache types.

Also applies to: 63-63

@beer-1 beer-1 requested a review from sh-cha February 3, 2025 07:50
Copy link
Contributor

@sh-cha sh-cha left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@beer-1 beer-1 merged commit 99b894e into main Feb 3, 2025
3 checks passed
@beer-1 beer-1 deleted the fix/audit branch February 3, 2025 09:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants