Skip to content

Teycir/smartcontractpatternfinder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

163 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Smart Contract Pattern Finder (SCPF)

SCPF Logo
Smart Contract Pattern Finder Banner

πŸ” High-performance tool for detecting security vulnerabilities and patterns in Ethereum smart contracts.

How it works: Define patterns in YAML templates β†’ SCPF scans smart contracts β†’ Finds matching patterns β†’ Reports vulnerabilities

Rust License: MIT Crates.io Docs.rs GitHub Workflow Status

Tags: rust smart-contracts security scanner ethereum blockchain vulnerability-detection pattern-matching defi web3 solidity static-analysis open-source mit


πŸ“‘ Table of Contents


✨ Features

  • 🌐 Ethereum Support - Mainnet contract scanning via Etherscan API
  • πŸ“ Local Project Scanning - Scan .sol files in your workspace
  • πŸ”„ Git Diff Scanning - Only scan changed files in PRs
  • πŸ€– CI/CD Integration - GitHub Actions, GitLab CI, Bitbucket Pipelines
  • πŸ“ YAML Templates - Easy-to-write pattern definitions
  • βœ… ERC Compliance - Detect ERC-20/721/1155 implementations
  • πŸ“Š Size-Weighted Risk Scoring - Normalized per 100KB to eliminate size bias
  • 🧠 Context-Aware Filtering - Reduce obvious false positives with semantic and contextual filters
  • ⚑ Chunked Scanning - Handle larger sources without exhausting memory
  • πŸ’Ύ Smart Caching - Avoid redundant API calls
  • πŸ”‘ Cascade API Key System - Up to 6 keys with automatic rolling fallback
  • 🎯 Modular Architecture - CLI, core engine, server, and web UI components
  • πŸ”’ Security Focused - Built for vulnerability triage, reporting, and SARIF-based code scanning
  • πŸš€ High Performance - Built with Rust for speed
  • πŸ”§ Extensible - Easy to add custom patterns
  • 🌐 Optional Web UI - scpf-server and frontend/ provide a dashboard-driven workflow

πŸ’‘ Use Cases

Security Auditing

  • Automated Vulnerability Detection - Scan contracts for common vulnerabilities (reentrancy, delegatecall, unchecked calls)
  • Pre-deployment Checks - Validate contracts before mainnet deployment
  • Continuous Monitoring - Watch for newly deployed vulnerable contracts

DeFi Research

  • Pattern Analysis - Identify common patterns in DeFi protocols
  • Protocol Comparison - Compare security implementations across projects
  • Risk Assessment - Evaluate smart contract risk profiles

Bug Bounty Hunting

  • Automated Reconnaissance - Quickly scan multiple contracts for vulnerabilities
  • Pattern Discovery - Find recurring vulnerability patterns
  • Batch Analysis - Scan entire protocols at once

Development & CI/CD

  • Pre-commit Hooks - Validate contracts before commits
  • CI/CD Integration - Automated security checks in pipelines
  • Code Review - Assist manual code reviews with automated findings

Education & Training

  • Learning Tool - Understand common smart contract vulnerabilities
  • Template Library - Study real-world vulnerability patterns
  • Security Training - Train developers on secure coding practices

πŸš€ Quick Start

How It Works

  1. Create Templates - Define vulnerability patterns in YAML files
  2. Load Templates - SCPF reads your pattern definitions
  3. Fetch Contracts - Retrieves smart contract source code from blockchain explorers
  4. Scan & Match - Applies regex patterns to find vulnerabilities
  5. Report Results - Displays findings with severity levels and context

Installation

git clone https://github.com/Teycir/smartcontractpatternfinder.git
cd smartcontractpatternfinder
cargo build --release

Initialize Project

scpf init

Scan a Contract

# Scan blockchain contract
scpf scan 0x1234567890abcdef --chains ethereum

# Scan local project (auto-detects .sol files)
scpf scan

# Scan only changed files (for PRs)
scpf scan --diff main..HEAD

# Scan with custom templates
scpf scan --templates ./my-templates

# Scan multiple contracts
scpf scan 0xabc... 0xdef... 0x123... --chains ethereum

# Export to JSON/SARIF
scpf scan --output json > results.json
scpf scan --output sarif > results.sarif

# Restrict results to critical findings
scpf scan --min-severity critical

πŸ“‹ Template Example

Templates define patterns to search for in smart contracts. SCPF loads these templates and matches them against contract source code.

id: reentrancy-basic
name: Basic Reentrancy Pattern
description: Detects potential reentrancy vulnerabilities
severity: high
tags:
  - security
  - reentrancy
patterns:
  - id: external-call-with-value
    pattern: '\.call\{value:'
    message: External call with value transfer detected
  - id: delegatecall-usage
    pattern: '\.delegatecall\('
    message: Delegatecall usage detected

What happens:

  1. SCPF loads this template from templates/reentrancy.yaml
  2. Fetches contract source code from blockchain explorer
  3. Searches for .call{value: and .delegatecall( patterns
  4. Reports any matches with line numbers and context

πŸ—οΈ Architecture

smartcontractpatternfinder/
β”œβ”€β”€ crates/
β”‚   β”œβ”€β”€ scpf-types/     # Core types and data structures
β”‚   β”œβ”€β”€ scpf-core/      # Scanning, semantic analysis, caching
β”‚   β”œβ”€β”€ scpf-cli/       # Command-line interface
β”‚   └── scpf-server/    # Web server and scan orchestration
β”œβ”€β”€ frontend/           # Optional web dashboard
β”œβ”€β”€ templates/          # Pattern detection templates
β”œβ”€β”€ benchmarks/         # Accuracy and SARIF benchmark tooling
β”œβ”€β”€ scripts/            # Utility scripts (.sh, .py)
β”œβ”€β”€ docs/               # Project documentation
β”œβ”€β”€ sol/                # Solidity test files
└── action.yml          # GitHub Marketplace action definition

Module Overview

  • scpf-types: Core data structures (Template, Pattern, Match, ScanResult)
  • scpf-core: Business logic (Scanner, TemplateLoader, ContractFetcher, Cache, AST and semantic validation)
  • scpf-cli: User interface (CLI commands, output formatting)
  • scpf-server: HTTP server for orchestrating scans and streaming progress
  • frontend: Browser UI for starting scans and reviewing results

πŸ› οΈ CLI Commands

scpf scan

Scan smart contracts for patterns.

scpf scan [OPTIONS] [ADDRESSES]...

Options:
  -n, --chains <CHAINS>            Comma-separated chain list
  -t, --templates <TEMPLATES>      Templates directory
  -o, --output <OUTPUT>            Output format [default: console]
      --concurrency <CONCURRENCY>  Concurrent requests [default: 2]
      --pages <PAGES>              Number of explorer pages to fetch [default: 5]
      --diff <DIFF>                Only scan changed files (e.g., main..HEAD)
      --min-severity <LEVEL>       Minimum severity to report [default: high]
      --only-templates <IDS>       Restrict scan to specific template IDs
      --exclude-templates <IDS>    Exclude specific template IDs
      --contract-type <TYPE>       Filter by contract type (erc20, erc721, erc1155, proxy, defi)
      --fast                       Skip semantic analysis for speed
      --fetch-zero-day <DAYS>      Pull recent exploit patterns before scanning
      --extract-sources <N>        Save the top N riskiest sources into the report directory
  -v, --verbose...                 Increase verbosity (-v, -vv, -vvv)
  -h, --help                       Print help

Examples:

# Scan local project
scpf scan

# Scan blockchain contract
scpf scan 0x1234567890abcdef --chains ethereum

# Scan only changed files
scpf scan --diff main..HEAD

# Scan with custom templates
scpf scan --templates ./custom-templates

# Scan with more pages
scpf scan --chains ethereum --pages 10

# Restrict findings to selected templates
scpf scan --only-templates reentrancy,delegatecall-user-input

# Export to SARIF for CI/CD
scpf scan --output sarif > results.sarif

Other Commands

  • scpf audit runs the broader audit workflow using the same scan arguments
  • scpf templates lists, shows, installs, updates, and browses template collections
  • scpf fetch-zero-day imports recent exploit intelligence into templates
  • scpf pattern-builder launches the interactive pattern helper

scpf init

Initialize a new SCPF project.

scpf init [PATH]

Options:
  -y, --yes  Skip interactive prompts
  -h, --help Print help

Examples:

# Initialize in current directory
scpf init

# Initialize in specific directory
scpf init ./my-project

# Skip prompts
scpf init --yes

🎯 Supported Chains

Chain Network API Provider Status
Ethereum Mainnet Etherscan API βœ… Active
BSC BNB Smart Chain BscScan API 🚧 Planned
Polygon Polygon PoS PolygonScan API 🚧 Planned
Arbitrum Arbitrum One Arbiscan API 🚧 Planned
Optimism OP Mainnet Optimistic Etherscan API 🚧 Planned
Base Base Mainnet BaseScan API 🚧 Planned
Avalanche Avalanche C-Chain SnowTrace API 🚧 Planned
Fantom Fantom Opera FtmScan API 🚧 Planned
Linea Linea Mainnet LineaScan API 🚧 Planned
Scroll Scroll Mainnet ScrollScan API 🚧 Planned

Note: Currently only Ethereum mainnet is fully supported. Multi-chain support is planned for future releases. See Chain Support Status for implementation details.


πŸ”§ Configuration

API Key Setup

SCPF uses Etherscan API for fetching contract source code. Configure API keys via environment variables:

# Single key (required)
export ETHERSCAN_API_KEY="your-key"

# Optional: Add up to 6 keys for automatic cascade fallback
export ETHERSCAN_API_KEY_2="your-key-2"
export ETHERSCAN_API_KEY_3="your-key-3"
export ETHERSCAN_API_KEY_4="your-key-4"
export ETHERSCAN_API_KEY_5="your-key-5"
export ETHERSCAN_API_KEY_6="your-key-6"

Cascade API Key System

SCPF implements a rolling cascade fallback system for API keys:

  1. Primary Key - Tries ETHERSCAN_API_KEY first
  2. Automatic Rotation - If rate limited or failed, automatically tries next key
  3. Up to 6 Keys - Supports ETHERSCAN_API_KEY through ETHERSCAN_API_KEY_6
  4. Smart Retry - 50ms delay between key attempts
  5. Rate Limiting - Built-in semaphore (5 concurrent requests)

Benefits:

  • βœ… Avoid rate limit errors (Etherscan free tier: 5 calls/sec)
  • βœ… Increased throughput with multiple keys
  • βœ… Automatic failover if one key fails
  • βœ… Zero configuration - just add more keys

Getting API Keys

Tip: Create multiple free Etherscan accounts to get 6 API keys for maximum throughput (30 calls/sec).


πŸ“Š Output Formats

  • console - Human-readable terminal output (default)
  • json - Machine-readable JSON
  • sarif - SARIF format for CI/CD integration

πŸ€– CI/CD Integration

GitHub Actions

Add to .github/workflows/security.yml:

name: Security Scan

on: [push, pull_request]

jobs:
  scpf:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
      - uses: teycir/smartcontractpatternfinder@v1
        with:
          severity: high
          output-format: sarif
          fail-on-findings: true

Features:

  • βœ… Zero configuration
  • βœ… SARIF integration (results in Security tab)
  • βœ… Cached installation
  • βœ… Customizable severity threshold via --min-severity

πŸ“– Full GitHub Action Documentation

GitLab CI

scpf-scan:
  image: rust:latest
  script:
    - cargo install scpf-cli
    - scpf scan --output sarif > results.sarif
  artifacts:
    reports:
      sast: results.sarif

πŸ“– Full GitLab/Bitbucket Documentation

Pre-commit Hook

#!/bin/bash
# .git/hooks/pre-commit
scpf scan --diff HEAD || exit 1

πŸ§ͺ Development

# Run tests
cargo test --all

# Check code
cargo check

# Format code
cargo fmt

# Lint
cargo clippy

# Build release
cargo build --release

πŸ“ Creating Templates

Templates are the core of SCPF - they define what patterns to find in smart contracts.

How Templates Work

  1. Define Patterns - Write regex patterns that match vulnerable code
  2. Set Severity - Classify findings (info, low, medium, high, critical)
  3. Add Context - Provide descriptions and messages for findings
  4. Save as YAML - Store in templates/ directory
  5. SCPF Loads & Scans - Tool automatically uses your templates

Creating a Template

  1. Create a .yaml file in templates/
  2. Define patterns with regex
  3. Set severity level (info, low, medium, high, critical)
  4. Add descriptive tags

Template Structure:

id: unique-template-id
name: Human Readable Name
description: Detailed description of what this detects
severity: high  # info | low | medium | high | critical
tags:
  - category
  - subcategory
patterns:
  - id: pattern-id
    pattern: 'regex-pattern'
    message: Description of what was found

🀝 Contributing

Contributions welcome! Please follow:

  • Amazon Q rules in .amazonq/rules/
  • Modular architecture principles
  • Test-driven development
  • Clean, documented code

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch
  3. Follow coding standards
  4. Add tests for new features
  5. Submit a pull request

πŸ“„ License

MIT License - see LICENSE for details.


πŸ‘€ Author

Teycir Ben Soltane


πŸ”— Links


Built with ❀️ using Rust by Teycir Ben Soltane

About

High-performance Rust tool for detecting security vulnerabilities in smart contracts. Ethereum mainnet support with YAML-based pattern templates, CI/CD integration, and SARIF output for GitHub Security tab.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors