public async Task ApplicationClosed() { /* 当应用程序关闭的时候不能直接关闭,因为某些程序可能还在运行,如果立即结束,有可能造成数据丢失 * 1、当应用程序关闭的时候需要即时判断BlockChainStatus的状态,如果是Stoped就可以结束了,如果是Stopping或者Running不能结束 * 需要用try catch捕获异常来判断是否关闭 */ //应用程序关闭的时候先调用StopEngine的接口 await BlockChainEngineApi.StopEngine(); //即时判断BlockChainStatus try { Schedule(async() => { ApiResponse response = await BlockChainEngineApi.GetBlockChainStatus(); if (!response.HasError) { BlockChainStatus result = response.GetResult <BlockChainStatus>(); if (result.RpcService == "Stopped") { //这个其实什么都不用写,因为接口服务关闭后,你只能获取到错误 //Application.Exit(); } } }).ToRunNow().AndEvery(1).Seconds(); } catch { //在这里捕获错误,然后关闭整个Application //Application.Exit(); } }
public async Task GetBlockChainStatus() { ApiResponse response = await BlockChainEngineApi.GetBlockChainStatus(); Assert.IsFalse(response.HasError); BlockChainStatus result = response.GetResult <BlockChainStatus>(); Assert.IsNotNull(result); }
public IResult AppClosed() { /* 当应用程序关闭的时候不能直接关闭,因为某些程序可能还在运行,如果立即结束,有可能造成数据丢失 * 1、当应用程序关闭的时候需要即时判断BlockChainStatus的状态,如果是Stoped就可以结束了,如果是Stopping或者Running不能结束 * 需要用try catch捕获异常来判断是否关闭 */ //应用程序关闭的时候先调用StopEngine的接口 Result result = new Result(); AutoResetEvent autoResetEvent = new AutoResetEvent(false); Task stopEngineTask = new Task(async() => { await BlockChainEngineApi.StopEngine(); }); stopEngineTask.Start(); //即时判断BlockChainStatus try { Task task = new Task(async() => { ApiResponse response = await BlockChainEngineApi.GetBlockChainStatus(); if (!response.HasError) { bool flag = true; while (flag) { BlockChainStatus blockChainStatus = response.GetResult <BlockChainStatus>(); if (blockChainStatus.RpcService == "Stopped") { flag = false; autoResetEvent.Set(); } Thread.Sleep(1000); } } }); task.Start(); } catch { //在这里捕获错误,然后关闭整个Application result.IsFail = true; autoResetEvent.Set(); } autoResetEvent.WaitOne(); result.IsFail = false; return(result); }
public async Task TestSendToAddress() { ApiResponse blockChainResponse = await BlockChainEngineApi.GetBlockChainStatus(); if (!blockChainResponse.HasError) { //地址 string address = "fiiitCPyohiEPn9q11AXCdvVDouoVvgojXBcVj"; //地址校验 BlockChainStatus blockChainStatus = blockChainResponse.GetResult <BlockChainStatus>(); //验证address if (AddressTools.AddressVerfy(blockChainStatus.ChainNetwork, address)) { //判断是否加密 ApiResponse transactionResponse = await TransactionApi.GetTxSettings(); if (!transactionResponse.HasError) { TransactionFeeSetting settingResult = transactionResponse.GetResult <TransactionFeeSetting>(); if (settingResult.Encrypt) { //先解锁 string password = "******"; ApiResponse unlockResponse = await WalletManagementApi.WalletPassphrase(password); if (!unlockResponse.HasError) { ApiResponse response = await TransactionApi.SendToAddress(address, 50000000, "this is your request", "John", false); Assert.IsFalse(response.HasError); string result = response.GetResult <string>(); Assert.IsNotNull(result); } ApiResponse lockResponse = await WalletManagementApi.WalletLock(); } else { ApiResponse response = await TransactionApi.SendToAddress(address, 50000000, "this is your request", "John", false); Assert.IsFalse(response.HasError); string result = response.GetResult <string>(); Assert.IsNotNull(result); } } } } }
public IResult AppClosed() { Result result = new Result(); AutoResetEvent autoResetEvent = new AutoResetEvent(false); Task stopEngineTask = new Task(async() => { await BlockChainEngineApi.StopEngine(); }); stopEngineTask.Start(); try { Task task = new Task(async() => { ApiResponse response = await BlockChainEngineApi.GetBlockChainStatus(); if (!response.HasError) { bool flag = true; while (flag) { BlockChainStatus blockChainStatus = response.GetResult <BlockChainStatus>(); if (blockChainStatus.RpcService == "Stopped") { result.IsFail = response.HasError; result.ApiResponse = response; flag = false; autoResetEvent.Set(); break; } Thread.Sleep(1000); } } }); task.Start(); } catch { //在这里捕获错误,然后关闭整个Application result.IsFail = true; autoResetEvent.Set(); } autoResetEvent.WaitOne(); return(result); }
public static async Task <ApiResponse> GetBlockChainStatus() { ApiResponse response = new ApiResponse(); try { BlockChainEngine engine = new BlockChainEngine(); BlockChainStatus status = new BlockChainStatus(); BlockChainStatusOM result = await engine.GetBlockChainStatus(); if (result != null) { status.ChainService = result.ChainService; status.BlockService = result.BlockService; status.P2pService = result.P2pService; status.RpcService = result.RpcService; status.ChainNetwork = result.ChainNetwork; status.Height = result.Height; response.Result = Newtonsoft.Json.Linq.JToken.FromObject(status); } else { response.Result = null; } } catch (ApiCustomException ex) { Logger.Singleton.Error(ex.Message); Logger.Singleton.Error("Api error code is:" + ex.ErrorCode.ToString()); Logger.Singleton.Error("Api error reason is:" + ex.InnerException.ToString()); response.Error = new ApiError(ex.ErrorCode, ex.Message); } catch (Exception ex) { Logger.Singleton.Error(ex.Message); Logger.Singleton.Error("Custom error code is:" + ex.HResult); Logger.Singleton.Error("Custom error reason is:" + ex.InnerException); response.Error = new ApiError(ex.HResult, ex.Message); } return(response); }
public async Task AddNewAddressBookItem() { //fiiit6ZgKDM5ZyDYhkSWDsUmRZpkbRQf7NWiKT //先根据接口获取网络类型 ApiResponse blockChainResponse = await BlockChainEngineApi.GetBlockChainStatus(); if (!blockChainResponse.HasError) { BlockChainStatus blockChainStatus = blockChainResponse.GetResult <BlockChainStatus>(); //验证address if (AddressTools.AddressVerfy(blockChainStatus.ChainNetwork, "fiiit6ZgKDM5ZyDYhkSWDsUmRZpkbRQf7NWiKT")) { ApiResponse addressBookResponse = await AddressBookApi.AddNewAddressBookItem("fiiit6ZgKDM5ZyDYhkSWDsUmRZpkbRQf7NWiKT", "label or comment"); if (!addressBookResponse.HasError) { //do something } } } }
static void Run(string[] args) { var app = new CommandLineApplication(false); app.HelpOption("-?|-h|--help"); app.OnExecute(() => { app.ShowHelp(); return; }); app.Command("mining", command => { command.Description = "begin mining"; command.HelpOption("-?|-h|--help"); CommandArgument nameArgument = command.Argument("[minerName]", "minerName"); CommandArgument addressArgument = command.Argument("[walletAddress]", "walletAddress"); command.OnExecute(async() => { if (nameArgument != null && !string.IsNullOrEmpty(nameArgument.Value) && addressArgument != null && !string.IsNullOrEmpty(addressArgument.Value)) { string name = nameArgument.Value; string address = addressArgument.Value; Program program = new Program(); BlockChainStatus chainStatus = await program.GetChainStatus(); if (chainStatus == null) { app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain"); return; } //验证本地区块高度和网络区块高度 ApiResponse response = await NetworkApi.GetBlockChainInfo(); if (!response.HasError) { BlockChainInfo info = response.GetResult <BlockChainInfo>(); if (info.IsRunning) { if (info.RemoteLatestBlockHeight <= info.LocalLastBlockHeight) { command.Out.WriteLine($"current network is {chainStatus.ChainNetwork}"); //validate wallet address if (AddressTools.AddressVerfy(chainStatus.ChainNetwork, address)) { command.Out.WriteLine($"address verify success. prepare to mine"); await BlockMining.MiningAsync(name, address); } else { command.Out.WriteLine($"address verify fail. address: {address} is invalid"); return; } } else { command.Out.WriteLine("Block Chain is in sync, please try it later"); return; } } else { command.Out.WriteLine("Block Chain has stopped"); return; } } else { command.Out.WriteLine(response.Error.Message); return; } } else { command.ShowHelp(); return; } }); }); app.Command("height", command => { command.Description = "view current block height"; command.OnExecute(async() => { Program program = new Program(); BlockChainStatus chainStatus = await program.GetChainStatus(); if (chainStatus == null) { app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain"); return; } ApiResponse response = await BlockChainEngineApi.GetBlockCount(); if (!response.HasError) { long result = response.GetResult <long>(); command.Out.WriteLine($"current block height is {result}"); } else { command.Out.WriteLine($"{response.Error.Message}"); } }); }); app.Command("balance", command => { command.Description = "view wallet balance"; command.OnExecute(async() => { Program program = new Program(); BlockChainStatus chainStatus = await program.GetChainStatus(); if (chainStatus == null) { app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain"); return; } ApiResponse response = await UtxoApi.GetTxOutSetInfo(); if (!response.HasError) { TxOutSet set = response.GetResult <TxOutSet>(); command.Out.WriteLine($"wallet balance is :{set.Total_amount}"); } }); }); app.Command("transaction", command => { command.Description = "view recent transaction record(default 5 content)"; CommandArgument recordArgument = command.Argument("[count]", "record content"); command.OnExecute(async() => { if (recordArgument != null && !string.IsNullOrEmpty(recordArgument.Value)) { if (int.TryParse(recordArgument.Value, out int count)) { Program program = new Program(); BlockChainStatus chainStatus = await program.GetChainStatus(); if (chainStatus == null) { app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain"); return; } ApiResponse response = await TransactionApi.ListTransactions("*", count); if (!response.HasError) { List <Payment> result = response.GetResult <List <Payment> >(); if (result != null && result.Count > 0) { command.Out.WriteLine("recent transaction record blow:"); foreach (var item in result) { //time(需要转换为DataTime), comment, amount string time = new DateTime(1970, 1, 1).AddMilliseconds(item.Time).ToString("yyyy-MM-dd HH:mm:ss"); command.Out.WriteLine($"Time:{time}; Comment:{item.Comment}; Amount:{item.Amount}"); } } else { command.Out.WriteLine("no recent transaction record."); } } } else { command.ShowHelp(); } } else { Program program = new Program(); BlockChainStatus chainStatus = await program.GetChainStatus(); if (chainStatus == null) { app.Out.WriteLine("there is something wrong with the api, you should check the fiiichain"); return; } ApiResponse response = await TransactionApi.ListTransactions(); if (!response.HasError) { List <Payment> result = response.GetResult <List <Payment> >(); if (result != null && result.Count > 0) { command.Out.WriteLine("recent transaction record blow:"); foreach (var item in result) { //time(需要转换为DataTime), comment, amount string time = new DateTime(1970, 1, 1).AddMilliseconds(item.Time).ToString("yyyy-MM-dd HH:mm:ss"); command.Out.WriteLine($"Time:{time}; Comment:{item.Comment}; Amount:{item.Amount}"); } } else { command.Out.WriteLine("no recent transaction record."); } } } }); }); /* * if (args.Length > 1 && args[0].ToLower() == "fiiipay" && IsContainsCommand(args[1])) * { * List<string> list = new List<string>(args); * list.RemoveAt(0); * app.Execute(list.ToArray()); * } */ if (args != null && args.Length > 0 && IsContainsCommand(args[0])) { app.Execute(args); } else { app.Execute(new[] { "-?" }); } }
private Servers GetServerMonitorData_V2(Servers server, DelegateServers account) { string name = server.serverName; string error = ""; server.tailLog = string.Empty; server.error = string.Empty; var client = bll.GetConection(server);//new SshClient(server.serverIP, server.userName, server.userPassword); try { bool isLiskRunning = bll.VerifyIfLiskIsRunning_V2(server, out error, client); decimal missedBlockPrevous = account.account.missedblocks; Servers serverPreviousData = (Servers)server.Clone(); string url = "http://" + server.serverIP + ":" + server.serverPort; BlockChainStatus status = bll.GetBlockChainStatusSSH_V2(server, out error, client); server.error += error; if (status.success && isLiskRunning) { server.blockChainHeight = status.height; server.blockDiff = status.blocks; server.isChainSyncing = status.syncing; server.broadhash = status.broadhash; server.consensus = string.IsNullOrEmpty(status.consensus) ? 0 : Convert.ToInt16(status.consensus); // server.BroadhashConsensus100=status if (server.isChainSyncing) { server.isChainSynced = false; server.isRebuilding = true; //server.lastRebuild = DateTime.Now; if (serverPreviousData.isForging) { server.isForging = false; } } else { server.isChainSynced = true; server.isRebuilding = false; } } //GetMaxPeerBlock string erro2 = ""; //server.maxPeerBlock= bll.GetMaxPeerBlock(out erro2,server.serverPort); server.maxPeerBlock = bll.GetMaxPeerBlock_V2(out erro2, server, client); server.error += erro2; //blockdiff server.blockDiff = server.maxPeerBlock - server.blockChainHeight; if (server.blockDiff < 0) { server.blockDiff = server.blockDiff * -1; } if (server.blockDiff > blockDiffToRebuild) { server.isChainSynced = false; if (serverPreviousData.isRebuilding == true && server.isRebuilding == false /*changed because GetBlockChainStatusSSH above has issue*/) { server.isChainSynced = false; server.isRebuilding = true; } } else { server.isChainSynced = true; server.isRebuilding = false; } //latestBlockForged string error3 = ""; if (server.isChainSynced == true && server.isRebuilding == false) { Block block = bll.GetLatestBlockSSH_V2(server, account.account.generatorPublicKey, out error3, client); server.LastBlockMinutsPassedSince = block.minutsPassedSinceLastBlock; server.LastBlockForgedHeight = block.height; // getnextforgers int position = bll.GetForgingPosition(server, account.account.generatorPublicKey, client); server.forgingPositionCurrenSlot = position == -1?-1:position + 1; } else { Block block = new Block(); server.LastBlockMinutsPassedSince = 9999; server.LastBlockForgedHeight = 0; server.forgingPositionCurrenSlot = -1; } server.error += error3; server.tailLog = bll.ReadTailLog_V2(server, client); ////notify END rebuild if (serverPreviousData.isChainSynced == false && serverPreviousData.isRebuilding && server.isRebuilding == false) { string serverResult = bll.GetAccountString(account);//GetServerJsonToNotify(server); if (serverPreviousData.isRebuilding == true && server.isRebuilding == false) { //server.lastRebuild = DateTime.Now.AddMinutes(10); File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\logs\\" + "REBUILD_END_" + server.serverName + "_" + DateTime.Now.Ticks.ToString() + ".txt", "Rebuild End at " + DateTime.Now.ToString() + " \r\n Server Data:" + serverResult); bll.SendEmail("SERVER END REBUILD " + server.serverName + " " + DateTime.Now.ToString(), account.account.email, "SERVER END REBUILD " + server.serverName + " " + DateTime.Now.ToString() + " server data: " + serverResult); } } //notify LastBlockForgedHeight if (server.isForging && server.isChainSynced && numberTickesMade > 1) { if (server.LastBlockLastNofication < DateTime.Now) { if (account.account.rate <= 101 && serverPreviousData.LastBlockForgedHeight < server.LastBlockForgedHeight && server.LastBlockForgedHeight > 0) { //string accountString = JsonConvert.SerializeObject(account); string accountString = bll.GetAccountString(account); string sms = account.account.username + " Rank: " + account.account.rate.ToString() + " Last Block: " + DateTime.Now.ToString() + " - " + server.serverName + " LastBlockForgedHeight:" + server.LastBlockForgedHeight.ToString() + " LastBlockMinutsPassed: " + server.LastBlockMinutsPassedSince + " this notification is sent every 5 hours, see inside account data.!!!"; bll.SendEmail(sms, account.account.email, sms + " Account: " + accountString); } else { if (account.account.rate > 101) { //string accountString = JsonConvert.SerializeObject(account); string accountString = bll.GetAccountString(account); string sms = account.account.username + " Rank: " + account.account.rate.ToString() + " this notification is sent every 5 hours, see inside account data.!!!"; bll.SendEmail(sms, account.account.email, sms + " Account:" + accountString); } } server.LastBlockLastNofication = DateTime.Now.AddHours(5); } } //notify missed block if (missedBlockPrevous < account.account.missedblocks) { string accountString = bll.GetAccountString(account); //JsonConvert.SerializeObject(account); string sms = "Missed Block Notification " + account.account.username + " Rank:" + account.account.rate.ToString() + " " + DateTime.Now.ToString() + " - Server: " + server.serverName + " Missed Blocks:" + account.account.missedblocks; bll.SendEmail(sms, account.account.email, sms + " Account:" + accountString); } } catch { } finally { //client.Disconnect(); //client.Dispose(); } return(server); }