Skip to content

Draft fix#4

Closed
bowenwang1996 wants to merge 3 commits intolinear-protocol:mainfrom
bowenwang1996:potential-fix
Closed

Draft fix#4
bowenwang1996 wants to merge 3 commits intolinear-protocol:mainfrom
bowenwang1996:potential-fix

Conversation

@bowenwang1996
Copy link
Contributor

@bowenwang1996 bowenwang1996 commented Jun 22, 2025

There is a problem that the new staking pool does not have the interface to call voting function and we need to handle it separately.

Summary by CodeRabbit

  • New Features

    • Added support for voting through staking pool accounts with asynchronous ownership verification.
  • Bug Fixes

    • Improved voting security by verifying staking pool ownership before allowing votes.
  • Tests

    • Updated tests to support the optional staking pool parameter in voting.

@coderabbitai
Copy link

coderabbitai bot commented Jun 22, 2025

Walkthrough

The changes add support for voting through staking pool accounts by verifying their ownership. A new external contract interface is introduced to query the staking pool's owner. The voting method now optionally accepts a staking pool ID, performs an asynchronous ownership check, and only allows voting if the caller owns the staking pool.

Changes

File(s) Change Summary
src/lib.rs Added staking pool voting support: new constant for gas, external contract trait, updated vote logic, ownership verification method, and modified vote method signature.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Contract
    participant StakingPool

    Caller->>Contract: vote(is_vote, staking_pool_id)
    alt staking_pool_id is Some
        Contract->>StakingPool: get_owner_id() (async call)
        StakingPool-->>Contract: owner_account_id
        Contract->>Contract: check_owner_id_match(owner_account_id, callback_result)
        alt owner matches caller
            Contract->>Contract: proceed with voting
        else owner does not match
            Contract->>Caller: abort with error
        end
    else staking_pool_id is None
        Contract->>Contract: proceed with voting (using predecessor)
    end
Loading

Poem

A rabbit hops with code so bright,
Now pools can vote, the logic’s right!
Ownership checked from far away,
Only true owners get their say.
With async calls and careful checks,
The contract guards against all wrecks.
🐇✨


📜 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 a029e1d and 19a9f3a.

📒 Files selected for processing (1)
  • src/lib.rs (14 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib.rs
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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: 2

🔭 Outside diff range comments (1)
src/lib.rs (1)

220-488: Add tests for staking pool voting functionality

The new staking pool voting feature lacks test coverage. Please add tests for:

  • Voting through a staking pool with valid ownership
  • Rejection when the caller doesn't own the staking pool
  • Handling of cross-contract call failures
  • Edge cases with staking pool ID validation

Would you like me to help generate comprehensive test cases for the new functionality?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0f319 and 7250e3b.

📒 Files selected for processing (1)
  • src/lib.rs (4 hunks)
🔇 Additional comments (3)
src/lib.rs (3)

6-8: LGTM!

The additional imports for cross-contract functionality are appropriate.


17-17: LGTM!

The gas allocation of 5 TGas is reasonable for a simple getter function.


32-35: LGTM!

The external contract trait is well-defined with a clear interface for querying staking pool ownership.

src/lib.rs Outdated
Comment on lines +71 to +89
pub fn vote(&mut self, is_vote: bool, staking_pool_id: Option<AccountId>) {
self.ping();
let account_id = env::predecessor_account_id();
let account_id = if let Some(pool_id) = staking_pool_id {
let strs = pool_id.as_str().split(".").collect::<Vec<&str>>();
require!(
strs.len() == 3 && strs[1] == "pool" && strs[2] == "near",
"New staking_pool_id must be in the format <pool_id>.pool.near"
);
ext_staking_pool::ext(pool_id.clone())
.with_static_gas(GET_OWNER_ID_GAS)
.get_owner_id()
.then(
Self::ext(env::current_account_id())
.check_owner_id_match(env::predecessor_account_id()),
);
pool_id
} else {
env::predecessor_account_id()
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Vote is processed before ownership verification completes

The current implementation has a race condition where votes are counted before staking pool ownership is verified. The asynchronous call to get_owner_id doesn't block execution, so the vote proceeds immediately using the staking pool ID.

This is a security vulnerability that allows anyone to vote on behalf of any staking pool.

The voting logic needs to be moved into the callback to ensure ownership is verified first. Consider this architectural approach:

  1. Move the actual voting logic into a separate internal method
  2. In the main vote method, if staking_pool_id is provided, only initiate the async call
  3. In check_owner_id_match, after successful verification, call the internal voting method
  4. For direct voting (no staking pool), call the internal voting method directly

Additionally, the hardcoded format validation <pool_id>.pool.near may be too restrictive. Consider making this configurable or removing it entirely, relying only on the ownership check.

🤖 Prompt for AI Agents
In src/lib.rs lines 71 to 89, the vote function processes votes before verifying
staking pool ownership due to asynchronous calls not blocking execution.
Refactor by moving the voting logic into a separate internal method. Modify the
vote method to only initiate the async ownership verification call if
staking_pool_id is provided, and call the internal voting method directly if
not. Then, in the check_owner_id_match callback, after successful verification,
invoke the internal voting method to process the vote. Also, consider removing
or making the staking_pool_id format validation configurable instead of
hardcoding the "<pool_id>.pool.near" pattern.

src/lib.rs Outdated
Comment on lines +58 to +67
pub fn check_owner_id_match(
&self,
owner_account_id: AccountId,
#[callback_result] owner_account_id_result: Result<AccountId, PromiseError>,
) {
require!(
owner_account_id == owner_account_id_result.unwrap(),
"Voting is only allowed for the staking pool owner"
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle cross-contract call failures gracefully

The callback method will panic if the cross-contract call fails. This could be exploited or cause unexpected failures.

Apply this diff to handle errors properly:

-    pub fn check_owner_id_match(
-        &self,
-        owner_account_id: AccountId,
-        #[callback_result] owner_account_id_result: Result<AccountId, PromiseError>,
-    ) {
-        require!(
-            owner_account_id == owner_account_id_result.unwrap(),
-            "Voting is only allowed for the staking pool owner"
-        );
-    }
+    pub fn check_owner_id_match(
+        &self,
+        owner_account_id: AccountId,
+        #[callback_result] owner_account_id_result: Result<AccountId, PromiseError>,
+    ) {
+        match owner_account_id_result {
+            Ok(pool_owner) => {
+                require!(
+                    owner_account_id == pool_owner,
+                    "Voting is only allowed for the staking pool owner"
+                );
+            }
+            Err(_) => {
+                env::panic_str("Failed to retrieve staking pool owner");
+            }
+        }
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn check_owner_id_match(
&self,
owner_account_id: AccountId,
#[callback_result] owner_account_id_result: Result<AccountId, PromiseError>,
) {
require!(
owner_account_id == owner_account_id_result.unwrap(),
"Voting is only allowed for the staking pool owner"
);
}
pub fn check_owner_id_match(
&self,
owner_account_id: AccountId,
#[callback_result] owner_account_id_result: Result<AccountId, PromiseError>,
) {
match owner_account_id_result {
Ok(pool_owner) => {
require!(
owner_account_id == pool_owner,
"Voting is only allowed for the staking pool owner"
);
}
Err(_) => {
env::panic_str("Failed to retrieve staking pool owner");
}
}
}
🤖 Prompt for AI Agents
In src/lib.rs around lines 58 to 67, the method check_owner_id_match currently
unwraps the Result from a cross-contract call, which will panic if the call
fails. To fix this, modify the method to handle the Err case gracefully by
checking if owner_account_id_result is Ok and comparing the contained AccountId
with owner_account_id, otherwise handle the error case without panicking, for
example by returning early or logging an error, ensuring the contract does not
panic on cross-contract call failures.

@bowenwang1996
Copy link
Contributor Author

Close in favor of #5

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.

1 participant