Skip to main content

AI-powered bug detection tool for Stylus/Rust contracts

Project description

Stylus Analyzer

A tool for analyzing Stylus/Rust smart contracts for security issues and bugs.

Features

  • AI-powered contract analysis using OpenAI models
  • Static analysis to detect common vulnerabilities
    • Unchecked transfer vulnerabilities
    • Unsafe panic!() and unwrap() calls
    • Unsafe ABI encoding operations
    • Locked Ether vulnerabilities
    • Extensible detector system for easily adding new vulnerability checks

Installation

You can install Stylus Analyzer using pip:

pip install stylus-analyzer

For development or the latest features, you can install from the source:

# Clone the repository
git clone https://github.com/StylusAnalyzer/stylus-analyzer.git
cd stylus-analyzer

# Install the package in development mode
pip install -e .

Usage

Static Analysis

To perform static analysis on Rust contracts to detect common issues:

# Analyze a single file
stylus-analyzer static-analyze test_contracts/unsafe_transfer_example.rs

# Analyze all contracts in a directory
stylus-analyzer static-analyze test_contracts/

# Save results to a JSON file
stylus-analyzer static-analyze test_contracts/ -o analysis_results.json

# Save results to a PDF report
stylus-analyzer static-analyze test_contracts/ -p analysis_report.pdf

# Save results in both JSON and PDF formats
stylus-analyzer static-analyze test_contracts/ -o analysis_results.json -p analysis_report.pdf

# Show detailed output including code snippets
stylus-analyzer static-analyze test_contracts/ --verbose

The static analyzer will check for various issues including:

  • Unchecked transfer return values that can lead to silent failures
  • Unsafe panic!() macro calls that cause immediate termination
  • Unsafe unwrap() calls that may cause panics
  • Unsafe encode_packed operations with dynamic types that may cause hash collisions
  • Locked Ether vulnerabilities where funds can be received but not withdrawn
  • More detectors can be added by extending the framework

AI Analysis

To perform AI-powered analysis (requires OpenAI API key):

# Set your OpenAI API key
export OPENAI_API_KEY=your-api-key

# Analyze a single file
stylus-analyzer analyze-file test_contracts/test_token.rs

# Analyze all contracts in a project directory
stylus-analyzer analyze path/to/project

# Save results to a file
stylus-analyzer analyze path/to/project -o analysis_results.json

Custom Detectors

You can create custom detectors for the static analyzer by following these steps:

  1. Create a new detector file in stylus_analyzer/detectors/
  2. Extend the BaseDetector class
  3. Implement the required methods
  4. Register your detector in the system

Example detector:

from tree_sitter import Node, Tree
from stylus_analyzer.detectors.detector_base import BaseDetector

class MyCustomDetector(BaseDetector):
    def __init__(self):
        super().__init__(
            name="my_custom_detector",
            description="Description of what this detector looks for"
        )
    
    def detect(self, tree: Tree, code: str, results) -> None:
        # Implement your detection logic here
        pass

You can register your detector in two ways:

  1. Add it to the AVAILABLE_DETECTORS list in stylus_analyzer/detectors/__init__.py:
from stylus_analyzer.detectors.my_custom_detector import MyCustomDetector

AVAILABLE_DETECTORS = [
    # Other detectors...
    MyCustomDetector
]
  1. Or register it programmatically:
from stylus_analyzer.detectors import register_detector
from my_package.my_detector import MyCustomDetector

register_detector(MyCustomDetector)

Performance Optimizations

The analyzer includes several performance optimizations:

  1. AST generation is done once per file and reused across all detectors
  2. Parser initialization uses a singleton pattern to avoid redundant setup
  3. Analysis timing is tracked and reported for benchmarking
  4. Error handling tracks and reports issues without crashing

Contributing

Contributions to Stylus Analyzer are welcome! Here's how you can contribute:

Adding New Vulnerability Detectors

  1. Fork the repository
  2. Create a new detector file in the stylus_analyzer/detectors/ directory
  3. Implement your detector by extending the BaseDetector class
  4. Add tests for your detector in the stylus_analyzer/tests/ directory
  5. Submit a pull request with a description of the vulnerability your detector identifies

Coding Standards

  • Use type hints for all function parameters and return values
  • Add docstrings for all classes and functions
  • Follow PEP 8 style guidelines
  • Write unit tests for new functionality

Development Setup

# Clone your fork
git clone https://github.com/StylusAnalyzer/stylus-analyzer.git
cd stylus-analyzer

# Create and activate a virtual environment (optional but recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e .

# Run tests
pytest

License

This project is licensed under the terms of the MIT license.

Detectors

Unchecked Transfer

Detects unchecked transfer calls where the return value is not properly checked. This can lead to silent failures where token transfers fail but the contract continues execution as if they succeeded.

Unsafe Unwrap

Detects uses of .unwrap() in Rust code, which can cause runtime panics if the value is None or Err. In a blockchain context, panics can cause transactions to fail and may lead to loss of funds or unexpected behavior. Instead, developers should use pattern matching, the ? operator, or other explicit error handling techniques.

Unsafe Panic

Detects uses of panic!() macro in Rust code, which causes immediate termination that cannot be caught or recovered from. In a blockchain context, this will cause the entire transaction to fail with no way to handle the error gracefully. Developers should use Result/Option types with explicit error handling instead.

Unsafe Encode Packed

Detects potentially unsafe uses of encode_packed with dynamic types like strings. When used with dynamic types without delimiters, different inputs can produce the same packed result (e.g., encode_packed("a", "bc") == encode_packed("ab", "c")), which can lead to hash collisions. This is particularly problematic when the packed result is used for signatures, authentication, or as a unique identifier. Developers should use regular encode which adds padding, use fixed-size types with encode_packed, or add delimiters between dynamic values.

Locked Ether

Detects contracts that can receive Ether but lack withdrawal methods, potentially causing funds to become permanently inaccessible. This occurs when contracts have payable functions or can receive Ether through fallback mechanisms but don't provide any way for users or administrators to retrieve those funds. Developers should implement withdrawal functions with proper access controls, emergency withdrawal mechanisms, or remove the ability to receive Ether if it's not needed for the contract's functionality.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stylus_analyzer-0.1.12.tar.gz (304.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stylus_analyzer-0.1.12-py3-none-any.whl (332.7 kB view details)

Uploaded Python 3

File details

Details for the file stylus_analyzer-0.1.12.tar.gz.

File metadata

  • Download URL: stylus_analyzer-0.1.12.tar.gz
  • Upload date:
  • Size: 304.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.6

File hashes

Hashes for stylus_analyzer-0.1.12.tar.gz
Algorithm Hash digest
SHA256 638ee145467c03cb5d041919d69c8166589716ba798987aaff0d36c7bf0e7d64
MD5 1108c4050c4eaf43c492f4473b0176e6
BLAKE2b-256 c7b101e851d396ba34752e1835993974756e232eafd0de42df040b66803d05a7

See more details on using hashes here.

File details

Details for the file stylus_analyzer-0.1.12-py3-none-any.whl.

File metadata

File hashes

Hashes for stylus_analyzer-0.1.12-py3-none-any.whl
Algorithm Hash digest
SHA256 f49a359d934c2142bb233bb697e8c16a675d2e5f9b2117ecc2ef4afb4f987c5b
MD5 601b858513d579233c5f5bdbb037bdc4
BLAKE2b-256 05f117e304e7fdc9bafe2841aaed439b1bad5fdd032c26b562a15f940a741ec0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page