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
    • 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
  • 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.

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.10.tar.gz (410.4 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.10-py3-none-any.whl (439.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: stylus_analyzer-0.1.10.tar.gz
  • Upload date:
  • Size: 410.4 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.10.tar.gz
Algorithm Hash digest
SHA256 ab0e6ca86ce9034677b368c635456dcaffc67dd4a5c6267a6e47700ce70c4127
MD5 83dd163f5aefaa701813c818f4d8da55
BLAKE2b-256 19594e1678a64566e20081636355795e6d651de510e2cfbf165b146c1bc08461

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for stylus_analyzer-0.1.10-py3-none-any.whl
Algorithm Hash digest
SHA256 1ab0302f0dd7822f9937f608b5898bf2aff973a0417f09725bd674b53fd085b6
MD5 b8360ca68d8c36285c19a8e49dc27126
BLAKE2b-256 068c6dfa39c24292c6a03a7b59984ac5d0fc176502e4e476b2cf36f06b678ce5

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