Beispiel #1
0
        /// <summary>
        /// Set manual affinity, use native function depending of the Operating system.
        /// </summary>
        /// <param name="threadAffinity"></param>
        public static void SetManualAffinity(string threadAffinity)
        {
            try
            {
                ulong handle = Convert.ToUInt64(threadAffinity, 16);

                if (Environment.OSVersion.Platform == PlatformID.Unix) // Linux/UNIX
                {
                    sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref handle);
                }
                else
                {
                    Thread.BeginThreadAffinity();
                    int           threadId = GetCurrentThreadId();
                    ProcessThread thread   = Process.GetCurrentProcess().Threads.Cast <ProcessThread>()
                                             .Single(t => t.Id == threadId);
                    thread.ProcessorAffinity = (IntPtr)handle;
                    SetThreadAffinityMask((IntPtr)threadId, (IntPtr)handle);
                }
            }
            catch (Exception error)
            {
                ClassConsole.WriteLine(
                    "Cannot apply Manual Affinity with: " + threadAffinity + " | Exception: " + error.Message, 3);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Set automatic affinity, use native function depending of the Operating system.
        /// </summary>
        /// <param name="threadIdMining"></param>
        public static void SetAffinity(int threadIdMining)
        {
            try
            {
                if (Environment.OSVersion.Platform == PlatformID.Unix) // Linux/UNIX
                {
                    if (Environment.ProcessorCount > threadIdMining && threadIdMining >= 0)
                    {
                        ulong processorMask = 1UL << threadIdMining;
                        sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref processorMask);
                    }
                }
                else
                {
                    if (Environment.ProcessorCount > threadIdMining && threadIdMining >= 0)
                    {
                        Thread.BeginThreadAffinity();
                        int           threadId = GetCurrentThreadId();
                        ProcessThread thread   = Process.GetCurrentProcess().Threads.Cast <ProcessThread>()
                                                 .Single(t => t.Id == threadId);

                        ulong cpuMask = 1UL << threadIdMining;

                        thread.ProcessorAffinity = (IntPtr)cpuMask;
                        SetThreadAffinityMask((IntPtr)threadIdMining, (IntPtr)cpuMask);
                    }
                }
            }
            catch (Exception error)
            {
                ClassConsole.WriteLine(
                    "Cannot apply Automatic Affinity with thread id: " + threadIdMining + " | Exception: " + error.Message, 3);
            }
        }
Beispiel #3
0
        public static void Connect(string ip)
        {
            IPEndPoint serverEp = new IPEndPoint(IPAddress.Parse(ip), Config.Port);

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            server.ReceiveTimeout = -1;

            ClassConsole.WriteLine("Connecting to seed node " + (seedNodeListNo + 1) + " on address " + Config.SeedNodes[seedNodeListNo] + ":" + Config.Port, "NODE_CLI", Colors.DarkYellow, Colors.Cyan);


            // Connect to the server.
            try { server.Connect(serverEp); }
            catch (Exception)
            {
                // Error connecing to server
                ClassConsole.WriteLine("Could not connect to " + serverEp + "!", "NODE_CLI", Colors.Red, Colors.Cyan);
                if (seedNodeListNo == Config.SeedNodes.Length - 1)
                {
                    seedNodeListNo = 0;
                }
                else
                {
                    seedNodeListNo = seedNodeListNo + 1;
                }
                Connect(Config.SeedNodes[seedNodeListNo]);
                return;
            }

            // Connected
            ClassConsole.WriteLine("Connected to seed node " + (seedNodeListNo + 1) + " on address " + serverEp, "NODE_CLI", Colors.Green, Colors.Cyan);
            WorkWithServer(server);
        }
Beispiel #4
0
        public static void Connection()
        {
            try
            {
                listener = new TcpListener(IPAddress.Any, Config.ApiPort);
                listener.Start();
                ClassConsole.WriteLine("Starting API server on " + IPAddress.Any + ":" + Config.ApiPort, "API", Colors.DarkGreen, Colors.DarkMagenta);
            }
            catch (Exception)
            {
                ClassConsole.WriteLine("Could not start server, port " + Config.ApiPort + " is already used!", "API", Colors.Red, Colors.DarkMagenta);
                return;
            }

            ClassConsole.WriteLine("API server started", "API", Colors.Green, Colors.DarkMagenta);

            while (true)
            {
                TcpClient     tcpClient     = listener.AcceptTcpClient();
                NetworkStream networkStream = tcpClient.GetStream();

                string   request      = ToString(networkStream);
                string[] requestLines = Regex.Split(request, "\r\n");
                string   getRequest   = requestLines[0].Split(' ')[1];

                // Send Request Header
                StringBuilder responseBuilder = new StringBuilder();
                responseBuilder.AppendLine(@"HTTP/1.1 200 OK");
                responseBuilder.AppendLine(@"Content-Type: application/json");
                responseBuilder.AppendLine(@"");

                // Api Requests
                if (getRequest == ApiRequests.GET_STATUS)
                {
                    ApiStatus getStatus = new ApiStatus();
                    getStatus.version = Config.CoinNetworkVersion;
                    getStatus.result  = "error";
                    responseBuilder.AppendLine(JsonConvert.SerializeObject(getStatus));
                }
                else if (getRequest == "/favicon.ico")
                {
                }
                else
                {
                    ApiError apiError = new ApiError();
                    apiError.version = Config.CoinNetworkVersion;
                    apiError.result  = "error";
                    responseBuilder.AppendLine(JsonConvert.SerializeObject(apiError));
                }

                byte[] sendBytes = enc.GetBytes(responseBuilder.ToString());
                networkStream.Write(sendBytes, 0, sendBytes.Length);

                networkStream.Close();
                tcpClient.Close();
            }
        }
Beispiel #5
0
        static void Process(Socket client)
        {
            ClassConsole.SetTitle(connections);
            ClassConsole.WriteLine("Node connected from address " + client.RemoteEndPoint, "NODE_SRV", Colors.DarkGreen, Colors.DarkCyan);

            const int maxMessageSize = 1024;

            byte[] response;
            int    received;

            //client.Send(Encoding.ASCII.GetBytes("FromServer7"));

            while (true)
            {
                // Receive message from the server:
                response = new byte[maxMessageSize];
                received = client.Receive(response);

                List <byte> respBytesList = new List <byte>(response);
                respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
                if (Encoding.ASCII.GetString(respBytesList.ToArray()) == "")
                {
                    connections = (connections - 1);
                    ClassConsole.SetTitle(connections);
                    ClassConsole.WriteLine("Node disconnected from address " + client.RemoteEndPoint, "NODE_SRV", Colors.DarkGreen, Colors.DarkCyan);
                    client.Close();
                    return;
                }
                else
                {
                    ClassConsole.WriteLine("[" + client.RemoteEndPoint + "] " + Encoding.ASCII.GetString(respBytesList.ToArray()), "NODE_SRV", Colors.DarkBlue, Colors.DarkCyan);
                }
            }

            /*while (true)
             * {
             *
             *  // Send message to the client:
             *  client.Send(Encoding.ASCII.GetBytes("FromServer"));
             *
             *  // Receive message from the server:
             *  response = new byte[maxMessageSize];
             *  received = client.Receive(response);
             *
             *  List<byte> respBytesList = new List<byte>(response);
             *  respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
             *  Console.WriteLine("[SRV] [" + client.RemoteEndPoint + "] Client->Server: " + Encoding.ASCII.GetString(respBytesList.ToArray()));
             * }*/
        }
Beispiel #6
0
        public static void Open()
        {
            int backlog = -1, port = Config.Port;

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            server.ReceiveTimeout = -1;

            // Start listening.
            try
            {
                ClassConsole.WriteLine("Starting node server on address " + IPAddress.Any + ":" + Config.Port, "NODE_SRV", Colors.DarkGreen, Colors.DarkCyan);
                server.Bind(new IPEndPoint(IPAddress.Any, port));
                server.Listen(backlog);
            }
            catch (Exception)
            {
                ClassConsole.WriteLine("Could not start server, port " + Config.Port + " is already used!", "NODE_SRV", Colors.Red, Colors.DarkCyan);
                return;
            }

            ClassConsole.WriteLine("Node server started", "NODE_SRV", Colors.Green, Colors.DarkCyan);

            while (true)
            {
                // If connection is made with client
                Socket client = server.Accept();
                new System.Threading.Thread(() => {
                    try
                    {
                        clientSockets.Add(client); connections = (connections + 1);
                        Process(client);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message == "An existing connection was forcibly closed by the remote host.")
                        {
                            connections = (connections - 1);
                            ClassConsole.SetTitle(connections);
                            ClassConsole.WriteLine("Node disconnected from address " + client.RemoteEndPoint, "NODE_SRV", Colors.DarkGreen, Colors.DarkCyan);
                        }
                        else
                        {
                            ClassConsole.WriteLine("Client connection processing error: " + ex.Message, "NODE_SRV", Colors.Red, Colors.DarkCyan);
                        }
                    }
                }).Start();
            }
        }
        public static void BlockchainCheckData()
        {
            // Check if database directory exists
            if (!Directory.Exists("Blockchain"))
            {
                // If not, create it
                Directory.CreateDirectory("Blockchain");
                ClassConsole.WriteLine("Blockchain directory has been created", "BLOCKCHAIN", Colors.DarkGreen, Colors.Yellow);
            }
            else
            {
                // If it is, message and next step
                ClassConsole.WriteLine("Blockchain directory exists", "BLOCKCHAIN", Colors.DarkGreen, Colors.Yellow);

                if (File.Exists("Blockchain/" + Config.BlockchainBlocksDatabase))
                {
                    ClassConsole.WriteLine("Database file '" + Config.BlockchainBlocksDatabase + "' exists", "BLOCKCHAIN", Colors.Green, Colors.Yellow);
                }
                else
                {
                    using (var blocksFile = new StreamWriter("Blockchain/" + Config.BlockchainBlocksDatabase, true))
                    {
                        StringBuilder kevin = new StringBuilder();
                        kevin.Append("{ \"1\": \"BLOCKNO1\" }");
                        blocksFile.WriteLine(kevin.ToString());
                    }
                }

                if (File.Exists("Blockchain/" + Config.BlockchainTransactionsDatabase))
                {
                    ClassConsole.WriteLine("Database file '" + Config.BlockchainTransactionsDatabase + "' exists", "BLOCKCHAIN", Colors.Green, Colors.Yellow);
                }
                else
                {
                    using (var transactionsFile = new StreamWriter("Blockchain/" + Config.BlockchainTransactionsDatabase, true))
                    {
                        transactionsFile.WriteLine("The next line!");
                    }
                }
            }
        }