/// <summary> /// Load peer list. /// </summary> public static void LoadPeerList() { if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PeerFileName))) { using (var reader = new StreamReader(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PeerFileName))) { string line; while ((line = reader.ReadLine()) != null) { try { var peerObject = JsonConvert.DeserializeObject <ClassPeerObject>(line); if (IPAddress.TryParse(peerObject.peer_host, out _)) { if (!PeerList.ContainsKey(peerObject.peer_host)) { PeerList.Add(peerObject.peer_host, peerObject); } } } catch { } } } } else { File.Create(AppDomain.CurrentDomain.BaseDirectory + PeerFileName).Close(); } }
/// <summary> /// Initialize stream writer's for push logs into log files. /// </summary> private static void LogInitizaliationStreamWriter() { LogApiStreamWriter?.Close(); LogGeneralStreamWriter?.Close(); LogWalletUpdaterStreamWriter?.Close(); LogSyncStreamWriter?.Close(); LogRemoteNodeSyncStreamWriter?.Close(); LogGeneralStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogGeneral), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogWalletUpdaterStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogWalletUpdater), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogApiStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogApi), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogSyncStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogSync), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; LogRemoteNodeSyncStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogRemoteNodeSync), true, Encoding.UTF8, WriteLogBufferSize) { AutoFlush = true }; }
/// <summary> /// Save settings of the wallet gui into a file. /// </summary> public static void SaveSetting() { if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + _WalletOldSettingFile)) { File.Delete(AppDomain.CurrentDomain.BaseDirectory + _WalletOldSettingFile); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + _WalletSettingFile))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + _WalletSettingFile)) .Close(); } var walletSettingJsonObject = new ClassWalletSettingJson { wallet_current_language = ClassTranslation.CurrentLanguage, wallet_sync_mode = (int)Program.WalletXiropht.WalletSyncMode, wallet_sync_manual_host = Program.WalletXiropht.WalletSyncHostname, enable_peer_trust_system = ClassPeerList.PeerEnableTrustSystem, enable_proxy_mode = Program.WalletXiropht.WalletEnableProxyMode }; using (var writer = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + _WalletSettingFile), false)) { string data = JsonConvert.SerializeObject(walletSettingJsonObject, Formatting.Indented); writer.WriteLine(data); } }
/// <summary> /// Initialize stream writer's for push logs into log files. /// </summary> private static void LogInitizaliationStreamWriter() { LogCloseStreamWriter(); PoolGeneralErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneralError), true, Encoding.UTF8, WriteLogBufferSize); PoolGeneralLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneral), true, Encoding.UTF8, WriteLogBufferSize); PoolFilteringErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFilteringError), true, Encoding.UTF8, WriteLogBufferSize); PoolFilteringLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFiltering), true, Encoding.UTF8, WriteLogBufferSize); PoolMinerCheckStatsErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStatsError), true, Encoding.UTF8, WriteLogBufferSize); PoolMinerCheckStatsLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStats), true, Encoding.UTF8, WriteLogBufferSize); PoolMinerErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerError), true, Encoding.UTF8, WriteLogBufferSize); PoolMinerLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMiner), true, Encoding.UTF8, WriteLogBufferSize); PoolPaymentErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPaymentError), true, Encoding.UTF8, WriteLogBufferSize); PoolPaymentLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPayment), true, Encoding.UTF8, WriteLogBufferSize); PoolWalletErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWalletError), true, Encoding.UTF8, WriteLogBufferSize); PoolWalletLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWallet), true, Encoding.UTF8, WriteLogBufferSize); PoolApiErrorLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApiError), true, Encoding.UTF8, WriteLogBufferSize); PoolApiLogWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApi), true, Encoding.UTF8, WriteLogBufferSize); }
/// <summary> /// Clear each transMethodInvoker into cache. /// </summary> /// <param name="walletAddress"></param> public static bool RemoveWalletCache(string walletAddress) { _inClearCache = true; if (!string.IsNullOrEmpty(walletAddress)) { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\"))) { if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension))) { File.Delete(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension)); } Directory.Delete( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\"), true); Directory.CreateDirectory(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress)); } ListTransaction.Clear(); } _inClearCache = false; return(true); }
/// <summary> /// Insert a new wallet informations to the datbases file. /// </summary> /// <param name="walletAddress"></param> /// <param name="walletPublicKey"></param> /// <param name="walletPrivateKey"></param> /// <param name="walletPinCode"></param> /// <param name="walletPassword"></param> public static async void InsertNewWalletAsync(string walletAddress, string walletPublicKey, string walletPrivateKey, string walletPinCode, string walletPassword) { await Task.Factory.StartNew(delegate { InSave = true; bool success = false; while (!success) { try { if (!RpcDatabaseContent.ContainsKey(walletAddress)) { string encryptedWallet = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, walletAddress + "|" + walletPublicKey + "|" + walletPrivateKey + "|" + walletPinCode + "|" + walletPassword, RpcDatabasePassword, ClassWalletNetworkSetting.KeySize); RpcDatabaseStreamWriter.WriteLine(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine + encryptedWallet); var walletObject = new ClassWalletObject(walletAddress, walletPublicKey, walletPassword, walletPrivateKey, walletPinCode, encryptedWallet); RpcDatabaseContent.Add(walletAddress, walletObject); } success = true; } catch { RpcDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; } } InSave = false; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current); }
/// <summary> /// Insert a new transaction to database. /// </summary> /// <param name="walletAddress"></param> /// <param name="transaction"></param> public static async void InsertTransactionToSyncDatabaseAsync(string walletAddress, string walletPublicKey, string transaction) { await Task.Factory.StartNew(delegate { InSave = true; bool success = false; while (!success) { try { transaction = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, transaction, walletAddress + walletPublicKey, ClassWalletNetworkSetting.KeySize); string transactionLine = ClassSyncDatabaseEnumeration.DatabaseSyncStartLine + walletAddress + "|" + transaction; SyncDatabaseStreamWriter.WriteLine(transactionLine); success = true; } catch { SyncDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; } } TotalTransactionRead++; ClassConsole.ConsoleWriteLine("Total transaction saved: " + TotalTransactionRead); InSave = false; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current); }
/// <summary> /// Clear each block into cache. /// </summary> public static bool RemoveWalletBlockCache() { try { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "\\"))) { File.Delete(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain." + WalletBlockCacheFileExtension)); Directory.Delete( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "\\"), true); Directory.CreateDirectory( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } } catch { // } try { ListBlock.Clear(); } catch { } return(true); }
private static readonly int maxLogList = 10; // Minimum lines required for write them to the log file. /// <summary> /// Initialization of StreamWriter for the log file. /// </summary> public static void InitializeLog() { _writerLog = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + "\\wallet.log")) { AutoFlush = true }; }
/// <summary> /// Initialize sync database. /// </summary> /// <returns></returns> public static bool InitializeSyncDatabase() { try { if (!File.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile))) { File.Create(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile)).Close(); } else { using (FileStream fs = File.Open(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; int lineRead = 0; while ((line = sr.ReadLine()) != null) { lineRead++; if (line.Contains(ClassSyncDatabaseEnumeration.DatabaseSyncStartLine)) { string transactionLine = line.Replace(ClassSyncDatabaseEnumeration.DatabaseSyncStartLine, ""); var splitTransactionLine = transactionLine.Split(new[] { "|" }, StringSplitOptions.None); string walletAddress = splitTransactionLine[0]; if (ClassRpcDatabase.RpcDatabaseContent.ContainsKey(walletAddress)) { string transaction = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, splitTransactionLine[1], walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize); var splitTransaction = transaction.Split(new[] { "#" }, StringSplitOptions.None); if (splitTransaction[0] == "anonymous") { ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(transaction, true, false); } else { ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(transaction, false, false); } TotalTransactionRead++; } } } } } } } } catch { return(false); } SyncDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; ClassConsole.ConsoleWriteLine("Total transaction read from sync database: " + TotalTransactionRead, ClassConsoleColorEnumeration.IndexConsoleGreenLog, ClassConsoleLogLevelEnumeration.LogLevelSyncDatabase); return(true); }
/// <summary> /// Create or read contact list file of the wallet gui. /// </summary> public static void InitializationContactList() { if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName)) .Close(); // Create and close the file for don't make in busy permissions. } else { using (var fs = File.Open( ClassUtility.ConvertPath( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName)), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var bs = new BufferedStream(fs)) using (var sr = new StreamReader(bs)) { var errorRead = false; string line; while ((line = sr.ReadLine()) != null) { try { var splitContactLine = line.Split(new[] { "|" }, StringSplitOptions.None); var contactName = splitContactLine[0]; var contactWalletAddress = splitContactLine[1]; if (!ListContactWallet.ContainsKey(contactName)) { ListContactWallet.Add(contactName.ToLower(), new Tuple <string, string>(contactName, contactWalletAddress)); } #if DEBUG else { Log.WriteLine("Contact name: " + contactName + " already exist on the list."); } #endif } catch { errorRead = true; break; } } if (errorRead) // Replace file corrupted by a cleaned one. { ListContactWallet.Clear(); // Clean dictionnary just in case. #if DEBUG Log.WriteLine("Database contact list file corrupted, remake it"); #endif File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName)) .Close(); // Create and close the file for don't make in busy permissions. } } } }
/// <summary> /// Save transaction database. /// </summary> public static void SaveTransactionPoolDatabase(string transaction) { using (var transactionWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { transactionWriter.WriteLine(ClassMiningPoolTransactionDatabaseEnumeration.DatabaseTransactionStart + transaction); } }
/// <summary> /// Save each transaction into cache /// </summary> /// <param name="walletAddress"></param> public static async Task SaveWalletCacheAsync(string walletAddress, string transaction) { if (!string.IsNullOrEmpty(walletAddress)) { walletAddress += "ANONYMITY"; if (ListTransaction.Count > 0 && _inClearCache == false) { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory)) == false) { Directory.CreateDirectory( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory)); } if (Directory.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress)); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension)).Close(); } try { using (var transactionFile = new StreamWriter(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension), true)) { await transactionFile.WriteAsync(transaction + "\n").ConfigureAwait(false); } } catch { // ignored } } } }
/// <summary> /// Load transaction in cache. /// </summary> /// <param name="walletAddress"></param> /// <returns></returns> public static void LoadWalletCache(string walletAddress) { if (ListTransaction != null) { ListTransaction.Clear(); } else { ListTransaction = new Dictionary <long, string>(); } if (!string.IsNullOrEmpty(walletAddress)) { walletAddress += "ANONYMITY"; if (Directory.Exists( ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\"))) { if (File.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension))) { using (FileStream fs = File.Open(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { if (!ListTransaction.ContainsValue(line)) { ListTransaction.Add(ListTransaction.Count, line); } } } } else { File.Create(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress + "\\" + WalletTransactionCacheFileExtension)).Close(); } } else { if (Directory.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory)); } Directory.CreateDirectory(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletTransactionCacheDirectory + walletAddress)); } } }
/// <summary> /// Force to save whole databases of wallets. /// </summary> public static async Task <bool> SaveWholeRpcWalletDatabaseFile() { while (InSave) { await Task.Delay(100); } InSave = true; bool success = false; while (!success) { try { try { RpcDatabaseStreamWriter?.Close(); RpcDatabaseStreamWriter?.Dispose(); } catch { } File.Copy(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFileBackup + "-" + DateTimeOffset.Now.ToUnixTimeMilliseconds())); // Backup wallet database just in case. File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile)).Close(); RpcDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; foreach (var wallet in RpcDatabaseContent) { string encryptedWallet = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, wallet.Value.GetWalletAddress() + "|" + wallet.Value.GetWalletPublicKey() + "|" + wallet.Value.GetWalletPrivateKey() + "|" + wallet.Value.GetWalletPinCode() + "|" + wallet.Value.GetWalletPassword(), RpcDatabasePassword, ClassWalletNetworkSetting.KeySize); RpcDatabaseStreamWriter.WriteLine(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine + encryptedWallet); } success = true; } catch { RpcDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; } } InSave = false; return(true); }
/// <summary> /// Save each block into cache /// </summary> /// <param name="block"></param> public static async Task SaveWalletBlockCache(string block) { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)) == false) { Directory.CreateDirectory( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension)) == false) { try { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension)).Close(); using (var transactionFile = new StreamWriter(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension), true)) { await transactionFile.WriteAsync(block + "\n").ConfigureAwait(false); } } catch { // ignored } } else { try { using (var transactionFile = new StreamWriter(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension), true)) { await transactionFile.WriteAsync(block + "\n").ConfigureAwait(false); } } catch { // } } }
/// <summary> /// Load block in cache. /// </summary> /// <returns></returns> public static void LoadBlockchainCache() { if (ListBlock != null) { ListBlock.Clear(); } else { ListBlock = new List <string>(); } if (Directory.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "\\"))) { if ( File.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension))) { int counter = 0; using (FileStream fs = File.Open(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { ListBlock.Add(line); counter++; } } } } else { if (Directory.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } Directory.CreateDirectory(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } }
/// <summary> /// Remove by contact name, because they should are unique. /// </summary> /// <param name="name"></param> public static void RemoveContact(string name) { if (ListContactWallet.ContainsKey(name.ToLower())) { ListContactWallet.Remove(name.ToLower()); } File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName)) .Close(); // Create and close the file for don't make in busy permissions. foreach (var contact in ListContactWallet) { using (var writerContact = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName), true)) { writerContact.WriteLine(contact.Value.Item1 + "|" + contact.Value.Item2); } } }
/// <summary> /// Save peer list. /// </summary> public static void SavePeerList() { try { File.Create(AppDomain.CurrentDomain.BaseDirectory + PeerFileName).Close(); using (var writer = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PeerFileName))) { foreach (var peer in PeerList.ToArray()) { var peerData = JsonConvert.SerializeObject(peer.Value); writer.WriteLine(peerData); } } } catch { } }
/// <summary> /// Create the log directory and log files if they not exist. /// </summary> private static bool LogInitializationFile() { if (Directory.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogDirectory)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogDirectory)); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogGeneral))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogGeneral)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogWalletUpdater))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogWalletUpdater)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogApi))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogApi)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogSync))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogSync)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogRemoteNodeSync))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogRemoteNodeSync)).Close(); return(false); } return(true); }
/// <summary> /// Catch unexpected exception and them to a log file. /// </summary> private static void EnableCatchUnexpectedException() { AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs args2) { var filePath = ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + UnexpectedExceptionFile); var exception = (Exception)args2.ExceptionObject; using (var writer = new StreamWriter(filePath, true)) { writer.WriteLine("Message :" + exception.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exception.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now); writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine); } Trace.TraceError(exception.StackTrace); Console.WriteLine("Unexpected error catched, check the error file: " + ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + UnexpectedExceptionFile)); Environment.Exit(1); }; }
/// <summary> /// Insert a new contact to the list and save the database file. /// </summary> /// <param name="name"></param> /// <param name="walletAddress"></param> /// <returns></returns> public static bool InsertContact(string name, string walletAddress) { if (ListContactWallet.ContainsKey(name.ToLower())) { #if DEBUG Log.WriteLine("Contact name: " + name + " already exist."); #endif return(false); } foreach (var contactList in ListContactWallet) { if (contactList.Value.Item2.ToLower() == walletAddress.ToLower()) { #if DEBUG Log.WriteLine("Contact wallet address: " + walletAddress + " already exist."); #endif return(false); } if (contactList.Value.Item1.ToLower() == name.ToLower()) { #if DEBUG Log.WriteLine("Contact wallet address: " + walletAddress + " already exist."); #endif return(false); } } ListContactWallet.Add(name.ToLower(), new Tuple <string, string>(name, walletAddress)); using (var writerContact = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + ContactFileName), true)) { writerContact.WriteLine(name + "|" + walletAddress); } return(true); }
/// <summary> /// Load setting file of the wallet gui. /// </summary> public static bool LoadSetting() { if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + _WalletSettingFile))) { SaveSetting(); return(true); // This is the first start of the wallet gui. } string jsonSetting = string.Empty; using (var reader = new StreamReader(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + _WalletSettingFile))) { string line; while ((line = reader.ReadLine()) != null) { jsonSetting += line; } } try { var walletSettingJsonObject = JsonConvert.DeserializeObject <ClassWalletSettingJson>(jsonSetting); ClassTranslation.CurrentLanguage = walletSettingJsonObject.wallet_current_language; Program.WalletXiropht.WalletSyncHostname = walletSettingJsonObject.wallet_sync_manual_host; Program.WalletXiropht.WalletSyncMode = (ClassWalletSyncMode)walletSettingJsonObject.wallet_sync_mode; Program.WalletXiropht.WalletEnableProxyMode = walletSettingJsonObject.enable_proxy_mode; ClassPeerList.PeerMaxBanTime = walletSettingJsonObject.peer_max_ban_time; ClassPeerList.PeerMaxDisconnect = walletSettingJsonObject.peer_max_disconnect; ClassPeerList.PeerEnableTrustSystem = walletSettingJsonObject.enable_peer_trust_system; } catch { return(false); } return(true); }
/// <summary> /// Create the log directory and log files if they not exist. /// </summary> private static bool LogInitializationFile() { if (Directory.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogDirectory)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogDirectory)); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneralError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneralError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneral))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolGeneral)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFilteringError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFilteringError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFiltering))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolFiltering)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStatsError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStatsError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStats))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolMinerCheckStats)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPaymentError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPaymentError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPayment))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolPayment)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWalletError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWalletError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWallet))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolWallet)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApiError))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApiError)).Close(); return(false); } if (!File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApi))) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + LogPoolApi)).Close(); return(false); } return(true); }
/// <summary> /// Load block in cache. /// </summary> /// <returns></returns> public static void LoadBlockchainCache() { if (ListBlock != null) { ListBlock.Clear(); ListBlockIndex.Clear(); } else { ListBlock = new Dictionary <string, ClassBlockObject>(); ListBlockIndex = new Dictionary <int, string>(); } OnLoad = true; try { Task.Factory.StartNew(() => { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "\\"))) { if ( File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension))) { var counter = 0; using (var fs = File.Open( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory + "/blockchain" + WalletBlockCacheFileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var bs = new BufferedStream(fs)) using (var sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { var blockLine = line.Split(new[] { "#" }, StringSplitOptions.None); if (!ListBlock.ContainsKey(blockLine[1])) { var blockObject = new ClassBlockObject { BlockHeight = blockLine[0], BlockHash = blockLine[1], BlockTransactionHash = blockLine[2], BlockTimestampCreate = blockLine[3], BlockTimestampFound = blockLine[4], BlockDifficulty = blockLine[5], BlockReward = blockLine[6] }; ListBlock.Add(blockLine[1], blockObject); ListBlockIndex.Add(ListBlockIndex.Count, blockLine[1]); counter++; } #if DEBUG else { Log.WriteLine("Duplicate block line: " + line); } #endif } } } } else { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)) == false) { Directory.CreateDirectory( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } Directory.CreateDirectory( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletBlockCacheDirectory)); } OnLoad = false; Program.WalletXiropht.ClassWalletObject.TotalBlockInSync = ListBlock.Count; }, Program.WalletXiropht.WalletCancellationToken.Token, TaskCreationOptions.DenyChildAttach, TaskScheduler.Current).ConfigureAwait(false); } catch { Program.WalletXiropht.ClassWalletObject.TotalBlockInSync = 0; ListBlock.Clear(); ListBlockIndex.Clear(); OnLoad = false; } }
/// <summary> /// Load RPC Database file. /// </summary> /// <returns></returns> public static bool LoadRpcDatabaseFile() { RpcDatabaseContent = new Dictionary <string, ClassWalletObject>(); try { if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile))) { using (FileStream fs = File.Open(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; int lineRead = 0; while ((line = sr.ReadLine()) != null) { lineRead++; if (line.StartsWith(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine)) { string walletData = line.Replace(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine, ""); walletData = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, walletData, RpcDatabasePassword, ClassWalletNetworkSetting.KeySize); if (walletData != ClassAlgoErrorEnumeration.AlgoError) { var splitWalletData = walletData.Split(new[] { "|" }, StringSplitOptions.None); var walletAddress = splitWalletData[0]; if (!RpcDatabaseContent.ContainsKey(walletAddress)) { var walletPublicKey = splitWalletData[1]; var walletPrivateKey = splitWalletData[2]; var walletPinCode = splitWalletData[3]; var walletPassword = splitWalletData[4]; var walletObject = new ClassWalletObject(walletAddress, walletPublicKey, walletPassword, walletPrivateKey, walletPinCode, walletData); if (!RpcDatabaseContent.ContainsKey(walletAddress)) { RpcDatabaseContent.Add(walletAddress, walletObject); } } } else { ClassConsole.ConsoleWriteLine("Decrypt database of wallets failed at line: " + lineRead); return(false); } } } } } } } else { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile)).Close(); } } catch { return(false); } RpcDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }; return(true); }
/// <summary> /// Stop auto save mining pool databases. /// </summary> public static void StopAutoSaveMiningPoolDatabases() { if (ThreadAutoSaveMiningPoolDatabases != null && (ThreadAutoSaveMiningPoolDatabases.IsAlive || ThreadAutoSaveMiningPoolDatabases != null)) { ThreadAutoSaveMiningPoolDatabases.Abort(); GC.SuppressFinalize(ThreadAutoSaveMiningPoolDatabases); } #region Save Database Miner Stats if (ClassMinerStats.DictionaryMinerStats.Count > 0) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile)).Close(); using (var minerWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { foreach (var miner in ClassMinerStats.DictionaryMinerStats) { if (!string.IsNullOrEmpty(miner.Key)) { string line = ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerStart + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerWalletAddress + miner.Key + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalGoodShare + miner.Value.TotalGoodShare + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalInvalidShare + miner.Value.TotalInvalidShare + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalMiningScore + miner.Value.TotalMiningScore + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalBalance + miner.Value.TotalBalance + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalPaid + miner.Value.TotalPaid + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerCustomMinimumPayment + miner.Value.CustomMinimumPayment; minerWriter.WriteLine(line); } } } ClassLog.ConsoleWriteLog("Auto save miner database: " + ClassMinerStats.DictionaryMinerStats.Count + " total miners saved.", ClassLogEnumeration.IndexPoolGeneralLog); } #endregion #region Save Database Pool if (ClassMiningPoolGlobalStats.ListBlockFound.Count > 0) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile)).Close(); int totalBlockFound = ClassMiningPoolGlobalStats.ListBlockFound.Count; using (var poolWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { for (int i = 0; i < totalBlockFound; i++) { if (i < totalBlockFound) { poolWriter.WriteLine(ClassMiningPoolGlobalStats.ListBlockFound[i]); } } } ClassLog.ConsoleWriteLog("Auto save pool database: " + totalBlockFound + " total blocks found saved.", ClassLogEnumeration.IndexPoolGeneralLog); } #endregion #region Save Database Transactions if (ClassMinerStats.DictionaryMinerTransaction.Count > 0) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile)).Close(); using (var transactionMinerWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { foreach (var miner in ClassMinerStats.DictionaryMinerTransaction) { if (!string.IsNullOrEmpty(miner.Key)) { if (miner.Value.Count > 0) { foreach (var transaction in miner.Value) { string line = ClassMiningPoolTransactionDatabaseEnumeration.DatabaseTransactionStart + miner.Key + "|" + transaction; transactionMinerWriter.WriteLine(line); } } } } } } #endregion }
/// <summary> /// Read database files of the mining pool. /// </summary> public static bool InitializationMiningPoolDatabases() { try { #region Read Database Miner stats if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile))) { using (FileStream fs = File.Open(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerStart)) { string minerWalletAddress = string.Empty; var minerLine = line.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerStart, ""); var splitMinerLine = minerLine.Split(new[] { "|" }, StringSplitOptions.None); foreach (var minerInfo in splitMinerLine) { if (minerInfo != null) { if (!string.IsNullOrEmpty(minerInfo)) { if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerWalletAddress)) { minerWalletAddress = minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerWalletAddress, ""); if (!ClassMinerStats.DictionaryMinerStats.ContainsKey(minerWalletAddress)) { ClassMinerStats.DictionaryMinerStats.Add(minerWalletAddress, new ClassMinerStatsObject()); ClassMinerStats.DictionaryMinerTransaction.Add(minerWalletAddress, new List <string>()); } } if (!string.IsNullOrEmpty(minerWalletAddress)) { if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalGoodShare)) { ClassMinerStats.DictionaryMinerStats[minerWalletAddress].TotalGoodShare = long.Parse(minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalGoodShare, "")); } else if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalInvalidShare)) { ClassMinerStats.DictionaryMinerStats[minerWalletAddress].TotalInvalidShare = float.Parse(minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalInvalidShare, "")); } else if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalMiningScore)) { ClassMinerStats.DictionaryMinerStats[minerWalletAddress].TotalMiningScore = long.Parse(minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalMiningScore, "")); } else if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalBalance)) { ClassMinerStats.DictionaryMinerStats[minerWalletAddress].TotalBalance = decimal.Parse(minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalBalance, "").Replace(".", ","), NumberStyles.Currency, Program.GlobalCultureInfo); } else if (minerInfo.StartsWith(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerCustomMinimumPayment)) { ClassMinerStats.DictionaryMinerStats[minerWalletAddress].CustomMinimumPayment = decimal.Parse(minerInfo.Replace(ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerCustomMinimumPayment, "").Replace(".", ","), NumberStyles.Currency, Program.GlobalCultureInfo); } } } } } } } } } } } else { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile)).Close(); } #endregion #region Read Database Pool if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile))) { using (FileStream fs = File.Open(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { var splitBlockFound = line; ClassMiningPoolGlobalStats.ListBlockFound.Add(ClassMiningPoolGlobalStats.ListBlockFound.Count, splitBlockFound); } } } } } else { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile)).Close(); } #endregion #region Read Database Transactions if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile))) { using (FileStream fs = File.Open(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string line; List <KeyValuePair <long, string> > ListTransactionPool = new List <KeyValuePair <long, string> >(); while ((line = sr.ReadLine()) != null) { if (line.StartsWith(ClassMiningPoolTransactionDatabaseEnumeration.DatabaseTransactionStart)) { var transactionLine = line.Replace(ClassMiningPoolTransactionDatabaseEnumeration.DatabaseTransactionStart, ""); var splitTransactionLine = transactionLine.Split(new[] { "|" }, StringSplitOptions.None); if (ClassMinerStats.DictionaryMinerTransaction.ContainsKey(splitTransactionLine[0])) { ClassMinerStats.DictionaryMinerTransaction[splitTransactionLine[0]].Add(splitTransactionLine[1] + "|" + splitTransactionLine[2] + "|" + splitTransactionLine[3] + "|" + splitTransactionLine[4]); } else { ClassMinerStats.DictionaryMinerTransaction.Add(splitTransactionLine[0], new List <string>() { splitTransactionLine[1] + "|" + splitTransactionLine[2] + "|" + splitTransactionLine[3] + "|" + splitTransactionLine[4] }); } if (!ClassMinerStats.DictionaryMinerStats.ContainsKey(splitTransactionLine[0])) { ClassMinerStats.DictionaryMinerStats.Add(splitTransactionLine[0], new ClassMinerStatsObject()); } long dateSend = long.Parse(splitTransactionLine[4]); decimal amountPaid = decimal.Parse(splitTransactionLine[2]); decimal feePaid = decimal.Parse(splitTransactionLine[3]); ClassMinerStats.DictionaryMinerStats[splitTransactionLine[0]].TotalPaid += (amountPaid + feePaid); string transactionInfo = splitTransactionLine[1] + "|" + splitTransactionLine[2] + "|" + splitTransactionLine[3] + "|" + splitTransactionLine[4]; KeyValuePair <long, string> transactionKeyValuePair = new KeyValuePair <long, string>(dateSend, transactionInfo); ListTransactionPool.Add(transactionKeyValuePair); ClassMiningPoolGlobalStats.PoolTotalPaid += (amountPaid + feePaid); } } if (ListTransactionPool.Count > 0) { ListTransactionPool = ListTransactionPool.OrderBy(x => x.Key).ToList(); foreach (var transactionPool in ListTransactionPool) { ClassMinerStats.DictionaryPoolTransaction.Add(ClassMinerStats.DictionaryPoolTransaction.Count, transactionPool.Value); } ListTransactionPool.Clear(); } } } } } else { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerTransactionDatabaseFile)).Close(); } #endregion } catch (Exception error) { ClassLog.ConsoleWriteLog("Error on initialization of mining pool databases, exception: " + error.Message, ClassLogEnumeration.IndexPoolGeneralErrorLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog, true); return(false); } return(true); }
/// <summary> /// Load transMethodInvoker in cache. /// </summary> /// <param name="walletAddress"></param> /// <returns></returns> public static void LoadWalletCache(string walletAddress) { if (ListTransaction != null) { ListTransaction.Clear(); } else { ListTransaction = new Dictionary <string, ClassWalletTransactionObject>(); } if (!string.IsNullOrEmpty(walletAddress)) { OnLoad = true; try { Task.Factory.StartNew(() => { if (Directory.Exists( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\"))) { if (File.Exists(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension))) { byte[] AesKeyIv = null; byte[] AesSalt = null; using (var password = new PasswordDeriveBytes( Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress + Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey, ClassUtils.GetByteArrayFromString(ClassUtils.FromHex( (Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress + Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey) .Substring(0, 8))))) { AesKeyIv = password.GetBytes( ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8); AesSalt = password.GetBytes(16); } var listTransactionEncrypted = new List <string>(); using (var fs = File.Open( ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension), FileMode.Open, FileAccess.Read, FileShare.Read)) using (var bs = new BufferedStream(fs)) using (var sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { listTransactionEncrypted.Add(line); } } if (listTransactionEncrypted.Count > 0) { var line = 0; foreach (var transactionEncrypted in listTransactionEncrypted) { line++; var walletTransactionDecrypted = ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, transactionEncrypted, ClassWalletNetworkSetting.KeySize, AesKeyIv, AesSalt); if (walletTransactionDecrypted != ClassAlgoErrorEnumeration.AlgoError) { var splitTransaction = walletTransactionDecrypted.Split(new[] { "#" }, StringSplitOptions.None); if (!ListTransaction.ContainsKey(splitTransaction[1])) { var splitBlockchainHeight = splitTransaction[7] .Split(new[] { "~" }, StringSplitOptions.None); var transactionObject = new ClassWalletTransactionObject { TransactionType = splitTransaction[0], TransactionHash = splitTransaction[1], TransactionWalletAddress = splitTransaction[2], TransactionAmount = decimal.Parse( splitTransaction[3].ToString(Program.GlobalCultureInfo), NumberStyles.Currency, Program.GlobalCultureInfo), TransactionFee = decimal.Parse( splitTransaction[4].ToString(Program.GlobalCultureInfo), NumberStyles.Currency, Program.GlobalCultureInfo), TransactionTimestampSend = long.Parse(splitTransaction[5]), TransactionTimestampRecv = long.Parse(splitTransaction[6]), TransactionBlockchainHeight = splitBlockchainHeight[0].Replace("{", "") }; ListTransaction.Add(splitTransaction[1], transactionObject); Program.WalletXiropht.UpdateLabelSyncInformation( "On load transaction database - total transactions loaded and decrypted: " + (ListTransaction.Count + ClassWalletTransactionAnonymityCache .ListTransaction.Count)); } #if DEBUG else { Log.WriteLine("Duplicate anonymous transaction: " + walletTransactionDecrypted); } #endif } #if DEBUG else { Log.WriteLine("Wrong transaction at line: " + line); } #endif } } listTransactionEncrypted.Clear(); Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync = ListTransaction.Count; AesKeyIv = null; AesSalt = null; } else { File.Create(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension)).Close(); } } else { if (Directory.Exists(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory)) == false) { Directory.CreateDirectory(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory)); } Directory.CreateDirectory(ClassUtility.ConvertPath( AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory + walletAddress)); } Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync = ListTransaction.Count; OnLoad = false; }, Program.WalletXiropht.WalletCancellationToken.Token, TaskCreationOptions.DenyChildAttach, TaskScheduler.Current).ConfigureAwait(false); } catch { Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync = 0; ListTransaction.Clear(); OnLoad = false; } } }
/// <summary> /// Auto save mining pools databases. /// </summary> public static void AutoSaveMiningPoolDatabases() { if (ThreadAutoSaveMiningPoolDatabases != null && (ThreadAutoSaveMiningPoolDatabases.IsAlive || ThreadAutoSaveMiningPoolDatabases != null)) { ThreadAutoSaveMiningPoolDatabases.Abort(); GC.SuppressFinalize(ThreadAutoSaveMiningPoolDatabases); } ThreadAutoSaveMiningPoolDatabases = new Thread(delegate() { while (!Program.Exit) { try { #region Save Database Miner Stats if (ClassMinerStats.DictionaryMinerStats.Count > 0) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile)).Close(); using (var minerWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + MinerDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { foreach (var miner in ClassMinerStats.DictionaryMinerStats) { if (!string.IsNullOrEmpty(miner.Key)) { string line = ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerStart + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerWalletAddress + miner.Key + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalGoodShare + miner.Value.TotalGoodShare + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalInvalidShare + miner.Value.TotalInvalidShare + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalMiningScore + miner.Value.TotalMiningScore + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalBalance + miner.Value.TotalBalance + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerTotalPaid + miner.Value.TotalPaid + "|" + ClassMiningPoolMinerDatabaseEnumeration.DatabaseMinerCustomMinimumPayment + miner.Value.CustomMinimumPayment; minerWriter.WriteLine(line); } } } ClassLog.ConsoleWriteLog("Auto save miner database: " + ClassMinerStats.DictionaryMinerStats.Count + " total miners saved.", ClassLogEnumeration.IndexPoolGeneralLog); } #endregion Thread.Sleep(AutoSaveMiningPoolDatabasesInterval); #region Save Database Pool if (ClassMiningPoolGlobalStats.ListBlockFound.Count > 0) { File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile)).Close(); int totalBlockFound = ClassMiningPoolGlobalStats.ListBlockFound.Count; using (var poolWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + PoolDatabaseFile), true, Encoding.UTF8, 8192) { AutoFlush = true }) { for (int i = 0; i < totalBlockFound; i++) { if (i < totalBlockFound) { poolWriter.WriteLine(ClassMiningPoolGlobalStats.ListBlockFound[i]); } } } ClassLog.ConsoleWriteLog("Auto save pool database: " + totalBlockFound + " total blocks found saved.", ClassLogEnumeration.IndexPoolGeneralLog); } #endregion Thread.Sleep(AutoSaveMiningPoolDatabasesInterval); } catch (Exception error) { ClassLog.ConsoleWriteLog("Auto save databases of the pool exception: " + error.Message + " retry after few seconds", ClassLogEnumeration.IndexPoolGeneralLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog, true); Thread.Sleep(5000); } } }); ThreadAutoSaveMiningPoolDatabases.Start(); }