static public void start() { // Initialize the crypto manager CryptoManager.initLib(); // Prepare the wallet string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); walletStorage = new WalletStorage(Path.Combine(path, Config.walletFile)); // Initialize the wallet state walletState = new WalletState(); // Prepare the local storage localStorage = new SPIXI.Storage.LocalStorage(); // Read the account file localStorage.readAccountFile(); // Start the network queue NetworkQueue.start(); // Prepare the stream processor StreamProcessor.initialize(); // Start the keepalive thread PresenceList.startKeepAlive(); // Setup a timer to handle routine updates mainLoopTimer = new System.Timers.Timer(2500); mainLoopTimer.Elapsed += new ElapsedEventHandler(onUpdate); mainLoopTimer.Start(); }
static public void stop() { if (!running) { return; } running = false; customAppManager.stop(); // Stop TIV tiv.stop(); // Stop the transfer manager TransferManager.stop(); // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the loop timer if (mainLoopTimer != null) { mainLoopTimer.Stop(); mainLoopTimer = null; } // Stop the network queue NetworkQueue.stop(); NetworkClientManager.stop(); StreamClientManager.stop(); // Stop the stream processor StreamProcessor.uninitialize(); }
static public void start() { // Generate presence list PresenceList.init(IxianHandler.publicIP, 0, 'C'); // Prepare the local storage localStorage = new SPIXI.Storage.LocalStorage(Config.spixiUserFolder); // Read the account file localStorage.readAccountFile(); // Start the network queue NetworkQueue.start(); // Prepare the stream processor StreamProcessor.initialize(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the transfer manager TransferManager.start(); startCounter++; // Setup a timer to handle routine updates mainLoopTimer = new System.Timers.Timer(2500); mainLoopTimer.Elapsed += new ElapsedEventHandler(onUpdate); mainLoopTimer.Start(); }
static public void stop() { Program.noStart = true; forceShutdown = true; ConsoleHelpers.forceShutdown = true; // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the block processor blockProcessor.stopOperation(); // Stop the block sync blockSync.stop(); // Stop the API server if (apiServer != null) { apiServer.stop(); apiServer = null; } // Stop the miner if (miner != null) { miner.stop(); miner = null; } if (maintenanceThread != null) { maintenanceThread.Abort(); maintenanceThread = null; } // Stop the block storage Storage.stopStorage(); // stop activity storage ActivityStorage.stopStorage(); // Stop the network queue NetworkQueue.stop(); // Stop all network clients NetworkClientManager.stop(); // Stop the network server NetworkServer.stopNetworkOperations(); // Stop the console stats screen // Console screen has a thread running even if we are in verbose mode statsConsoleScreen.stop(); NetDump.Instance.shutdown(); presenceListActive = false; }
/// <summary> /// Reads a protocol message from the specified byte-field and calls appropriate methods to process this message. /// </summary> /// <remarks> /// This function checks all applicable checksums and validates that the message is complete before calling one of the specialized /// methods to handle actual decoding and processing. /// </remarks> /// <param name="recv_buffer">Byte-field with an Ixian protocol message.</param> /// <param name="endpoint">Remote endpoint from where the message was received.</param> public static void readProtocolMessage(QueueMessageRaw raw_message, MessagePriority priority, RemoteEndpoint endpoint) { if (endpoint == null) { Logging.error("Endpoint was null. readProtocolMessage"); return; } ProtocolMessageCode code = raw_message.code; // Filter messages if (endpoint.presence == null) { // Check for presence and only accept hello and bye messages if there is no presence. if (code != ProtocolMessageCode.hello && code != ProtocolMessageCode.helloData && code != ProtocolMessageCode.bye) { return; } } if (raw_message.legacyChecksum != null) { // Compute checksum of received data byte[] local_checksum = Crypto.sha512sqTrunc(raw_message.data, 0, 0, 32); // Verify the checksum before proceeding if (local_checksum.SequenceEqual(raw_message.legacyChecksum) == false) { Logging.error("Dropped message (invalid legacy checksum)"); return; } } else { // Compute checksum of received data uint local_checksum = Crc32CAlgorithm.Compute(raw_message.data); // Verify the checksum before proceeding if (local_checksum != raw_message.checksum) { Logging.error("Dropped message (invalid checksum)"); return; } } // Can proceed to parse the data parameter based on the protocol message code. // Data can contain multiple elements. //parseProtocolMessage(code, data, socket, endpoint); NetworkQueue.receiveProtocolMessage(code, raw_message.data, Crc32CAlgorithm.Compute(raw_message.data), priority, endpoint); }
static public void stop() { IxianHandler.forceShutdown = true; // Stop TIV tiv.stop(); // Stop the network queue NetworkQueue.stop(); // Stop all network clients NetworkClientManager.stop(); }
public void start() { PresenceList.init(IxianHandler.publicIP, 0, 'C'); // Start the network queue NetworkQueue.start(); // Start the network client manager NetworkClientManager.start(); // Start the keepalive thread //PresenceList.startKeepAlive(); }
static public void reconnect() { // Reset the network receive queue NetworkQueue.reset(); // Check for test client mode if (Config.isTestClient) { TestClientNode.reconnect(); return; } // Reconnect server and clients NetworkServer.restartNetworkOperations(); NetworkClientManager.restartClients(); }
public void start(bool verboseConsoleOutput) { // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, 'R'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); // Prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Check for test client mode if (Config.isTestClient) { TestClientNode.start(); return; } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); }
static public void stop() { Program.noStart = true; IxianHandler.forceShutdown = true; // Stop TIV tiv.stop(); // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the API server if (apiServer != null) { apiServer.stop(); apiServer = null; } if (maintenanceThread != null) { maintenanceThread.Abort(); maintenanceThread = null; } ActivityStorage.stopStorage(); // Stop the network queue NetworkQueue.stop(); // Check for test client mode if (Config.isTestClient) { TestClientNode.stop(); return; } // Stop all network clients NetworkClientManager.stop(); // Stop the network server NetworkServer.stopNetworkOperations(); // Stop the console stats screen // Console screen has a thread running even if we are in verbose mode statsConsoleScreen.stop(); }
static public void stop() { // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the loop timer mainLoopTimer.Stop(); // Stop the network queue NetworkQueue.stop(); NetworkClientManager.stop(); StreamClientManager.stop(); // Stop the stream processor StreamProcessor.uninitialize(); }
public void Login(string username, string password, executeLogin_onCompleteCallback cb) { string url = Mobage.GetEnvironmentUrl(GameClient.appId) + "/session"; NetworkQueue.Request req = new NetworkQueue.Request(url, "POST"); req.headers.Add("Accept", "application/json"); req.body = "gamertag=" + username + "&password="******"&id=012d521f-bc7f-40de-9124-2aa99b9bd334" + "&device_type=iPhone" + "&os_version=3.0" + "&local=en"; req.profile = false; req.trace = false; req.Callback(delegate(NetworkQueue.Response res) { if (res.error != null) { cb(0, new Error(res.error)); return; } JsonData json = JsonMapper.ToObject(res.bodyString); if (!json.Contains("success") || !json.Contains("oauth_token") || !json.Contains("oauth_secret")) { cb(0, new Error("Missing fields from server response")); return; } if (json["success"].GetBoolean() != true) { cb(0, new Error("Success is false")); return; } this.oauthToken = json["oauth_token"].GetString(); this.oauthTokenSecret = json["oauth_secret"].GetString(); cb(0, null); }); NetworkQueue net = NetworkQueue.instance; net.Enqueue(req); }
static public void stop() { Program.noStart = true; IxianHandler.forceShutdown = true; // Stop TIV tiv.stop(); // Stop the keepalive thread //PresenceList.stopKeepAlive(); // Stop the network queue NetworkQueue.stop(); // Stop all network clients NetworkClientManager.stop(); }
static public void synchronize() { // Clear everything and force a resynchronization Logging.info("\n\n\tSynchronizing to network...\n"); blockProcessor.stopOperation(); blockProcessor = new BlockProcessor(); blockChain = new BlockChain(); walletState.clear(); TransactionPool.clear(); NetworkQueue.stop(); NetworkQueue.start(); // Finally, reconnect to the network CoreNetworkUtils.reconnect(); }
static public void start(bool verboseConsoleOutput) { // Network configuration NetworkUtils.configureNetwork(); PresenceList.generatePresenceList(Config.publicServerIP, 'R'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); // Start the HTTP JSON API server apiServer = new APIServer(); // Prepare stats screen Config.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (Config.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Check for test client mode if (Config.isTestClient) { TestClientNode.start(); return; } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); }
static public void start() { if (running) { return; } running = true; // Generate presence list PresenceList.init(IxianHandler.publicIP, 0, 'C'); // Start local storage localStorage.start(); // Start the network queue NetworkQueue.start(); // Prepare the stream processor StreamProcessor.initialize(); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the transfer manager TransferManager.start(); // Start TIV tiv.start(); customAppManager.start(); startCounter++; // Setup a timer to handle routine updates mainLoopTimer = new System.Timers.Timer(2500); mainLoopTimer.Elapsed += new ElapsedEventHandler(onUpdate); mainLoopTimer.Start(); // Set the identifier tag string tag = Base58Check.Base58CheckEncoding.EncodePlain(IxianHandler.getWalletStorage().getPrimaryAddress()); DependencyService.Get <IPushService>().setTag(tag); }
static public void stop() { if (!running) { Logging.stop(); IxianHandler.status = NodeStatus.stopped; return; } Logging.info("Stopping node..."); running = false; // Stop the stream processor StreamProcessor.uninitialize(); localStorage.stop(); customAppManager.stop(); // Stop TIV tiv.stop(); // Stop the transfer manager TransferManager.stop(); // Stop the keepalive thread PresenceList.stopKeepAlive(); // Stop the network queue NetworkQueue.stop(); NetworkClientManager.stop(); StreamClientManager.stop(); UpdateVerify.stop(); IxianHandler.status = NodeStatus.stopped; Logging.info("Node stopped"); Logging.stop(); }
static public void reconnect() { // Reconnect server and clients presenceListActive = false; // Reset the network receive queue NetworkQueue.reset(); if (!Node.isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); NetworkServer.stopNetworkOperations(); } else { NetworkServer.restartNetworkOperations(); } NetworkClientManager.restartClients(); }
public void start() { PresenceList.init(IxianHandler.publicIP, 0, 'C'); // Start the network queue NetworkQueue.start(); // Start the network client manager NetworkClientManager.start(2); // Start TIV if (generatedNewWallet || !File.Exists(Config.walletFile)) { generatedNewWallet = false; tiv.start(""); } else { tiv.start("", 0, null); } }
static public bool update() { if (serverStarted == false) { /*if(Node.blockProcessor.operating == true) * {*/ Logging.info("Starting Network Server now."); // Start the node server if (!isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); } else { NetworkServer.beginNetworkOperations(); } serverStarted = true; //} } // Check for node deprecation if (checkCurrentBlockDeprecation(Node.blockChain.getLastBlockNum()) == false) { ConsoleHelpers.verboseConsoleOutput = true; Logging.consoleOutput = true; shutdownMessage = string.Format("Your DLT node can only handle blocks up to #{0}. Please update to the latest version from www.ixian.io", Config.nodeDeprecationBlock); Logging.error(shutdownMessage); IxianHandler.forceShutdown = true; running = false; return(running); } // Check for sufficient node balance if (checkMasternodeBalance() == false) { //running = false; } TimeSpan last_isolate_time_diff = DateTime.UtcNow - lastIsolateTime; if (Node.blockChain.getTimeSinceLastBLock() > 900 && (last_isolate_time_diff.TotalSeconds < 0 || last_isolate_time_diff.TotalSeconds > 1800)) // if no block for over 900 seconds with cooldown of 1800 seconds { CoreNetworkUtils.isolate(); lastIsolateTime = DateTime.UtcNow; } // TODO TODO TODO TODO this is a global flood control and should be also done per node to detect attacks // I propose getting average traffic from different types of nodes and detect a node that's sending // disproportionally more messages than the other nodes, provided thatthe network queue is over a certain limit int total_queued_messages = NetworkQueue.getQueuedMessageCount() + NetworkQueue.getTxQueuedMessageCount(); if (floodPause == false && total_queued_messages > 5000) { Logging.warn("Flooding detected, isolating the node."); NetworkClientManager.stop(); if (isMasterNode()) { NetworkServer.stopNetworkOperations(); } floodPause = true; } else if (floodPause == true && total_queued_messages < 100) { Logging.warn("Data after flooding processed, reconnecting the node."); NetworkClientManager.start(); if (isMasterNode()) { NetworkServer.beginNetworkOperations(); } floodPause = false; } return(running); }
// Start the node public void start(bool verboseConsoleOutput) { char node_type = 'M'; // TODO TODO TODO TODO change this to 'W' or 'C' after the upgrade if (Config.disableMiner) { node_type = 'M'; } // Check if we're in worker-only mode if (Config.workerOnly) { // Enable miner Config.disableMiner = false; node_type = 'W'; CoreConfig.simultaneousConnectedNeighbors = 4; } // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, node_type); // Initialize storage Storage.prepareStorage(); ActivityStorage.prepareStorage(); // Initialize the block chain blockChain = new BlockChain(); //runDiffTests(); //return; // Create the block processor and sync blockProcessor = new BlockProcessor(); blockSync = new BlockSync(); if (Config.devInsertFromJson) { Console.WriteLine("Inserting from JSON"); devInsertFromJson(); Program.noStart = true; return; } if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); if (IXICore.Platform.onMono() == false && !Config.disableWebStart) { System.Diagnostics.Process.Start(Config.apiBinds[0]); } miner = new Miner(); // Start the network queue NetworkQueue.start(); // prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Distribute genesis funds IxiNumber genesisFunds = new IxiNumber(Config.genesisFunds); // Check if this is a genesis node if (genesisFunds > (long)0) { Logging.info(String.Format("Genesis {0} specified. Starting operation.", genesisFunds)); distributeGenesisFunds(genesisFunds); genesisNode = true; blockProcessor.resumeOperation(); serverStarted = true; if (!isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); } else { NetworkServer.beginNetworkOperations(); } } else { if (File.Exists(Config.genesisFile)) { Block genesis = new Block(Crypto.stringToHash(File.ReadAllText(Config.genesisFile))); blockChain.setGenesisBlock(genesis); } ulong lastLocalBlockNum = Meta.Storage.getLastBlockNum(); if (lastLocalBlockNum > 6) { lastLocalBlockNum = lastLocalBlockNum - 6; } if (Config.lastGoodBlock > 0 && Config.lastGoodBlock < lastLocalBlockNum) { lastLocalBlockNum = Config.lastGoodBlock; } if (lastLocalBlockNum > 0) { Block b = blockChain.getBlock(lastLocalBlockNum, true); if (b != null) { ConsensusConfig.minRedactedWindowSize = ConsensusConfig.getRedactedWindowSize(b.version); ConsensusConfig.redactedWindowSize = ConsensusConfig.getRedactedWindowSize(b.version); } } if (Config.recoverFromFile) { Block b = Meta.Storage.getBlock(lastLocalBlockNum); blockSync.onHelloDataReceived(b.blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getSignatureCount(), lastLocalBlockNum); } else { ulong blockNum = WalletStateStorage.restoreWalletState(lastLocalBlockNum); if (blockNum > 0) { Block b = blockChain.getBlock(blockNum, true); if (b != null) { blockSync.onHelloDataReceived(blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getSignatureCount(), lastLocalBlockNum); } else { walletState.clear(); } } else { blockSync.lastBlockToReadFromStorage = lastLocalBlockNum; } // Start the server for ping purposes serverStarted = true; if (!isMasterNode()) { Logging.info("Network server is not enabled in modes other than master node."); } else { NetworkServer.beginNetworkOperations(); } // Start the network client manager NetworkClientManager.start(); } } PresenceList.startKeepAlive(); TLC = new ThreadLiveCheck(); // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Name = "Node_Maintenance_Thread"; maintenanceThread.Start(); }
public JsonResponse onStatus(Dictionary <string, object> parameters) { JsonError error = null; Dictionary <string, object> networkArray = new Dictionary <string, object>(); networkArray.Add("Core Version", CoreConfig.version); networkArray.Add("Node Version", CoreConfig.productVersion); networkArray.Add("Network type", IxianHandler.networkType.ToString()); networkArray.Add("My time", Clock.getTimestamp()); networkArray.Add("Network time difference", Clock.networkTimeDifference); networkArray.Add("Real network time difference", Clock.realNetworkTimeDifference); networkArray.Add("My External IP", IxianHandler.publicIP); networkArray.Add("My Listening Port", IxianHandler.publicPort); //networkArray.Add("Listening interface", context.Request.RemoteEndPoint.Address.ToString()); networkArray.Add("Node Deprecation Block Limit", Config.nodeDeprecationBlock); string dltStatus = "Active"; if (Node.blockSync.synchronizing) { dltStatus = "Synchronizing"; } if (Node.blockChain.getTimeSinceLastBLock() > 1800) // if no block for over 1800 seconds { dltStatus = "ErrorLongTimeNoBlock"; } if (Node.blockProcessor.networkUpgraded) { dltStatus = "ErrorForkedViaUpgrade"; } networkArray.Add("Update", checkUpdate()); networkArray.Add("DLT Status", dltStatus); networkArray.Add("Core Status", IxianHandler.status); string bpStatus = "Stopped"; if (Node.blockProcessor.operating) { bpStatus = "Running"; } networkArray.Add("Block Processor Status", bpStatus); Block last_block = Node.blockChain.getLastBlock(); if (last_block != null) { networkArray.Add("Block Height", last_block.blockNum); networkArray.Add("Block Version", last_block.version); networkArray.Add("Block Signature Count", last_block.getFrozenSignatureCount()); } else { networkArray.Add("Block Height", 0); networkArray.Add("Block Version", 0); networkArray.Add("Block Signature Count", 1); } networkArray.Add("Network Block Height", IxianHandler.getHighestKnownNetworkBlockHeight()); networkArray.Add("Node Type", PresenceList.myPresenceType); networkArray.Add("Connectable", NetworkServer.isConnectable()); if (parameters.ContainsKey("vv") || parameters.ContainsKey("verbose")) { networkArray.Add("Required Consensus", Node.blockChain.getRequiredConsensus()); networkArray.Add("Wallets", Node.walletState.numWallets); networkArray.Add("Presences", PresenceList.getTotalPresences()); networkArray.Add("Supply", Node.walletState.calculateTotalSupply().ToString()); networkArray.Add("Applied TX Count", TransactionPool.getAppliedTransactionCount()); networkArray.Add("Unapplied TX Count", TransactionPool.getUnappliedTransactionCount()); networkArray.Add("Masters", PresenceList.countPresences('M')); networkArray.Add("Relays", PresenceList.countPresences('R')); networkArray.Add("Clients", PresenceList.countPresences('C')); } if (parameters.ContainsKey("vv")) { Dictionary <string, object> queues = new Dictionary <string, object>(); queues.Add("RcvLow", NetworkQueue.getLowPriorityMessageCount()); queues.Add("RcvMedium", NetworkQueue.getMediumPriorityMessageCount()); queues.Add("RcvHigh", NetworkQueue.getHighPriorityMessageCount()); queues.Add("SendClients", NetworkServer.getQueuedMessageCount()); queues.Add("SendServers", NetworkClientManager.getQueuedMessageCount()); queues.Add("Logging", Logging.getRemainingStatementsCount()); queues.Add("Pending Transactions", PendingTransactions.pendingTransactionCount()); queues.Add("Storage", Node.storage.getQueuedQueryCount()); queues.Add("Inventory", Node.inventoryCache.getItemCount()); queues.Add("Inventory Processed", Node.inventoryCache.getProcessedItemCount()); queues.Add("Activity", ActivityStorage.getQueuedQueryCount()); networkArray.Add("Queues", queues); networkArray.Add("WS Checksum", Crypto.hashToString(Node.walletState.calculateWalletStateChecksum())); } networkArray.Add("Network Clients", NetworkServer.getConnectedClients()); networkArray.Add("Network Servers", NetworkClientManager.getConnectedClients(true)); return(new JsonResponse { result = networkArray, error = error }); }
// Receive thread protected virtual void recvLoop() { socketReadBuffer = new byte[8192]; lastMessageStatTime = DateTime.UtcNow; while (running) { TLC.Report(); // Let the protocol handler receive and handle messages try { byte[] data = readSocketData(); if (data != null) { parseDataInternal(data, this); messagesPerSecond++; } } catch (Exception e) { if (running) { Logging.warn(string.Format("recvRE: Disconnected client {0} with exception {1}", getFullAddress(), e.ToString())); } state = RemoteEndpointState.Closed; } // Check if the client disconnected if (state == RemoteEndpointState.Closed) { running = false; break; } TimeSpan timeSinceLastStat = DateTime.UtcNow - lastMessageStatTime; if (timeSinceLastStat.TotalSeconds < 0 || timeSinceLastStat.TotalSeconds > 2) { lastMessageStatTime = DateTime.UtcNow; lastMessagesPerSecond = (int)(messagesPerSecond / timeSinceLastStat.TotalSeconds); messagesPerSecond = 0; } if (lastMessagesPerSecond < 1) { lastMessagesPerSecond = 1; } // Sleep a while to throttle the client // Check if there are too many messages // TODO TODO TODO this can be handled way better int total_message_count = NetworkQueue.getQueuedMessageCount() + NetworkQueue.getTxQueuedMessageCount(); if (total_message_count > 500) { Thread.Sleep(100 * lastMessagesPerSecond); if (messagesPerSecond == 0) { lastMessageStatTime = DateTime.UtcNow; } lastDataReceivedTime = Clock.getTimestamp(); } else if (total_message_count > 100) { Thread.Sleep(total_message_count / 10); } else { Thread.Sleep(1); } } }
/// <summary> /// Reads a protocol message from the specified byte-field and calls appropriate methods to process this message. /// </summary> /// <remarks> /// This function checks all applicable checksums and validates that the message is complete before calling one of the specialized /// methods to handle actual decoding and processing. /// </remarks> /// <param name="recv_buffer">Byte-field with an Ixian protocol message.</param> /// <param name="endpoint">Remote endpoint from where the message was received.</param> public static void readProtocolMessage(byte[] recv_buffer, RemoteEndpoint endpoint) { if (endpoint == null) { Logging.error("Endpoint was null. readProtocolMessage"); return; } ProtocolMessageCode code = ProtocolMessageCode.hello; byte[] data = null; using (MemoryStream m = new MemoryStream(recv_buffer)) { using (BinaryReader reader = new BinaryReader(m)) { // Check for multi-message packets. One packet can contain multiple network messages. while (reader.BaseStream.Position < reader.BaseStream.Length) { byte[] data_checksum; try { byte startByte = reader.ReadByte(); int message_code = reader.ReadInt32(); code = (ProtocolMessageCode)message_code; int data_length = reader.ReadInt32(); // If this is a connected client, filter messages if (endpoint.GetType() == typeof(RemoteEndpoint)) { if (endpoint.presence == null) { // Check for presence and only accept hello and syncPL messages if there is no presence. if (code == ProtocolMessageCode.hello || code == ProtocolMessageCode.getPresenceList || code == ProtocolMessageCode.getBalance || code == ProtocolMessageCode.newTransaction) { } else { // Ignore anything else return; } } } data_checksum = reader.ReadBytes(32); // sha512qu, 32 bytes byte header_checksum = reader.ReadByte(); byte endByte = reader.ReadByte(); data = reader.ReadBytes(data_length); } catch (Exception e) { Logging.error(String.Format("NET: dropped packet. {0}", e)); return; } // Compute checksum of received data byte[] local_checksum = Crypto.sha512sqTrunc(data, 0, 0, 32); // Verify the checksum before proceeding if (local_checksum.SequenceEqual(data_checksum) == false) { Logging.error("Dropped message (invalid checksum)"); continue; } // Can proceed to parse the data parameter based on the protocol message code. // Data can contain multiple elements. //parseProtocolMessage(code, data, socket, endpoint); NetworkQueue.receiveProtocolMessage(code, data, data_checksum, endpoint); } } } }
public void start(bool verboseConsoleOutput) { UpdateVerify.start(); // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, 'C'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); if (IXICore.Platform.onMono() == false && !Config.disableWebStart) { System.Diagnostics.Process.Start(Config.apiBinds[0]); } // Prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(2); // Start the keepalive thread PresenceList.startKeepAlive(); // Start TIV string headers_path = ""; if (IxianHandler.isTestNet) { headers_path = Path.Combine(Config.dataDirectory, "testnet-headers"); } else { headers_path = Path.Combine(Config.dataDirectory, "headers"); } if (generatedNewWallet || !File.Exists(Path.Combine(Config.dataDirectory, Config.walletFile))) { generatedNewWallet = false; tiv.start(headers_path); } else { tiv.start(headers_path, 0, null); } // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); pushNotifications = new PushNotifications(Config.pushServiceUrl); pushNotifications.start(); }
public JsonResponse onStatus(Dictionary <string, object> parameters) { JsonError error = null; Dictionary <string, object> networkArray = new Dictionary <string, object>(); networkArray.Add("Core Version", CoreConfig.version); networkArray.Add("Node Version", CoreConfig.productVersion); string netType = "mainnet"; if (CoreConfig.isTestNet) { netType = "testnet"; } networkArray.Add("Network type", netType); networkArray.Add("My time", Clock.getTimestamp()); networkArray.Add("Network time difference", Core.networkTimeDifference); networkArray.Add("My External IP", IxianHandler.publicIP); //networkArray.Add("Listening interface", context.Request.RemoteEndPoint.Address.ToString()); networkArray.Add("Queues", "Rcv: " + NetworkQueue.getQueuedMessageCount() + ", RcvTx: " + NetworkQueue.getTxQueuedMessageCount() + ", SendClients: " + NetworkServer.getQueuedMessageCount() + ", SendServers: " + NetworkClientManager.getQueuedMessageCount() + ", Storage: " + Storage.getQueuedQueryCount() + ", Logging: " + Logging.getRemainingStatementsCount() + ", Pending Transactions: " + PendingTransactions.pendingTransactionCount()); networkArray.Add("Node Deprecation Block Limit", Config.nodeDeprecationBlock); string dltStatus = "Active"; if (Node.blockSync.synchronizing) { dltStatus = "Synchronizing"; } if (Node.blockChain.getTimeSinceLastBLock() > 1800) // if no block for over 1800 seconds { dltStatus = "ErrorLongTimeNoBlock"; } if (Node.blockProcessor.networkUpgraded) { dltStatus = "ErrorForkedViaUpgrade"; } networkArray.Add("Update", checkUpdate()); networkArray.Add("DLT Status", dltStatus); string bpStatus = "Stopped"; if (Node.blockProcessor.operating) { bpStatus = "Running"; } networkArray.Add("Block Processor Status", bpStatus); networkArray.Add("Block Height", Node.blockChain.getLastBlockNum()); networkArray.Add("Block Version", Node.blockChain.getLastBlockVersion()); networkArray.Add("Network Block Height", IxianHandler.getHighestKnownNetworkBlockHeight()); networkArray.Add("Node Type", PresenceList.myPresenceType); networkArray.Add("Connectable", NetworkServer.isConnectable()); if (parameters.ContainsKey("verbose")) { networkArray.Add("Required Consensus", Node.blockChain.getRequiredConsensus()); networkArray.Add("Wallets", Node.walletState.numWallets); networkArray.Add("Presences", PresenceList.getTotalPresences()); networkArray.Add("Supply", Node.walletState.calculateTotalSupply().ToString()); networkArray.Add("Applied TX Count", TransactionPool.getTransactionCount() - TransactionPool.getUnappliedTransactions().Count()); networkArray.Add("Unapplied TX Count", TransactionPool.getUnappliedTransactions().Count()); networkArray.Add("WS Checksum", Crypto.hashToString(Node.walletState.calculateWalletStateChecksum())); networkArray.Add("WS Delta Checksum", Crypto.hashToString(Node.walletState.calculateWalletStateChecksum(true))); networkArray.Add("Network Clients", NetworkServer.getConnectedClients()); networkArray.Add("Network Servers", NetworkClientManager.getConnectedClients(true)); } networkArray.Add("Masters", PresenceList.countPresences('M')); networkArray.Add("Relays", PresenceList.countPresences('R')); networkArray.Add("Clients", PresenceList.countPresences('C')); networkArray.Add("Workers", PresenceList.countPresences('W')); return(new JsonResponse { result = networkArray, error = error }); }
static public void start() { if (running) { return; } Logging.info("Starting node"); running = true; UpdateVerify.init(Config.checkVersionUrl, Config.checkVersionSeconds); ulong block_height = 0; byte[] block_checksum = null; string headers_path; if (IxianHandler.isTestNet) { headers_path = Path.Combine(Config.spixiUserFolder, "testnet-headers"); } else { headers_path = Path.Combine(Config.spixiUserFolder, "headers"); if (generatedNewWallet || !walletStorage.walletExists()) { generatedNewWallet = false; block_height = CoreConfig.bakedBlockHeight; block_checksum = CoreConfig.bakedBlockChecksum; } else { block_height = Config.bakedRecoveryBlockHeight; block_checksum = Config.bakedRecoveryBlockChecksum; } } // Start TIV tiv.start(headers_path, block_height, block_checksum); // Generate presence list PresenceList.init(IxianHandler.publicIP, 0, 'C'); // Start the network queue NetworkQueue.start(); // Prepare the stream processor StreamProcessor.initialize(Config.spixiUserFolder); // Start the keepalive thread PresenceList.startKeepAlive(); // Start the transfer manager TransferManager.start(); customAppManager.start(); startCounter++; if (mainLoopThread != null) { mainLoopThread.Abort(); mainLoopThread = null; } mainLoopThread = new Thread(mainLoop); mainLoopThread.Name = "Main_Loop_Thread"; mainLoopThread.Start(); // Init push service string tag = Base58Check.Base58CheckEncoding.EncodePlain(IxianHandler.getWalletStorage().getPrimaryAddress()); var push_service = DependencyService.Get <IPushService>(); push_service.setTag(tag); push_service.initialize(); push_service.clearNotifications(); Logging.info("Node started"); }
public void start(bool verboseConsoleOutput) { // Generate presence list PresenceList.init(IxianHandler.publicIP, Config.serverPort, 'R'); // Start the network queue NetworkQueue.start(); ActivityStorage.prepareStorage(); if (Config.apiBinds.Count == 0) { Config.apiBinds.Add("http://localhost:" + Config.apiPort + "/"); } // Start the HTTP JSON API server apiServer = new APIServer(Config.apiBinds, Config.apiUsers, Config.apiAllowedIps); if (IXICore.Platform.onMono() == false && !Config.disableWebStart) { System.Diagnostics.Process.Start(Config.apiBinds[0]); } // Prepare stats screen ConsoleHelpers.verboseConsoleOutput = verboseConsoleOutput; Logging.consoleOutput = verboseConsoleOutput; Logging.flush(); if (ConsoleHelpers.verboseConsoleOutput == false) { statsConsoleScreen.clearScreen(); } // Check for test client mode if (Config.isTestClient) { TestClientNode.start(); return; } // Start the node stream server NetworkServer.beginNetworkOperations(); // Start the network client manager NetworkClientManager.start(2); // Start the keepalive thread PresenceList.startKeepAlive(); // Start TIV if (generatedNewWallet || !walletStorage.walletExists()) { generatedNewWallet = false; tiv.start(""); } else { tiv.start("", 0, null); } // Start the maintenance thread maintenanceThread = new Thread(performMaintenance); maintenanceThread.Start(); }