<commit_before>using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Reactive;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Autofac;
using Miningcore.Banning;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.JsonRpc;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using Miningcore.Time;
using Miningcore.Util;
using Newtonsoft.Json;
using NLog;
using Contract = Miningcore.Contracts.Contract;
using static Miningcore.Util.ActionUtils;

namespace Miningcore.Stratum;

public abstract class StratumServer
{
    protected StratumServer(
        IComponentContext ctx,
        IMessageBus messageBus,
        IMasterClock clock)
    {
        Contract.RequiresNonNull(ctx, nameof(ctx));
        Contract.RequiresNonNull(messageBus, nameof(messageBus));
        Contract.RequiresNonNull(clock, nameof(clock));

        this.ctx = ctx;
        this.messageBus = messageBus;
        this.clock = clock;
    }

    static StratumServer()
    {
        if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            ignoredSocketErrors = new HashSet<int>
            {
                (int) SocketError.ConnectionReset,
                (int) SocketError.ConnectionAborted,
                (int) SocketError.OperationAborted
            };
        }

        else if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            // see: http://www.virtsync.com/c-error-codes-include-errno
            ignoredSocketErrors = new HashSet<int>
            {
                104, // ECONNRESET
                125, // ECANCELED
                103, // ECONNABORTED
                110, // ETIMEDOUT
                32,  // EPIPE
            };
        }
    }

    protected readonly ConcurrentDictionary<string, StratumConnection> connections = new();
    protected static readonly ConcurrentDictionary<string, X509Certificate2> certs = new();
    protected static readonly HashSet<int> ignoredSocketErrors;

    protected static readonly MethodBase streamWriterCtor = typeof(StreamWriter).GetConstructor(
        new[] { typeof(Stream), typeof(Encoding), typeof(int), typeof(bool) });

    protected readonly IComponentContext ctx;
    protected readonly IMessageBus messageBus;
    protected readonly IMasterClock clock;
    protected ClusterConfig clusterConfig;
    protected PoolConfig poolConfig;
    protected IBanManager banManager;
    protected ILogger logger;

    protected Task RunAsync(CancellationToken ct, params StratumEndpoint[] endpoints)
    {
        Contract.RequiresNonNull(endpoints, nameof(endpoints));

        logger.Info(() => $"Stratum ports {string.Join(", ", endpoints.Select(x => $"{x.IPEndPoint.Address}:{x.IPEndPoint.Port}").ToArray())} online");

        var tasks = endpoints.Select(port =>
        {
            var server = new Socket(SocketType.Stream, ProtocolType.Tcp);
            server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            server.Bind(port.IPEndPoint);
            server.Listen();

            return Task.Run(()=> Listen(server, port, ct), ct);
        }).ToArray();

        return Task.WhenAll(tasks);
    }

    private async Task Listen(Socket server, StratumEndpoint port, CancellationToken ct)
    {
        var cert = GetTlsCert(port);

        while(!ct.IsCancellationRequested)
        {
            try
            {
                var socket = await server.AcceptAsync();

                AcceptConnection(socket, port, cert, ct);
            }

            catch(ObjectDisposedException)
            {
                // ignored
                break;
            }

            catch(Exception ex)
            {
                logger.Error(ex);
            }
        }
    }

    private void AcceptConnection(Socket socket, StratumEndpoint port, X509Certificate2 cert, CancellationToken ct)
    {
        Task.Run(() => Guard(() =><commit_msg>Pass cancellation token<commit_after>using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Reactive;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Autofac;
using Miningcore.Banning;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.JsonRpc;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using Miningcore.Time;
using Miningcore.Util;
using Newtonsoft.Json;
using NLog;
using Contract = Miningcore.Contracts.Contract;
using static Miningcore.Util.ActionUtils;

namespace Miningcore.Stratum;

public abstract class StratumServer
{
    protected StratumServer(
        IComponentContext ctx,
        IMessageBus messageBus,
        IMasterClock clock)
    {
        Contract.RequiresNonNull(ctx, nameof(ctx));
        Contract.RequiresNonNull(messageBus, nameof(messageBus));
        Contract.RequiresNonNull(clock, nameof(clock));

        this.ctx = ctx;
        this.messageBus = messageBus;
        this.clock = clock;
    }

    static StratumServer()
    {
        if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            ignoredSocketErrors = new HashSet<int>
            {
                (int) SocketError.ConnectionReset,
                (int) SocketError.ConnectionAborted,
                (int) SocketError.OperationAborted
            };
        }

        else if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            // see: http://www.virtsync.com/c-error-codes-include-errno
            ignoredSocketErrors = new HashSet<int>
            {
                104, // ECONNRESET
                125, // ECANCELED
                103, // ECONNABORTED
                110, // ETIMEDOUT
                32,  // EPIPE
            };
        }
    }

    protected readonly ConcurrentDictionary<string, StratumConnection> connections = new();
    protected static readonly ConcurrentDictionary<string, X509Certificate2> certs = new();
    protected static readonly HashSet<int> ignoredSocketErrors;

    protected static readonly MethodBase streamWriterCtor = typeof(StreamWriter).GetConstructor(
        new[] { typeof(Stream), typeof(Encoding), typeof(int), typeof(bool) });

    protected readonly IComponentContext ctx;
    protected readonly IMessageBus messageBus;
    protected readonly IMasterClock clock;
    protected ClusterConfig clusterConfig;
    protected PoolConfig poolConfig;
    protected IBanManager banManager;
    protected ILogger logger;

    protected Task RunAsync(CancellationToken ct, params StratumEndpoint[] endpoints)
    {
        Contract.RequiresNonNull(endpoints, nameof(endpoints));

        logger.Info(() => $"Stratum ports {string.Join(", ", endpoints.Select(x => $"{x.IPEndPoint.Address}:{x.IPEndPoint.Port}").ToArray())} online");

        var tasks = endpoints.Select(port =>
        {
            var server = new Socket(SocketType.Stream, ProtocolType.Tcp);
            server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            server.Bind(port.IPEndPoint);
            server.Listen();

            return Task.Run(()=> Listen(server, port, ct), ct);
        }).ToArray();

        return Task.WhenAll(tasks);
    }

    private async Task Listen(Socket server, StratumEndpoint port, CancellationToken ct)
    {
        var cert = GetTlsCert(port);

        while(!ct.IsCancellationRequested)
        {
            try
            {
                var socket = await server.AcceptAsync(ct);

                AcceptConnection(socket, port, cert, ct);
            }

            catch(OperationCanceledException)
            {
                // ignored
                break;
            }

            catch(ObjectDisposedException)
            {
                // ignored
                break;
            }

            catch(Exception ex)
            {
                logger.Error(ex);
            }
        }
    }

    private void AcceptConnection(Socket socket, StratumEndpoint port, X509Certificate2 cert, CancellationToken ct)
    {
        Task.Run(() => Guard(() =>
{'fraction_non_alphanumeric': 0.09173326971251342, 'fraction_numerical': 0.005964451866873434, 'mean_word_length': 2.4445357436318815, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2635716', 'n_tokens_mistral': 2283, 'n_tokens_neox': 2164, 'n_words': 473}