auditing

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2025 License: Unlicense Imports: 8 Imported by: 0

README

Auditing Agents

The Arbitrum Sequencer Decoder includes a comprehensive auditing system to monitor and validate the various components of the arbitrage system. This system helps ensure the reliability, accuracy, and profitability of the arbitrage operations.

Components

1. Decoder Auditor

The Decoder Auditor monitors the performance and accuracy of the DEX transaction decoders.

Features
  • Tracks decoding success rates
  • Measures average, min, and max decode times
  • Monitors total liquidity processed
  • Provides configuration thresholds for alerts
  • Reports statistics at regular intervals
  • Tracks error details for better debugging
  • Implements performance metrics tracking
Configuration
  • Interval: How often to report statistics (default: 30s)
  • EnableStats: Whether to enable statistics collection (default: true)
  • EnableAlerts: Whether to enable alerting (default: true)
  • MinSuccessRate: Minimum success rate before alerting (default: 95%)
  • MaxDecodeTime: Maximum average decode time before alerting (default: 100ms)
2. Arbitrage Auditor

The Arbitrage Auditor validates arbitrage opportunities to ensure they are profitable and low-risk.

Features
  • Validates opportunity profitability
  • Calculates risk scores based on probability and inherent risk factors
  • Caches validation results
  • Monitors for expired opportunities
  • Provides validation before execution
  • Implements security metrics tracking
  • Tracks performance metrics for validation operations
3. System Health Auditor

The System Health Auditor monitors the overall health of all system components.

Features
  • Component status tracking (healthy/degraded/unhealthy)
  • Response time monitoring
  • Error detection and reporting
  • Comprehensive system statistics
  • Health check registration for custom components
  • Implements security and performance metrics
  • Maintains audit trails for compliance
4. Audit Manager

The Audit Manager coordinates all auditing activities and provides a unified interface.

Features
  • Centralized control of all auditors
  • Unified statistics access
  • Easy integration with existing components
  • Thread-safe operation
  • Aggregated audit metrics
  • Implements audit framework compliance

Extended Capabilities

Performance Monitoring
  • All auditors now track comprehensive performance metrics
  • Min/Max/Average time calculations
  • Performance trend analysis
  • Resource usage monitoring
Security Tracking
  • Risk event detection and monitoring
  • Invalid opportunities tracking
  • Suspicious activity monitoring
  • Security compliance metrics
Audit Trail and Compliance
  • Complete audit trail logging
  • Compliance with audit framework requirements
  • Detailed event tracking
  • Historical analysis capabilities

Integration

To integrate the auditing system into your application:

  1. Create an AuditManager instance:

    auditConfig := &AuditConfig{
        Interval: 30 * time.Second,
        EnableStats: true,
        EnableAlerts: true,
        MinSuccessRate: 0.90,
        MaxDecodeTime: 200 * time.Millisecond,
    }
    
    auditManager := NewAuditManager(auditConfig)
    
  2. Initialize auditors with system components:

    auditManager.InitializeAuditors(decoder, oracle, arbEngine, executor)
    
  3. Start the auditing system:

    go auditManager.Start(ctx)
    
  4. Use audited operations:

    // Decode with auditing
    actions, err := auditManager.AuditTransaction(txHash, func() ([]types.DecodedAction, error) {
        return decoder.Decode(tx, toAddress)
    })
    
    // Audit an arbitrage opportunity
    validation, err := auditManager.AuditOpportunity(opportunity)
    
    // Validate and execute with auditing
    err := auditManager.ValidateAndExecute(executor, opportunity)
    
  5. Access comprehensive metrics:

    // Get aggregated audit metrics
    metrics := auditManager.GetAuditMetrics()
    
    // Get specific auditor metrics
    decoderStats := auditManager.GetDecoderStats()
    arbitrageStats := auditManager.GetArbitrageStats()
    healthStats := auditManager.GetSystemHealthStats()
    
    // Get security and performance metrics
    decoderAuditor := /* reference to decoder auditor */
    perfMetrics := decoderAuditor.GetPerformanceMetrics()
    

Statistics and Monitoring

Each auditor provides access to extensive statistics:

  • Decoder Stats: Success rates, decode times (avg/min/max), liquidity processed, error details
  • Arbitrage Stats: Validated opportunities, profitability, risk scores
  • System Health Stats: Uptime, active components, transaction volume
  • Component Status: Individual component health status
  • Performance Metrics: Detailed performance tracking per system component
  • Security Metrics: Risk events, invalid opportunities, suspicious activities

Alerts and Notifications

The auditing system provides both internal monitoring and external notification capabilities through channels that can be monitored for audit events. Critical issues trigger alerts that can be integrated with external monitoring systems.

Best Practices

  1. Always initialize auditing before starting the main application logic
  2. Configure appropriate thresholds for your specific use case
  3. Monitor audit statistics regularly to identify performance issues
  4. Use the audit system to detect and respond to failed operations
  5. Implement proper logging to track audit events
  6. Ensure compliance with audit framework requirements
  7. Regularly review audit trails and security metrics
  8. Set up alerts for critical security and performance indicators
  9. Use performance metrics to optimize system efficiency
  10. Maintain audit compliance for regulatory requirements

Documentation

Overview

Package auditing provides auditing agents for the arbitrum-sequencer-decoder system

Package auditing provides auditing agents for the arbitrum-sequencer-decoder system

Package auditing provides auditing agents for the arbitrum-sequencer-decoder system

Package auditing provides examples of how to integrate auditing agents into the arbitrum-sequencer-decoder system

Package auditing provides auditing agents for the arbitrum-sequencer-decoder system

Package auditing provides auditing agents for the arbitrum-sequencer-decoder system

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExampleIntegration

func ExampleIntegration(ctx context.Context, reader *ExampleSequencerReader) error

Example integration of auditing agents with the sequencer reader

Types

type ArbitrageAuditor

type ArbitrageAuditor struct {
	// contains filtered or unexported fields
}

ArbitrageAuditor audits arbitrage opportunities to ensure they are valid and profitable Following the project's audit framework, security guidelines, and performance recommendations

func NewArbitrageAuditor

func NewArbitrageAuditor(arbEngine types.ArbitrageEngine, config *AuditConfig) *ArbitrageAuditor

NewArbitrageAuditor creates a new arbitrage auditor Following security best practices and performance optimization guidelines

func (*ArbitrageAuditor) AuditOpportunity

func (aa *ArbitrageAuditor) AuditOpportunity(opportunity types.ArbitrageOpportunity) (*ValidationResult, error)

AuditOpportunity audits a single arbitrage opportunity Following security best practices and performance monitoring recommendations

func (*ArbitrageAuditor) GetNotificationChannel

func (aa *ArbitrageAuditor) GetNotificationChannel() <-chan AuditEvent

GetNotificationChannel returns the channel for audit notifications

func (*ArbitrageAuditor) GetPerformanceMetrics

func (aa *ArbitrageAuditor) GetPerformanceMetrics() *ArbitragePerformanceMetrics

GetPerformanceMetrics returns performance metrics for monitoring Following performance audit recommendations

func (*ArbitrageAuditor) GetSecurityMetrics

func (aa *ArbitrageAuditor) GetSecurityMetrics() *ArbitrageSecurityMetrics

GetSecurityMetrics returns security metrics for monitoring Following security audit recommendations

func (*ArbitrageAuditor) GetStats

func (aa *ArbitrageAuditor) GetStats() *ArbitrageStats

GetStats returns the current arbitrage statistics

func (*ArbitrageAuditor) Start

func (aa *ArbitrageAuditor) Start(ctx context.Context) error

Start begins auditing arbitrage opportunities in a separate goroutine

func (*ArbitrageAuditor) ValidateAndExecute

func (aa *ArbitrageAuditor) ValidateAndExecute(executor types.TransactionExecutor, opportunity types.ArbitrageOpportunity) error

ValidateAndExecute validates an arbitrage opportunity and executes if valid

type ArbitragePerformanceMetrics

type ArbitragePerformanceMetrics struct {
	MaxValidationTime   time.Duration
	MinValidationTime   time.Duration
	TotalValidationTime time.Duration
	ValidationCount     int64
}

ArbitragePerformanceMetrics holds arbitrage auditor-specific performance metrics

type ArbitrageSecurityMetrics

type ArbitrageSecurityMetrics struct {
	RiskEventsDetected   int64
	InvalidOpportunities int64
	SuspiciousActivities int64
	LastSecurityEvent    time.Time
}

ArbitrageSecurityMetrics holds arbitrage auditor-specific security metrics

type ArbitrageStats

type ArbitrageStats struct {
	TotalOpportunities int64
	Validated          int64
	Invalid            int64
	Executed           int64
	Unprofitable       int64
	Expired            int64
	AvgProfit          *big.Float
	AvgRisk            float64
	LastUpdated        time.Time
}

ArbitrageStats holds statistics about arbitrage opportunities

type AuditConfig

type AuditConfig struct {
	Interval       time.Duration
	EnableStats    bool
	EnableAlerts   bool
	MinSuccessRate float64
	MaxDecodeTime  time.Duration
}

AuditConfig holds configuration for the auditing system

type AuditEvent

type AuditEvent struct {
	Timestamp time.Time
	EventType string
	Decoder   string
	Message   string
	Data      interface{}
	Error     error
}

AuditEvent represents an auditing event

type AuditManager

type AuditManager struct {
	// contains filtered or unexported fields
}

AuditManager coordinates all auditing activities in accordance with the project's audit framework

func NewAuditManager

func NewAuditManager(config *AuditConfig) *AuditManager

NewAuditManager creates a new audit manager that coordinates all auditing agents

func (*AuditManager) AuditOpportunity

func (am *AuditManager) AuditOpportunity(opportunity types.ArbitrageOpportunity) (*ValidationResult, error)

AuditOpportunity audits an arbitrage opportunity Following security and validation best practices

func (*AuditManager) AuditTransaction

func (am *AuditManager) AuditTransaction(txHash string, decodeFunc func() ([]types.DecodedAction, error)) ([]types.DecodedAction, error)

AuditTransaction audits a transaction through the decoder auditor Implements the new audit framework requirements

func (*AuditManager) GetAllComponentStatuses

func (am *AuditManager) GetAllComponentStatuses() map[string]*ComponentStatus

GetAllComponentStatuses returns the status of all components

func (*AuditManager) GetArbitrageStats

func (am *AuditManager) GetArbitrageStats() *ArbitrageStats

GetArbitrageStats returns arbitrage statistics

func (*AuditManager) GetAuditMetrics

func (am *AuditManager) GetAuditMetrics() *AuditMetrics

GetAuditMetrics returns aggregated audit metrics Implements the observability infrastructure recommendations

func (*AuditManager) GetComponentStatus

func (am *AuditManager) GetComponentStatus(componentName string) *ComponentStatus

GetComponentStatus returns the status of a system component

func (*AuditManager) GetDecoderStats

func (am *AuditManager) GetDecoderStats() map[string]*DecoderStats

GetDecoderStats returns decoder statistics

func (*AuditManager) GetSystemHealthStats

func (am *AuditManager) GetSystemHealthStats() *SystemHealthStats

GetSystemHealthStats returns system health statistics

func (*AuditManager) InitializeAuditors

func (am *AuditManager) InitializeAuditors(decoder types.Decoder, oracle types.PoolOracle, arbEngine types.ArbitrageEngine, executor types.TransactionExecutor)

InitializeAuditors sets up all auditing components with their dependencies Following security best practices and performance optimization recommendations

func (*AuditManager) Start

func (am *AuditManager) Start(ctx context.Context) error

Start begins all auditing processes with comprehensive error handling

func (*AuditManager) UpdateSystemStats

func (am *AuditManager) UpdateSystemStats(updateFunc func(*SystemHealthStats))

UpdateSystemStats updates the system health statistics

func (*AuditManager) ValidateAndExecute

func (am *AuditManager) ValidateAndExecute(executor types.TransactionExecutor, opportunity types.ArbitrageOpportunity) error

ValidateAndExecute validates an arbitrage opportunity and executes it if valid Implements security-first approach with multiple validation layers

type AuditMetrics

type AuditMetrics struct {
	StartTime            int64 // Unix timestamp for uptime calculation
	TotalAuditsProcessed int64
	AlertsGenerated      int64
	ErrorsDetected       int64
	PerformanceMetrics   map[string]interface{} // For performance monitoring
}

AuditMetrics holds aggregated metrics from all auditors

type ComponentStatus

type ComponentStatus struct {
	Name         string
	Status       string // "healthy", "degraded", "unhealthy", "unknown"
	LastUpdate   time.Time
	ErrorMessage string
	ResponseTime time.Duration
	LastCheck    time.Time
}

ComponentStatus represents the status of a system component

type DecoderAuditor

type DecoderAuditor struct {
	// contains filtered or unexported fields
}

DecoderAuditor audits the performance and accuracy of the decoder implementations Following the project's audit framework, code quality standards, and security guidelines

func NewDecoderAuditor

func NewDecoderAuditor(decoder types.Decoder, oracle types.PoolOracle, config *AuditConfig) *DecoderAuditor

NewDecoderAuditor creates a new decoder auditor Following security best practices and code quality standards

func (*DecoderAuditor) AuditTransaction

func (da *DecoderAuditor) AuditTransaction(txHash string, decodeFunc func() ([]types.DecodedAction, error)) ([]types.DecodedAction, error)

AuditTransaction audits a single transaction decoding

func (*DecoderAuditor) GetNotificationChannel

func (da *DecoderAuditor) GetNotificationChannel() <-chan AuditEvent

GetNotificationChannel returns the channel for audit notifications

func (*DecoderAuditor) GetPerformanceMetrics

func (da *DecoderAuditor) GetPerformanceMetrics() *DecoderPerformanceMetrics

GetPerformanceMetrics returns performance metrics for monitoring Following the performance monitoring recommendations

func (*DecoderAuditor) GetStats

func (da *DecoderAuditor) GetStats() map[string]*DecoderStats

GetStats returns the current statistics for all decoders Following code quality and security recommendations

func (*DecoderAuditor) Start

func (da *DecoderAuditor) Start(ctx context.Context) error

Start begins auditing in a separate goroutine

type DecoderPerformanceMetrics

type DecoderPerformanceMetrics struct {
	MaxDecodeTime   time.Duration
	MinDecodeTime   time.Duration
	TotalDecodeTime time.Duration
	DecodeCount     int64
}

DecoderPerformanceMetrics holds decoder-specific performance metrics

type DecoderStats

type DecoderStats struct {
	TotalDecoded   int64
	TotalFailed    int64
	AvgDecodeTime  time.Duration
	LastDecodeTime time.Duration
	SuccessRate    float64
	LastUpdated    time.Time
	TotalLiquidity *big.Int      // Track estimated liquidity processed (using big.Int to prevent overflow)
	MaxDecodeTime  time.Duration // Following performance metrics tracking
	MinDecodeTime  time.Duration // Following performance metrics tracking
	ErrorDetails   []string      // For enhanced error tracking
}

DecoderStats holds statistics about a decoder's performance Updated to follow code quality and audit framework recommendations

type ExampleSequencerReader

type ExampleSequencerReader struct {
	// contains filtered or unexported fields
}

ExampleSequencerReader is a simplified example of how the sequencer reader might look with auditing

func (*ExampleSequencerReader) GetAuditStats

func (r *ExampleSequencerReader) GetAuditStats() map[string]interface{}

GetAuditStats returns current audit statistics

func (*ExampleSequencerReader) Start

Start the sequencer reader with auditing capabilities

type HealthCheckFunc

type HealthCheckFunc func() (bool, error, time.Duration)

HealthCheckFunc is a function that performs a health check

type PerformanceMetrics

type PerformanceMetrics struct {
	MaxTime   time.Duration
	MinTime   time.Duration
	TotalTime time.Duration
	Count     int64
}

PerformanceMetrics holds performance-related metrics (shared across auditors)

func NewPerformanceMetrics

func NewPerformanceMetrics() *PerformanceMetrics

NewPerformanceMetrics creates a new PerformanceMetrics with default values

func (*PerformanceMetrics) AverageTime

func (pm *PerformanceMetrics) AverageTime() time.Duration

AverageTime returns the average time or 0 if no measurements

func (*PerformanceMetrics) Copy

Copy creates a deep copy of PerformanceMetrics

func (*PerformanceMetrics) Update

func (pm *PerformanceMetrics) Update(duration time.Duration)

Update updates the performance metrics with a new measurement

type SecurityMetrics

type SecurityMetrics struct {
	RiskEventsDetected   int64
	InvalidOpportunities int64
	SuspiciousActivities int64
	LastSecurityEvent    time.Time
}

SecurityMetrics holds security-related metrics (shared across auditors)

func NewSecurityMetrics

func NewSecurityMetrics() *SecurityMetrics

NewSecurityMetrics creates a new SecurityMetrics with default values

func (*SecurityMetrics) Copy

func (sm *SecurityMetrics) Copy() *SecurityMetrics

Copy creates a deep copy of SecurityMetrics

type SystemHealthAuditor

type SystemHealthAuditor struct {
	// contains filtered or unexported fields
}

SystemHealthAuditor monitors the overall health of the system Following the project's audit framework, security guidelines, and performance recommendations

func NewSystemHealthAuditor

func NewSystemHealthAuditor(config *AuditConfig) *SystemHealthAuditor

NewSystemHealthAuditor creates a new system health auditor Following security best practices and performance optimization guidelines

func (*SystemHealthAuditor) GetAllComponentStatuses

func (sha *SystemHealthAuditor) GetAllComponentStatuses() map[string]*ComponentStatus

GetAllComponentStatuses returns the status of all components

func (*SystemHealthAuditor) GetAuditTrail

func (sha *SystemHealthAuditor) GetAuditTrail() []AuditEvent

GetAuditTrail returns the audit trail for review Following audit framework recommendations

func (*SystemHealthAuditor) GetComponentStatus

func (sha *SystemHealthAuditor) GetComponentStatus(componentName string) *ComponentStatus

GetComponentStatus returns the status of a specific component

func (*SystemHealthAuditor) GetNotificationChannel

func (sha *SystemHealthAuditor) GetNotificationChannel() <-chan AuditEvent

GetNotificationChannel returns the channel for audit notifications

func (*SystemHealthAuditor) GetPerformanceMetrics

func (sha *SystemHealthAuditor) GetPerformanceMetrics() *SystemHealthPerformanceMetrics

GetPerformanceMetrics returns performance metrics for monitoring Following performance audit recommendations

func (*SystemHealthAuditor) GetSecurityMetrics

func (sha *SystemHealthAuditor) GetSecurityMetrics() *SystemHealthSecurityMetrics

GetSecurityMetrics returns security metrics for monitoring Following security audit recommendations

func (*SystemHealthAuditor) GetStats

func (sha *SystemHealthAuditor) GetStats() *SystemHealthStats

GetStats returns the current system health statistics

func (*SystemHealthAuditor) MonitorArbitrageEngine

func (sha *SystemHealthAuditor) MonitorArbitrageEngine(engine types.ArbitrageEngine)

MonitorArbitrageEngine adds health monitoring for an ArbitrageEngine component

func (*SystemHealthAuditor) MonitorDecoder

func (sha *SystemHealthAuditor) MonitorDecoder(decoder types.Decoder)

MonitorDecoder adds health monitoring for a Decoder component

func (*SystemHealthAuditor) MonitorPoolOracle

func (sha *SystemHealthAuditor) MonitorPoolOracle(oracle types.PoolOracle)

MonitorPoolOracle adds health monitoring for a PoolOracle component

func (*SystemHealthAuditor) MonitorTransactionExecutor

func (sha *SystemHealthAuditor) MonitorTransactionExecutor(executor types.TransactionExecutor)

MonitorTransactionExecutor adds health monitoring for a TransactionExecutor component

func (*SystemHealthAuditor) RegisterHealthCheck

func (sha *SystemHealthAuditor) RegisterHealthCheck(componentName string, checkFunc HealthCheckFunc)

RegisterHealthCheck registers a health check function for a component

func (*SystemHealthAuditor) Start

func (sha *SystemHealthAuditor) Start(ctx context.Context) error

Start begins auditing system health in a separate goroutine

func (*SystemHealthAuditor) UpdateStats

func (sha *SystemHealthAuditor) UpdateStats(updateFunc func(*SystemHealthStats))

UpdateStats updates the system health statistics

type SystemHealthPerformanceMetrics

type SystemHealthPerformanceMetrics struct {
	MaxCheckTime   time.Duration
	MinCheckTime   time.Duration
	TotalCheckTime time.Duration
	CheckCount     int64
}

SystemHealthPerformanceMetrics holds system health-specific performance metrics

type SystemHealthSecurityMetrics

type SystemHealthSecurityMetrics struct {
	RiskEventsDetected   int64
	InvalidOpportunities int64
	SuspiciousActivities int64
	LastSecurityEvent    time.Time
}

SystemHealthSecurityMetrics holds system health-specific security metrics

type SystemHealthStats

type SystemHealthStats struct {
	StartTime           time.Time
	ActiveDecoders      int
	ActivePools         int64
	ActiveOpportunities int64
	TotalTransactions   int64
	AvgLatency          time.Duration
	ErrorRate           float64
	LastHealthCheck     time.Time
}

SystemHealthStats holds statistics about the system's health

type ValidationResult

type ValidationResult struct {
	IsValid        bool
	Profitability  *big.Float
	RiskScore      float64
	Reason         string
	ValidationTime time.Time
	Expiration     time.Time
}

ValidationResult holds the result of validating an arbitrage opportunity

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL