Skip to content

added tests for demonstration of hash not uniqueness attack#62

Open
Sunnesoft wants to merge 5 commits intomainfrom
test/OZ-strategyHash-uniqueness
Open

added tests for demonstration of hash not uniqueness attack#62
Sunnesoft wants to merge 5 commits intomainfrom
test/OZ-strategyHash-uniqueness

Conversation

@Sunnesoft
Copy link
Copy Markdown
Contributor

No description provided.

@Sunnesoft Sunnesoft marked this pull request as ready for review January 24, 2026 23:21
@Sunnesoft Sunnesoft requested a review from Copilot January 24, 2026 23:21
@claude
Copy link
Copy Markdown

claude bot commented Jan 24, 2026

Claude finished @Sunnesoft's task —— View job


Code Review for Hash Uniqueness Attack Demonstration

Review Checklist

  • Gather context and read relevant files
  • Analyze the hash uniqueness attack being demonstrated
  • Review code quality and best practices
  • Assess potential security concerns
  • Check test coverage and effectiveness
  • Provide comprehensive feedback

Summary

This PR adds valuable tests demonstrating a critical security vulnerability where multiple strategies with identical programs share the same orderHash, potentially allowing unintended cross-token swaps that could lead to LP fund loss.

Security Analysis

🔴 Critical Security Issue Demonstrated

The test test_SameHash_DifferentTokens_TakerCanSwap() successfully demonstrates a dangerous scenario:

  1. Attack Vector: Two strategies with identical programs but different token pairs (A/B and C/D) produce the same orderHash
  2. Risk: Lines 207-251 show that a taker can perform cross-strategy swaps (B->C), accessing liquidity from different token pools
  3. Impact: LPs could lose funds as their liquidity becomes accessible for unintended token pairs

Recommended Mitigation Demonstrated

The test test_SameHash_DifferentTokens_TakerCanNotSwap() shows the proper solution:

  • Using the _salt instruction with unique values (lines 269, 272)
  • Results in different orderHash values for each strategy
  • Prevents cross-strategy swaps with proper revert (lines 328-344)

Code Quality

Positive Aspects:

  1. Clear Documentation: Excellent use of NatSpec comments explaining the security risk (lines 44-54) and recommended practice (lines 254-266)
  2. Comprehensive Testing: Both vulnerable and secure scenarios are tested
  3. Good Test Structure: Tests follow AAA pattern (Arrange, Act, Assert)
  4. Proper Error Testing: Uses vm.expectRevert with specific error selector

Minor Issues:

  1. Typo: Line 278 comment says "same orderHash" but should say "different orderHash"
  2. Gas Costs: The secure approach adds ~427k gas (test_SameHash_DifferentTokens_TakerCanSwap: 973,735 vs test_SameHash_DifferentTokens_TakerCanNotSwap: 546,563)

Test Coverage

The tests effectively cover:

  • ✅ Vulnerable scenario with same hash
  • ✅ Secure scenario with salt differentiation
  • ✅ Balance verification before and after swaps
  • ✅ Cross-strategy swap attempts
  • ✅ Error conditions

Recommendations

  1. Production Code: Ensure the main contract enforces unique strategy hashes or provides clear documentation warning about this risk
  2. Additional Test: Consider adding a test that demonstrates multiple strategies with the same tokens but different programs
  3. Documentation: This security consideration should be prominently documented in the main project README or security documentation

Performance Considerations

The gas snapshot shows:

  • test_SameHash_DifferentTokens_TakerCanSwap: 973,735 gas
  • test_SameHash_DifferentTokens_TakerCanNotSwap: 546,563 gas

The difference is expected due to the additional successful swap operations in the vulnerable scenario.

Conclusion

This is an excellent security-focused PR that clearly demonstrates a critical vulnerability and its mitigation. The tests serve as both documentation and validation of the security model. The code quality is high, with only minor issues that don't affect functionality.

Recommendation: ✅ Approve - This PR adds crucial security tests that will help prevent potential fund loss scenarios.

@Sunnesoft Sunnesoft requested a review from SevenSwen January 24, 2026 23:21
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds comprehensive test coverage to demonstrate hash collision vulnerabilities and their mitigation in the SwapVM system. The tests show both the security risk when strategies share the same hash (allowing unintended cross-token swaps) and the proper solution using salt values to ensure hash uniqueness.

Changes:

  • Added UniquenessTest.t.sol with two test cases demonstrating hash uniqueness behavior
  • Updated gas snapshots to include the new test measurements

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
test/UniquenessTest.t.sol Adds tests demonstrating hash collision vulnerability and the recommended salt-based mitigation approach
.gas-snapshot Updates gas measurements to include the new uniqueness tests

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Sunnesoft and others added 2 commits January 24, 2026 20:22
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@claude
Copy link
Copy Markdown

claude bot commented Jan 24, 2026

Claude finished @Sunnesoft's task —— View job


Code Review: Hash Uniqueness Attack Demonstration Tests

Review Checklist:

  • Read test files and understand the implementation
  • Analyze code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Review security concerns
  • Assess test coverage
  • Provide comprehensive review feedback

Summary

This PR adds well-crafted security tests that demonstrate a critical hash collision vulnerability and its mitigation. The tests effectively illustrate how strategies with identical programs can share the same hash, potentially allowing unintended cross-token swaps that could lead to fund loss. The code quality is high with excellent documentation.

Code Quality and Best Practices ✅

Strengths:

  1. Excellent Documentation: Outstanding use of NatSpec comments (lines 44-54, 254-266) clearly explaining the security risk and recommended practice
  2. Well-Structured Tests: Both tests follow the AAA (Arrange, Act, Assert) pattern with clear separation of concerns
  3. Descriptive Test Names: test_SameHash_DifferentTokens_TakerCanSwap and test_SameHash_DifferentTokens_TakerCanNotSwap clearly indicate what each test validates
  4. Good Helper Function: buildSimpleXYCProgram (line 35) promotes code reuse and clarity
  5. Comprehensive Assertions: Thorough verification of balances before and after operations

Areas for Improvement:

  • Consider extracting common setup code between the two tests into helper functions to reduce duplication (lines 74-105 are similar to 282-312)

Potential Bugs or Issues 🐛

  1. Misleading Comments: Several comments contain inaccuracies that were also identified by the Copilot review:

    • Line 271: Says "same program" but should say "different salt"
    • Line 278: Says "same orderHash" but should say "different orderHash"
    • Lines 319-321: Comment doesn't accurately describe what happens (swap fails, not succeeds)
  2. No Critical Bugs: The test logic is sound and correctly demonstrates both the vulnerability and mitigation

Performance Considerations ⚡

Gas measurements from .gas-snapshot:

  • test_SameHash_DifferentTokens_TakerCanSwap: 973,735 gas
  • test_SameHash_DifferentTokens_TakerCanNotSwap: 546,563 gas

The ~427k gas difference is expected because:

  • The vulnerable scenario performs 3 successful swaps
  • The secure scenario performs 0 swaps (reverts on attempt)
  • This difference highlights the computational cost of the vulnerability when exploited

Security Concerns 🔒

Critical Security Issue Demonstrated:

  1. Hash Collision Attack: The first test successfully demonstrates that strategies with identical programs but different token pairs produce the same orderHash
  2. Cross-Strategy Swap Risk: Lines 207-251 show a taker can perform unintended swaps between different token pools (B→C swap using strategy with A/B tokens)
  3. LP Fund Loss Risk: This vulnerability could allow attackers to drain liquidity from unrelated token pools

Mitigation Demonstrated:

  • The second test shows the proper solution using the _salt instruction to ensure unique hashes
  • Properly prevents cross-strategy swaps with SafeBalancesForTokenNotInActiveStrategy error

Test Coverage 📊

Comprehensive Coverage:

  • ✅ Vulnerable scenario with identical hashes
  • ✅ Secure scenario with salt-based differentiation
  • ✅ Balance verification pre/post operations
  • ✅ Cross-strategy swap attempts
  • ✅ Proper error conditions with vm.expectRevert

Suggestions for Additional Coverage:

  1. Test edge case with same tokens but different programs
  2. Test with more than 2 strategies sharing the same hash
  3. Test partial swaps and different swap directions

Recommendations 📝

  1. Fix Comment Inaccuracies: Update the misleading comments identified above to accurately reflect the test behavior
  2. Production Code Alert: Ensure the main contract documentation prominently warns about this vulnerability
  3. Consider Adding: A test demonstrating multiple (>2) strategies with the same hash to show the full scope of the issue
  4. Refactor Opportunity: Extract common setup code to reduce duplication and improve maintainability

Conclusion

This is an excellent security-focused PR that effectively demonstrates a critical vulnerability and its proper mitigation. The tests serve as both valuable documentation and validation of the security model. Despite minor comment inaccuracies, the implementation is solid and the security implications are well-illustrated.

Verdict: ✅ Approve with minor suggestions

The comment issues should be addressed, but they don't affect the functionality or value of these important security tests.

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@claude
Copy link
Copy Markdown

claude bot commented Jan 24, 2026

Claude finished @Sunnesoft's task —— View job


Code Review for Hash Uniqueness Attack Demonstration

Review Checklist

  • Read test/UniquenessTest.t.sol to understand the hash uniqueness tests
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Post comprehensive review feedback

Summary

This PR adds important tests demonstrating a critical security vulnerability where multiple strategies with identical programs produce the same orderHash, potentially allowing unintended cross-token swaps. The tests clearly show both the vulnerable scenario and the recommended mitigation using salt values.

Security Concerns

Critical Security Issue Demonstrated

The tests effectively demonstrate a dangerous attack vector where:

  • Two strategies with identical programs but different token pairs share the same orderHash
  • This allows takers to perform cross-strategy swaps (e.g., swapping B→C when strategies are for A/B and C/D pairs)
  • Lines 207-251 in test_SameHash_DifferentTokens_TakerCanSwap() clearly show this vulnerability

Proper Mitigation Shown

The second test demonstrates the correct solution using the _salt instruction with unique values, resulting in different orderHash values that prevent cross-strategy swaps.

Code Quality and Best Practices

Strengths:

  • Excellent documentation with NatSpec comments explaining the security risks and recommended practices
  • Clear test structure following AAA (Arrange, Act, Assert) pattern
  • Comprehensive testing of both vulnerable and secure scenarios
  • Proper use of vm.expectRevert with specific error selectors

Issues Found:

  1. Misleading Comments (Lines 278, 271, 319-321):

    • Line 278: Comment says "same orderHash" but should say "different orderHash"
    • Line 271: Comment incorrectly states second strategy has same program (it has different salt)
    • Lines 319-321: Comment incorrectly states swap will succeed, when it will actually fail with SafeBalancesForTokenNotInActiveStrategy
  2. Assertion Message Error (Line 279):

    • Message says "Strategies with same program should not have same orderHash" but they actually have different programs due to different salts

Performance Considerations

The gas snapshots show expected behavior:

  • test_SameHash_DifferentTokens_TakerCanSwap: 973,735 gas
  • test_SameHash_DifferentTokens_TakerCanNotSwap: 546,563 gas

The higher gas cost in the vulnerable scenario is due to successful swap operations, while the secure scenario reverts early, consuming less gas.

Test Coverage

The tests provide excellent coverage:

  • ✅ Demonstrates vulnerable scenario with hash collision
  • ✅ Shows secure scenario with salt differentiation
  • ✅ Verifies balance changes for all tokens
  • ✅ Tests cross-strategy swap attempts
  • ✅ Validates proper revert behavior with specific error

Potential Bugs or Issues

No functional bugs found. The main issues are documentation-related:

  • Incorrect comments that could confuse future developers about the test's purpose
  • These should be fixed to maintain code clarity

Recommendations

  1. Fix the misleading comments to accurately reflect what each test is demonstrating
  2. Consider adding an additional test showing multiple strategies with same tokens but different programs
  3. Document this security consideration prominently in the main project documentation
  4. Ensure production code enforces unique strategy hashes or clearly warns about this risk

Verdict

Recommendation: Approve with minor fixes

This is a valuable security-focused PR that demonstrates an important vulnerability and its mitigation. The tests are well-written and serve as both documentation and validation. The comment issues are minor and don't affect functionality, but should be addressed for clarity.

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