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(); }
// Handle timer routines static public void onUpdate(object source, ElapsedEventArgs e) { // Update the friendlist FriendList.Update(); // Cleanup the presence list // TODO: optimize this by using a different thread perhaps PresenceList.performCleanup(); if (Node.walletStorage.getPrimaryAddress() == null) { return; } if (PresenceList.curNodePresence == null) { PresenceList.generatePresenceList("spixi:000", 'C'); // TODO TODO TODO TODO spixi:000 is used only for tech preview and will later be replaced with something more secure } // Request wallet balance using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.Write(Node.walletStorage.getPrimaryAddress().Length); writer.Write(Node.walletStorage.getPrimaryAddress()); NetworkClientManager.broadcastData(new char[] { 'M' }, ProtocolMessageCode.getBalance, mw.ToArray(), null); } } }
public static void handleGetRandomPresences(byte[] data, RemoteEndpoint endpoint) { if (!endpoint.isConnected()) { return; } using (MemoryStream m = new MemoryStream(data)) { using (BinaryReader reader = new BinaryReader(m)) { char type = reader.ReadChar(); List <Presence> presences = PresenceList.getPresencesByType(type); int presence_count = presences.Count(); if (presence_count > 10) { Random rnd = new Random(); presences = presences.Skip(rnd.Next(presence_count - 10)).Take(10).ToList(); } foreach (Presence presence in presences) { byte[][] presence_chunks = presence.getByteChunks(); foreach (byte[] presence_chunk in presence_chunks) { endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null); } } } } }
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(); }
// Handle timer routines static public void onUpdate(object source, ElapsedEventArgs e) { // Update the friendlist FriendList.Update(); // Cleanup the presence list // TODO: optimize this by using a different thread perhaps PresenceList.performCleanup(); if (Node.walletStorage.getPrimaryAddress() == null) { return; } if (Config.enablePushNotifications) { OfflinePushMessages.fetchPushMessages(); } // Request initial wallet balance if (balance.blockHeight == 0 || balance.lastUpdate + 300 < Clock.getTimestamp()) { using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.Write(Node.walletStorage.getPrimaryAddress().Length); writer.Write(Node.walletStorage.getPrimaryAddress()); NetworkClientManager.broadcastData(new char[] { 'M' }, ProtocolMessageCode.getBalance, mw.ToArray(), null); } } } }
// Updates all contacts in the friendlist public static void Update() { lock (friends) { // Go through each friend and check for the pubkey in the PL foreach (Friend friend in friends) { if (PresenceList.getPresenceByAddress(friend.walletAddress) != null) { if (friend.online == false) { Node.shouldRefreshContacts = true; } friend.online = true; } else { if (friend.online == true) { Node.shouldRefreshContacts = true; } friend.online = false; } } } }
// Perform periodic cleanup tasks private static void performMaintenance() { while (running) { TLC.Report(); // Sleep a while to prevent cpu usage Thread.Sleep(10000); try { TransactionPool.processPendingTransactions(); // Cleanup the presence list PresenceList.performCleanup(); if (update() == false) { IxianHandler.forceShutdown = true; } } catch (Exception e) { Logging.error("Exception occurent in Node.performMaintenance: " + e); } } }
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 void handleGetPresence2(byte[] data, RemoteEndpoint endpoint) { using (MemoryStream m = new MemoryStream(data)) { using (BinaryReader reader = new BinaryReader(m)) { int walletLen = (int)reader.ReadIxiVarUInt(); byte[] wallet = reader.ReadBytes(walletLen); Presence p = PresenceList.getPresenceByAddress(wallet); if (p != null) { lock (p) { byte[][] presence_chunks = p.getByteChunks(); foreach (byte[] presence_chunk in presence_chunks) { endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null); } } } else { // TODO blacklisting point Logging.warn(string.Format("Node has requested presence information about {0} that is not in our PL.", Base58Check.Base58CheckEncoding.EncodePlain(wallet))); } } } }
// Handle timer routines static public void onUpdate(object source, ElapsedEventArgs e) { // Update the friendlist FriendList.Update(); // Cleanup the presence list // TODO: optimize this by using a different thread perhaps PresenceList.performCleanup(); if (Node.walletStorage.getPrimaryAddress() == null) { return; } // Request wallet balance using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.Write(Node.walletStorage.getPrimaryAddress().Length); writer.Write(Node.walletStorage.getPrimaryAddress()); NetworkClientManager.broadcastData(new char[] { 'M' }, ProtocolMessageCode.getBalance, mw.ToArray(), null); } } }
private JsonResponse onCountNodeVersions() { Dictionary <string, int> versions = new Dictionary <string, int>(); List <Presence> presences = PresenceList.getPresences(); lock (presences) { foreach (var entry in presences) { foreach (var pa_entry in entry.addresses) { if (!versions.ContainsKey(pa_entry.nodeVersion)) { versions.Add(pa_entry.nodeVersion, 0); } versions[pa_entry.nodeVersion]++; } } } return(new JsonResponse { result = versions, error = null }); }
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; }
// Retrieve the friend's connected S2 node address. Returns null if not found public string searchForRelay() { string hostname = null; Presence presence = PresenceList.getPresenceByAddress(walletAddress); if (presence == null) { return(hostname); } byte[] wallet = presence.wallet; lock (presence) { // Go through each presence address searching for C nodes foreach (PresenceAddress addr in presence.addresses) { // Only check Client nodes if (addr.type == 'C') { // We have a potential candidate here, store it hostname = addr.address; string[] hostname_split = hostname.Split(':'); if (hostname_split.Count() == 2 && NetworkUtils.validateIP(hostname_split[0])) { // client is directly connectable break; } // find a relay node Presence s2presence = PresenceList.getPresenceByDeviceId(hostname); if (s2presence != null) { PresenceAddress s2addr = s2presence.addresses.Find(x => x.device == hostname); if (s2addr != null) { // We found the friend's connected s2 node hostname = s2addr.address; wallet = s2presence.wallet; break; } } } } } // Store the last relay ip and wallet for this friend relayIP = hostname; relayWallet = wallet; // Finally, return the ip address of the node return(relayIP); }
// Perform periodic cleanup tasks private static void performMaintenance() { while (running) { // Sleep a while to prevent cpu usage Thread.Sleep(1000); // Cleanup the presence list PresenceList.performCleanup(); } }
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(); }
public JsonResponse onPl() { JsonError error = null; List <Presence> presences = PresenceList.getPresences(); // Show a list of presences lock (presences) { return(new JsonResponse { result = presences, error = error }); } }
public static void handleUpdatePresence(byte[] data, RemoteEndpoint endpoint) { // Parse the data and update entries in the presence list Presence updated_presence = PresenceList.updateFromBytes(data); // If a presence entry was updated, broadcast this message again if (updated_presence != null) { CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M', 'H', 'W' }, ProtocolMessageCode.updatePresence, data, updated_presence.wallet, endpoint); // Send this keepalive message to all subscribed clients CoreProtocolMessage.broadcastEventDataMessage(NetworkEvents.Type.keepAlive, updated_presence.wallet, ProtocolMessageCode.updatePresence, data, updated_presence.wallet, endpoint); } }
public void drawScreen() { Console.SetCursorPosition(0, 0); writeLine(" _______ _______ _ _ _____ ___ "); writeLine(" |_ _\\ \\ / /_ _| /\\ | \\ | | / ____|__ \\ "); writeLine(" | | \\ V / | | / \\ | \\| | | (___ ) |"); writeLine(" | | > < | | / /\\ \\ | . ` | \\___ \\ / / "); writeLine(" _| |_ / . \\ _| |_ / ____ \\| |\\ | ____) |/ /_ "); writeLine(" |_____/_/ \\_\\_____/_/ \\_\\_| \\_| |_____/|____|"); writeLine(" {0} ", ("" + Config.version).PadLeft(48)); writeLine(" http://localhost:{0}/ ", Config.apiPort); writeLine("──────────────────────────────────────────────────"); writeLine(" Thank you for running an Ixian S2 node.\n For help please visit www.ixian.io"); writeLine("──────────────────────────────────────────────────\n"); /* * if (Node.serverStarted == false) * { * return; * }*/ // Node status string dltStatus = "active "; int connectionsIn = NetworkServer.getConnectedClients().Count(); int connectionsOut = NetworkClientManager.getConnectedClients().Count(); if (connectionsIn + connectionsOut < 1) { dltStatus = "connecting "; } writeLine("\tStatus:\t\t{0}\n", dltStatus); writeLine("\tConnections (I/O):\t{0}", connectionsIn + "/" + connectionsOut); writeLine("\tPresences:\t\t{0}", PresenceList.getTotalPresences()); writeLine("\n──────────────────────────────────────────────────"); TimeSpan elapsed = DateTime.Now - startTime; writeLine(" Running for {0} days {1}h {2}m {3}s", elapsed.Days, elapsed.Hours, elapsed.Minutes, elapsed.Seconds); writeLine(""); writeLine(" Press V to toggle stats. Ctrl-C to exit."); }
// Handle timer routines static public void mainLoop() { byte[] primaryAddress = IxianHandler.getWalletStorage().getPrimaryAddress(); if (primaryAddress == null) { return; } byte[] getBalanceBytes; using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.WriteIxiVarInt(primaryAddress.Length); writer.Write(primaryAddress); } getBalanceBytes = mw.ToArray(); } while (running) { try { // Update the friendlist FriendList.Update(); // Request initial wallet balance if (balance.blockHeight == 0 || balance.lastUpdate + 300 < Clock.getTimestamp()) { CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M', 'H' }, ProtocolMessageCode.getBalance2, getBalanceBytes, null); } if (Config.enablePushNotifications) { OfflinePushMessages.fetchPushMessages(); } // Cleanup the presence list // TODO: optimize this by using a different thread perhaps PresenceList.performCleanup(); } catch (Exception e) { Logging.error("Exception occured in mainLoop: " + e); } Thread.Sleep(2500); } }
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(); }
// Finds a presence entry's pubkey public static byte[] findContactPubkey(byte[] wallet_address) { Friend f = getFriend(wallet_address); if (f != null && f.publicKey != null) { return(f.publicKey); } Presence p = PresenceList.getPresenceByAddress(wallet_address); if (p != null && p.addresses.Find(x => x.type == 'C') != null) { return(p.pubkey); } return(null); }
// Perform periodic cleanup tasks private static void performMaintenance() { while (running) { TLC.Report(); // Sleep a while to prevent cpu usage Thread.Sleep(1000); TransactionPool.processPendingTransactions(); // Cleanup transaction pool TransactionPool.performCleanup(); // Cleanup the presence list PresenceList.performCleanup(); } }
// Retrieve a presence entry connected S2 node. Returns null if not found public static string getRelayHostname(byte[] wallet_address) { string hostname = null; Presence presence = PresenceList.getPresenceByAddress(wallet_address); if (presence == null) { using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.Write(wallet_address.Length); writer.Write(wallet_address); CoreProtocolMessage.broadcastProtocolMessage(new char[] { 'M' }, ProtocolMessageCode.getPresence, mw.ToArray(), null); } } return(null); } byte[] wallet = presence.wallet; lock (presence) { // Go through each presence address searching for C nodes foreach (PresenceAddress addr in presence.addresses) { // Only check Client nodes if (addr.type == 'C') { // We have a potential candidate here, store it hostname = addr.address; string[] hostname_split = hostname.Split(':'); if (hostname_split.Count() == 2 && NetworkUtils.validateIP(hostname_split[0])) { break; } } } } // Finally, return the ip address of the node return(hostname); }
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(); }
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(); }
public static void handleKeepAlivesChunk(byte[] data, RemoteEndpoint endpoint) { using (MemoryStream m = new MemoryStream(data)) { using (BinaryReader reader = new BinaryReader(m)) { int ka_count = (int)reader.ReadIxiVarUInt(); int max_ka_per_chunk = CoreConfig.maximumKeepAlivesPerChunk; if (ka_count > max_ka_per_chunk) { ka_count = max_ka_per_chunk; } for (int i = 0; i < ka_count; i++) { if (m.Position == m.Length) { break; } int ka_len = (int)reader.ReadIxiVarUInt(); byte[] ka_bytes = reader.ReadBytes(ka_len); byte[] hash = Crypto.sha512sqTrunc(ka_bytes); Node.inventoryCache.setProcessedFlag(InventoryItemTypes.keepAlive, hash, true); byte[] address; long last_seen; byte[] device_id; bool updated = PresenceList.receiveKeepAlive(ka_bytes, out address, out last_seen, out device_id, endpoint); // If a presence entry was updated, broadcast this message again if (updated) { CoreProtocolMessage.addToInventory(new char[] { 'M', 'H', 'W' }, new InventoryItemKeepAlive(hash, last_seen, address, device_id), endpoint, ProtocolMessageCode.keepAlivePresence, ka_bytes, address); // Send this keepalive message to all subscribed clients CoreProtocolMessage.broadcastEventDataMessage(NetworkEvents.Type.keepAlive, address, ProtocolMessageCode.keepAlivePresence, ka_bytes, address, endpoint); } } } } }
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(); }
private bool handleKeepAlive(InventoryItem item, RemoteEndpoint endpoint) { if (endpoint == null) { return(false); } InventoryItemKeepAlive iika = (InventoryItemKeepAlive)item; Presence p = PresenceList.getPresenceByAddress(iika.address); if (p == null) { using (MemoryStream mw = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(mw)) { writer.WriteIxiVarInt(iika.address.Length); writer.Write(iika.address); endpoint.sendData(ProtocolMessageCode.getPresence2, mw.ToArray(), null); } } return(false); } else { var pa = p.addresses.Find(x => x.device.SequenceEqual(iika.deviceId)); if (pa == null || iika.lastSeen > pa.lastSeenTime) { byte[] address_len_bytes = ((ulong)iika.address.Length).GetIxiVarIntBytes(); byte[] device_len_bytes = ((ulong)iika.deviceId.Length).GetIxiVarIntBytes(); byte[] data = new byte[1 + address_len_bytes.Length + iika.address.Length + device_len_bytes.Length + iika.deviceId.Length]; data[0] = 1; Array.Copy(address_len_bytes, 0, data, 1, address_len_bytes.Length); Array.Copy(iika.address, 0, data, 1 + address_len_bytes.Length, iika.address.Length); Array.Copy(device_len_bytes, 0, data, 1 + address_len_bytes.Length + iika.address.Length, device_len_bytes.Length); Array.Copy(iika.deviceId, 0, data, 1 + address_len_bytes.Length + iika.address.Length + device_len_bytes.Length, iika.deviceId.Length); endpoint.sendData(ProtocolMessageCode.getKeepAlives, data, null); return(true); } } return(false); }