Skip to content

Add exception handling and retry logic for P2P network services#4

Draft
Copilot wants to merge 5 commits intomainfrom
copilot/fix-font-loading-issues
Draft

Add exception handling and retry logic for P2P network services#4
Copilot wants to merge 5 commits intomainfrom
copilot/fix-font-loading-issues

Conversation

Copy link
Contributor

Copilot AI commented Jan 20, 2026

The application was experiencing unhandled exceptions across font loading, SQLite operations, Bitcoin testnet3 P2P connections, IPFS engine initialization, and async operation cancellation. These caused startup crashes and prevented network connectivity.

Changes

Font Configuration

  • Removed references to missing OpenSans fonts; use default MAUI fonts

SQLite Operations

  • Wrapped all database operations in try-catch with logging
  • Directory creation before initialization
  • Retry logic with exponential backoff (3 attempts, 1-2-4 second delays)
  • Proper exception propagation on final failure

Bitcoin P2P Network

  • Socket exception handling with detailed error codes
  • Connection retry with exponential backoff (5 attempts, 2-4-8-16-32 second delays)
  • 30-second connection timeout with cancellation token support
  • Automatic reconnection on peer disconnect
  • Disposal state tracking to prevent use-after-dispose

IPFS P2P Network

  • Engine startup timeout (30s) with HTTP client fallback on failure
  • Per-operation timeouts: 60s downloads, 5s peer connections, 10s status checks
  • Repository directory creation before initialization
  • Graceful shutdown with 5-second timeout
  • Disposal state tracking

Operation Lifecycle

  • Cancellation token propagation throughout async chains
  • ObjectDisposedException guards before operations
  • Removed redundant cancellation checks in foreach loops

Code Quality

  • Extracted all timeout/retry values as named constants
  • Optimized exponential backoff using bit shifting ((1 << attempt) * baseDelay)

Example

Before:

private void InitializeP2PConnection()
{
    var parameters = new NodeConnectionParameters();
    _nodesGroup = new NodesGroup(_network, parameters);
    _nodesGroup.Connect();  // Throws unhandled SocketException
}

After:

private async Task ConnectWithRetryAsync(CancellationToken cancellationToken)
{
    int attempt = 0;
    while (attempt < MaxConnectionRetries && !cancellationToken.IsCancellationRequested)
    {
        try
        {
            _nodesGroup.Connect();
            await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
            if (_nodesGroup.ConnectedNodes.Count > 0) return;
        }
        catch (SocketException ex)
        {
            Console.WriteLine($"Socket error (attempt {attempt + 1}): {ex.Message}");
        }
        
        if (attempt < MaxConnectionRetries - 1)
        {
            var delay = TimeSpan.FromSeconds((1 << attempt) * RetryBackoffBaseSeconds);
            await Task.Delay(delay, cancellationToken);
        }
        attempt++;
    }
}

All services now gracefully degrade when connections fail, with status accurately reflected in the UI.

Original prompt

Problem Description

The SupStick application is experiencing multiple critical exceptions that are causing the Bitcoin testnet3 to fail to connect while IPFS shows intermittent connectivity issues.

Exceptions to Fix

1. Font Loading Issues

Priority: Medium

The application is failing to load the OpenSansRegular font with the following errors:

Microsoft.Maui.FontRegistrar: Warning: Unable to load font 'OpenSansRegular'.
System.IO.FileNotFoundException: Native font with the name OpenSans-Regular.ttf was not found.

Microsoft.Maui.FontManager: Error: Error loading font 'Assets/Fonts/OpenSansRegular.ttf'.
System.InvalidOperationException: This operation is not supported for a relative URI.

Fix Required:

  • Verify that OpenSans-Regular.ttf and OpenSansRegular.otf exist in the Assets/Fonts/ directory
  • Fix the font path configuration in MauiProgram.cs to use absolute paths or proper embedded resource paths
  • Update the .csproj file to ensure fonts are included as MauiFont resources with the correct build action
  • Consider using the default MAUI fonts if custom fonts are not essential

2. SQLite Database Exceptions

Priority: High

Multiple SQLite exceptions are being thrown:

Exception thrown: 'System.Exception' in SQLite-net.dll
Exception thrown: 'SQLite.SQLiteException' in SQLite-net.dll

Fix Required:

  • Add proper exception handling and logging around all SQLite database operations
  • Verify database file path and ensure the directory exists before attempting to create/open the database
  • Add database initialization checks and handle schema migration issues
  • Implement retry logic with exponential backoff for database operations
  • Ensure the database connection is properly disposed in finally blocks or using statements

3. Network Socket Exceptions - Bitcoin Testnet3

Priority: Critical

Numerous socket exceptions are preventing Bitcoin testnet3 connectivity:

Exception thrown: 'System.Net.Sockets.SocketException' in System.Net.Sockets.dll
Exception thrown: 'System.Net.Sockets.SocketException' in NBitcoin.dll

Fix Required:

  • Add proper exception handling for socket connection failures in Bitcoin connection code
  • Implement connection retry logic with exponential backoff for Bitcoin testnet3 nodes
  • Add connection timeout configuration
  • Verify Bitcoin testnet3 node addresses are correct and reachable
  • Add fallback nodes in case primary nodes are unavailable
  • Implement proper cancellation token handling to prevent ObjectDisposedException
  • Add connection state validation before attempting network operations

4. IPFS Engine Exceptions

Priority: High

IPFS engine is throwing exceptions:

Exception thrown: 'System.Exception' in Ipfs.Engine.dll

Fix Required:

  • Add detailed exception handling and logging in IPFS initialization and connection code
  • Ensure IPFS configuration is valid and repository path exists
  • Handle peer discovery failures gracefully
  • Add timeout handling for IPFS operations
  • Implement retry mechanism for IPFS node startup

5. Operation Cancellation Issues

Priority: Medium

Multiple OperationCanceledException and ObjectDisposedException:

Exception thrown: 'System.OperationCanceledException' in System.Private.CoreLib.dll
Exception thrown: 'System.ObjectDisposedException' in System.Private.CoreLib.dll
Exception thrown: 'System.OperationCanceledException' in NBitcoin.dll

Fix Required:

  • Properly handle cancellation tokens throughout the application
  • Add try-catch blocks specifically for OperationCanceledException where appropriate
  • Ensure objects are not disposed while operations are in progress
  • Implement proper cleanup in disposal methods
  • Check if objects are disposed before using them

Implementation Guidelines

  1. Error Handling: Wrap all network and database operations in try-catch blocks with proper logging
  2. Logging: Add comprehensive logging to identify exactly where exceptions occur and why
  3. Status Updates: Ensure status page correctly reflects connection states for both Bitcoin testnet3 and IPFS
  4. Graceful Degradation: Application should continue to function even if one service fails to connect
  5. User Feedback: Provide clear error messages to users when services fail to connect

Testing Requirements

  • Test font loading on clean install
  • Verify database creation and access in various scenarios
  • Test Bitcoin testnet3 connectivity with various network conditions
  • Test IPFS connectivity and peer discovery
  • Verify status page correctly shows connection states
  • Test application shutdown and cleanup to ensure no ObjectDisposedExceptions

Success Criteria

  • No unhandled exceptions during startup
  • Fonts load correctly without errors
  • Database operations complete successfully
  • Bitcoin testnet3 shows proper connection status (connected or clear error message)
  • IPFS shows proper connection status
  • Status page accurately refle...

This pull request was created from Copilot chat.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 4 commits January 20, 2026 17:17
Co-authored-by: embiimob <6278950+embiimob@users.noreply.github.com>
Co-authored-by: embiimob <6278950+embiimob@users.noreply.github.com>
Co-authored-by: embiimob <6278950+embiimob@users.noreply.github.com>
Co-authored-by: embiimob <6278950+embiimob@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix font loading issues for SupStick application Add exception handling and retry logic for P2P network services Jan 20, 2026
Copilot AI requested a review from embiimob January 20, 2026 17:29
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

Comments