public override void Update() { this.TimeNow = (uint)(TimeHelper.ClientNow() - this.StartTime); this.Recv(); foreach (var kv in this.localConnChannels) { kv.Value.Update(); } while (this.removedChannels.Count > 0) { long id = this.removedChannels.Dequeue(); KChannel channel; if (!this.localConnChannels.TryGetValue(id, out channel)) { continue; } this.localConnChannels.Remove(id); channel.Dispose(); } if (CheckHearBeat && timeHearBeat.IsPassSet()) { foreach (KChannel channel in localConnChannels.Values) { if (channel.CheckHearBeat()) { channel.OnError(ErrorCode.ERR_KcpChannelTimeout); Remove(channel.Id); } } } }
public void RunRegisterPool(object This) { System.Threading.Thread.Sleep(1000); try { RegisterPool(); } catch (Exception) { } while (true) { System.Threading.Thread.Sleep(1000); try { if (timepassRegister.IsPassSet()) { RegisterPool(); } if (timepassGetBlock.IsPassSet()) { GetMcBlock(height - 3); } } catch (Exception) { } } }
// 获取最新高度MC块 public Block GetLastMcBlock() { var levelDBStore = Entity.Root.GetComponent <LevelDBStore>(); // 取最新高度 long.TryParse(levelDBStore.Get("UndoHeight"), out long transferHeight); var chain1 = BlockChainHelper.GetBlockChain(transferHeight); var chain2 = chain1.GetMcBlockNext(); while (chain2 != null) { chain1 = chain2; if (chain1.height >= transferHeight + 10) { chain2 = null; } else { chain2 = chain1.GetMcBlockNext(); } } if (DelBlockWithHeightTime.IsPassSet()) { blockMgr.DelBlockWithHeight(consensus, chain1.height); } Block blk1 = chain1.GetMcBlock(); // 2F1 double t_2max = consensus.GetRuleCount(blk1.height + 1); List <Block> blks = blockMgr.GetBlock(blk1.height + 1); blks = BlockChainHelper.GetRuleBlk(consensus, blks, chain1.hash); if (blks.Count >= BlockChainHelper.Get2F1(t_2max)) { chain2 = BlockChainHelper.GetMcBlockNextNotBeLink(chain1); if (chain2 != null) { var blk2 = chain2.GetMcBlock(); double t_1max = consensus.GetRuleCount(blk2.height - 1); if (blk2.linksblk.Count >= BlockChainHelper.Get2F1(t_1max)) { return(blk2); } } } // Auxiliary Address var blkAuxiliary = blks.Find((x) => { return(x.Address == consensus.auxiliaryAddress); }); //if (blkAuxiliary != null && blkAuxiliary.Address == consensus.auxiliaryAddress && blks.Count >= Math.Min(2, consensus.GetRuleCount(blk1.height+1)) ) if (blkAuxiliary != null && blkAuxiliary.Address == consensus.auxiliaryAddress && blks.Count >= Math.Max(2, (BlockChainHelper.Get2F1(t_2max) / 2))) { return(blkAuxiliary); } return(blk1); }
public override void Update() { if (timePass.IsPassSet() && nodesLastTime.Count > 0) { float lastTime = 0; for (int i = 0; i < nodes.Count; i++) { NodeData node = nodes[i]; if (nodesLastTime.TryGetValue(node.nodeId, out lastTime)) { if (TimeHelper.time - lastTime > 30f) { nodes.Remove(node); nodesLastTime.Remove(node.nodeId); i--; Log.Debug($"nodes.Remove {node.nodeId} {nodes.Count}"); } } } } }
public void StartAccept(string uriPrefix) { httpListener = new HttpListener(); httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; httpListener.Prefixes.Add(uriPrefix); httpListener.Start(); httpThread = new Thread(new ThreadStart(delegate { try { while (!timepassKill.IsPassSet()) { HttpListenerContext httpListenerContext = httpListener.GetContext(); Result(httpListenerContext); } } catch (Exception) { } httpThread = null; })); httpThread.Start(); }
public async void Run() { //Entity.Root.GetComponent<LevelDBStore>().Undo(100); await Task.Delay(3000); long.TryParse(levelDBStore.Get("UndoHeight"), out height); Log.Debug($"Rule.Run at height {height}"); Wallet wallet = Wallet.GetWallet(); P2P_NewBlock p2p_NewBlock = new P2P_NewBlock() { networkID = NodeManager.networkIDBase }; Block blk = null; Block preblk = null; TimePass timePass = new TimePass(1); bool bBlkMining = true; if (httpRule == null) { broadcasttime = pooltime * 5 / 15; // 不挖矿就提前广播块 } state = 0xff; while (true) { try { if (state < 0xff) { await Task.Delay(1000); } long time = (nodeManager.GetNodeTime() / 1000) % pooltime; if (blk == null && time < broadcasttime && timePass.IsPassSet()) { preblk = GetLastMcBlock(); if (consensus.IsRule(preblk.height + 1, wallet.GetCurWallet().ToAddress())) { blk = CreateBlock(preblk, ref bBlkMining); if (blk != null && bBlkMining) { diff_max = 0; hashmining = blk.ToHashMining(); httpRule?.SetMinging(blk.height, hashmining, consensus.calculatePower.GetPower()); } } else { long.TryParse(levelDBStore.Get("UndoHeight"), out height); await Task.Delay(1000); } } if (blk != null && httpRule == null) { // 挖矿 if (httpRule == null && bBlkMining) { Mining(blk, hashmining); } } // 广播块 if (blk != null && time >= broadcasttime) { if (bBlkMining) { if (httpRule != null) { Dictionary <string, MinerTask> miners = httpRule.GetMiner(blk.height); if (miners != null) { double diff = miners.Values.Max(t => t.diff); var miner = miners.Values.FirstOrDefault(c => c.diff == diff); if (miner != null && miner.random != null && miner.random.Count > 0) { blk.random = miner.random[miner.random.Count - 1]; } httpRule.SetMinging(blk.height, "", consensus.calculatePower.GetPower()); } } height = blk.height; blk.hash = blk.ToHash(); blk.sign = blk.ToSign(Wallet.GetWallet().GetCurWallet()); blockMgr.AddBlock(blk); } p2p_NewBlock.block = JsonHelper.ToJson(blk); p2p_NewBlock.ipEndPoint = networkInner.ipEndPoint.ToString(); nodeManager.Broadcast(p2p_NewBlock, blk); relayNetwork?.Broadcast(p2p_NewBlock); Log.Debug($"Rule.Broadcast H:{blk.height} Mining:{bBlkMining} hash:{blk.hash} T:{blk.linkstran.Count}"); calculatePower.Insert(blk); hashmining = ""; diff_max = 0; blk = null; } await Task.Delay(10); } catch (Exception) { await Task.Delay(1000); } } }
public MinerView GetMinerViewAbstract(string address) { if (minerViewAbstractTimePass.IsPassSet()) { minerViewAbstractCache.Clear(); } if (minerViewAbstractCache.TryGetValue(address, out MinerView minerViewLast)) { return(minerViewLast); } var minerView = new MinerView(); // pool name var httpPoolRelay = Entity.Root.GetComponent <HttpPoolRelay>(); if (httpPoolRelay != null) { minerView.address = httpPoolRelay.number; } else { minerView.address = "Ruler"; } Dictionary <string, BlockSub> minerTransferCache = null; using (DbSnapshot snapshot = PoolDBStore.GetSnapshot()) { var str = snapshot.Get($"Pool_Cache_MinerReward"); if (!string.IsNullOrEmpty(str)) { minerTransferCache = JsonHelper.FromJson <Dictionary <string, BlockSub> >(str); } } var transfers_cur = minerTransferCache?.Values.FirstOrDefault(c => c.addressOut == address); if (transfers_cur != null) { minerView.amount_cur = transfers_cur.amount; minerView.share = transfers_cur.type; } // 当前总算力 var miners = httpPool.GetMinerRewardMin(out long miningHeight); var minerList = miners?.Values.Where((x) => x.address == address).ToList(); double totalPower = 0L; if (minerList != null) { minerList.Sort((MinerTask a, MinerTask b) => { return(a.number.CompareTo(b.number)); }); for (var ii = 0; ii < minerList.Count; ii++) { var miner = minerList[ii]; if (double.TryParse(miner.power_average, out double power_average)) { totalPower += power_average; } } minerView.totalMiners = minerList.Count; } minerView.totalPower = CalculatePower.GetPowerCompany(totalPower); minerViewAbstractCache.Add(address, minerView); return(minerView); }
public MinerView GetMinerView(string address, long transferIndex, long transferColumn, long minerIndex, long minerColumn) { if (getMinerViewTimePass.IsPassSet()) { getMinerViewCache.Clear(); } if (getMinerViewCache.TryGetValue($"{address}_{transferIndex}_{transferColumn}_{minerIndex}_{minerColumn}", out MinerView minerViewLast)) { return(minerViewLast); } transferColumn = Math.Min(transferColumn, 100); minerColumn = Math.Min(minerColumn, 100); var minerView = new MinerView(); minerView.address = address; Dictionary <string, BlockSub> minerTransferCache = null; using (DbSnapshot snapshot = PoolDBStore.GetSnapshot()) { var str = snapshot.Get($"Pool_Cache_MinerReward"); if (!string.IsNullOrEmpty(str)) { minerTransferCache = JsonHelper.FromJson <Dictionary <string, BlockSub> >(str); } } var transfers_cur = minerTransferCache?.Values.FirstOrDefault(c => c.addressOut == address); if (transfers_cur != null) { minerView.amount_cur = transfers_cur.amount; minerView.share = transfers_cur.type; } // 交易确认 using (DbSnapshot snapshot = PoolDBStore.GetSnapshot()) { int TopIndex = snapshot.Queue.GetTopIndex($"Pool_MT_{address}"); for (int ii = 1; ii <= (int)transferColumn; ii++) { var value = snapshot.Queue.Get($"Pool_MT_{address}", TopIndex - (int)transferIndex - ii); if (!string.IsNullOrEmpty(value)) { var transfer = JsonHelper.FromJson <BlockSub>(value); if (transfer != null) { minerView.transfers.Add(transfer); } } } foreach (var transfer in minerView.transfers) { // 节点使用自己的地址挖矿 if (transfer.addressIn == transfer.addressOut) { transfer.hash = transfer.addressIn; } else { transfer.hash = TransferProcess.GetMinerTansfer(snapshot, transfer.data); } } } var miners = httpPool.GetMinerRewardMin(out long miningHeight); var minerList = miners?.Values.Where((x) => x.address == address).ToList(); double totalPower = 0L; if (minerList != null) { minerList.Sort((MinerTask a, MinerTask b) => { return(a.number.CompareTo(b.number)); }); // 当前页矿机算力 for (var ii = 0; ii < minerColumn; ii++) { if ((minerIndex + ii) >= minerList.Count) { break; } var miner = minerList[(int)minerIndex + ii]; if (string.IsNullOrEmpty(miner.power_cur)) { miner.power_cur = CalculatePower.GetPowerCompany(CalculatePower.Power(miner.diff)); } var minerdata = new MinerViewData(); minerdata.number = miner.number; minerdata.lasttime = miner.time; minerdata.power_cur = miner.power_cur; double.TryParse(miner.power_average, out double power_average); minerdata.power_average = CalculatePower.GetPowerCompany(power_average); minerView.miners.Add(minerdata); } // 当前总算力 for (var ii = 0; ii < minerList.Count; ii++) { var miner = minerList[ii]; if (double.TryParse(miner.power_average, out double power_average)) { totalPower += power_average; } } minerView.totalMiners = minerList.Count; } minerView.totalPower = CalculatePower.GetPowerCompany(totalPower); getMinerViewCache.Add($"{address}_{transferIndex}_{transferColumn}_{minerIndex}_{minerColumn}", minerView); return(minerView); }
public Dictionary <string, BlockSub> MinerReward(bool saveDB = true) { long counted = 0; long minHeight = -1; long maxHeight = -1; using (DbSnapshot snapshot = PoolDBStore.GetSnapshot(0, true)) { string str_Counted = snapshot.Get("Pool_Counted"); long.TryParse(str_Counted, out counted); string str_MR = snapshot.Get($"Pool_MR_{str_Counted}"); MinerRewardDB minerRewardLast = null; if (!string.IsNullOrEmpty(str_MR)) { minerRewardLast = JsonHelper.FromJson <MinerRewardDB>(str_MR); } if (minerRewardLast == null) { if (httpPool.height <= 2) // 还没有获取到最新高度 { return(null); } snapshot.Add("Pool_Counted", "0"); var minerRewardNew = new MinerRewardDB(); minerRewardNew.counted = 0; minerRewardNew.minHeight = httpPool.height; minerRewardNew.maxHeight = httpPool.height; minerRewardNew.time = TimeHelper.time.ToString(); snapshot.Add($"Pool_MR_{0}", JsonHelper.ToJson(minerRewardNew)); snapshot.Commit(); return(null); } minHeight = minerRewardLast.maxHeight; string json = snapshot.Get("Pool_H_Miner"); if (!string.IsNullOrEmpty(json)) { long.TryParse(json, out maxHeight); } } // 超过一天的数据忽略 if (maxHeight - minHeight > 5760) { Log.Warning($"MinerReward maxHeight - minHeight > 5760, {maxHeight} - {minHeight} = {maxHeight - minHeight}"); } // 设置步长 if (maxHeight - minHeight >= RewardInterval) { maxHeight = minHeight + RewardInterval; runSleep = saveDB ? 10 : runSleep; // 加快处理速度 } // 缓存=========================================================================== Dictionary <string, BlockSub> minerTransferCache = null; if (MinerReward_TimePass.IsPassSet()) { minerTransferCache = MinerReward(false); if (minerTransferCache != null) { using (DbSnapshot snapshot = PoolDBStore.GetSnapshot(0, true)) { snapshot.Add($"Pool_Cache_MinerReward", JsonHelper.ToJson(minerTransferCache)); snapshot.Commit(); } } } // =============================================================================== if (maxHeight - minHeight < RewardInterval && saveDB) { runSleep = 7500; return(null); } Dictionary <string, BlockSub> minerTransfer = null; if (style == "PPLNS") { minerTransfer = minerTransferCache ?? GetMinerReward_PPLNS(minHeight, maxHeight); } if (style == "SOLO") { minerTransfer = minerTransferCache ?? GetMinerReward_SOLO(minHeight, maxHeight); } if (saveDB) { foreach (var it in minerTransfer) { transferProcess.AddTransferHandle(it.Value.addressIn, it.Value.addressOut, it.Value.amount, it.Value.data); } using (DbSnapshot snapshot = PoolDBStore.GetSnapshot(0, true)) { counted += 1; snapshot.Add("Pool_Counted", counted.ToString()); var minerRewardNew = new MinerRewardDB(); minerRewardNew.counted = counted; minerRewardNew.minHeight = minHeight; minerRewardNew.maxHeight = maxHeight; minerRewardNew.time = DateTime.Now.Ticks.ToString(); snapshot.Add($"Pool_MR_{counted}", JsonHelper.ToJson(minerRewardNew)); // Pool_MT var depend = new DateTime(DateTime.Now.Ticks).ToString("yyyy-MM-dd HH:mm:ss"); foreach (var it in minerTransfer) { it.Value.depend = depend; snapshot.Queue.Push($"Pool_MT_{it.Value.addressOut}", JsonHelper.ToJson(it.Value)); } snapshot.Commit(); } } return(minerTransfer); }
public async void Run() { Program.DisbleQuickEditMode(); Console.Clear(); Console.CursorVisible = false; Console.Title = $" address:{address} number:{number} poolUrl:{poolUrl}"; await Task.Delay(1000); //创建后台工作线程 for (int ii = 0; ii < 16; ii++) { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Mining)); thread.IsBackground = true;//设置为后台线程 thread.Start(this); } HttpMessage quest = new HttpMessage(); quest.map = new Dictionary <string, string>(); while (true) { try { if (timePass.IsPassSet()) { string hash = CryptoHelper.Sha256(hashmining + random); Log.Debug($"\n height:{height}, taskid:{taskid}, random:{random}, diff:{diff_max}, power:{calculatePower.GetPower()} hash:{hash}"); } quest.map.Clear(); quest.map.Add("cmd", "submit"); quest.map.Add("height", height.ToString()); quest.map.Add("address", address); quest.map.Add("number", number); quest.map.Add("random", random); quest.map.Add("taskid", taskid); HttpMessage result = await ComponentNetworkHttp.Query(poolUrl, quest); if (result.map != null) { if (result.map.ContainsKey("taskID")) { long.TryParse(result.map["height"], out long tempheight); taskid = result.map["taskID"]; string temphash = result.map["hashmining"]; if (temphash == null || temphash == "" || temphash != hashmining) { if (diff_max != 0) { calculatePower.Insert(diff_max); } diff_max = 0; hashmining = temphash; height = tempheight; random = ""; } } } } catch (Exception e) { Log.Error(e); } await Task.Delay(1000); } }
public async void Run() { Program.DisbleQuickEditMode(); Console.Clear(); Console.CursorVisible = false; Console.Title = $" address:{address},thread:{thread}, number:{number}, poolUrl:{poolUrl}"; Log.Info($"start mining..."); await Task.Delay(1000); //创建后台工作线程 for (int ii = 0; ii < thread; ii++) { System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Mining)); thread.IsBackground = true;//设置为后台线程 thread.Start(this); } HttpMessage quest = new HttpMessage(); quest.map = new Dictionary <string, string>(); while (true) { try { if (timePassInfo.IsPassSet()) { string hash = CryptoHelper.Sha256(hashmining + random); Log.Info($"\n height:{height}, taskid:{taskid}, random:{random}, diff:{diff_max}, power:{calculatePower.GetPower()} hash:{hash}"); } quest.map.Clear(); quest.map.Add("cmd", "submit"); quest.map.Add("height", height.ToString()); quest.map.Add("address", address); quest.map.Add("number", number); quest.map.Add("random", random); quest.map.Add("taskid", taskid); quest.map.Add("average", calculatePower.GetPowerDouble().ToString()); HttpMessage result = null; try { result = await ComponentNetworkHttp.Query($"http://{poolUrl}/mining", quest); } catch (Exception) { if (timePassDebug.IsPassSet()) { Log.Warning($"\n Unable to open the network connection http://{poolUrl}/mining"); } } if (result != null && result.map != null) { if (result.map.ContainsKey("taskid")) { if (result.map.ContainsKey("number")) { number = result.map["number"]; Console.Title = $" address:{address},thread:{thread}, number:{number}, poolUrl:{poolUrl}"; } long.TryParse(result.map["height"], out long tempheight); taskid = result.map["taskid"]; string temphash = result.map["hashmining"]; if (temphash == null || temphash == "" || temphash != hashmining) { if (diff_max != 0) { calculatePower.Insert(diff_max); } diff_max = 0; hashmining = temphash; height = tempheight; random = ""; result.map.TryGetValue("power", out poolPower); changeCallback?.Invoke(); } } } } catch (Exception e) { Log.Error(e); } await Task.Delay(intervalTime); } }
public async void Run() { SetTitle($" address:{address},thread:{thread}, number:{number}, poolUrl:{poolUrl}, version:{version}"); Log.Info($"start mining..."); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; //创建后台工作线程 ThreadDataList = new ThreadData[thread]; for (int ii = 0; ii < thread; ii++) { ThreadDataList[ii] = new ThreadData(); ThreadDataList[ii].miner = this; ThreadDataList[ii].index = ii; ThreadDataList[ii].diff_max = 0; ThreadDataList[ii].random = ""; ThreadDataList[ii].hashmining = ""; System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Mining)); thread.IsBackground = true;//设置为后台线程 thread.Priority = System.Threading.ThreadPriority.Normal; thread.Start(ThreadDataList[ii]); } HttpMessage quest = new HttpMessage(); quest.map = new Dictionary <string, string>(); while (true) { try { if (timePassInfo.IsPassSet()) { Get_Random_diff_max(); string hash = BlockDag.ToHash(height, hashmining_last, random); var sharePer = Math.Round(effectiveShare * 100 / submitCount, 2); var power = CalculatePower.GetPowerCompany(calculatePower.GetPowerDouble()); Log.Info($"\n height:{height}, taskid:{taskid},random:{random}, diff:{diff_max_last}, share:{sharePer}%, power:{power} hash:{hash}"); } long time = (GetNodeTime() / 1000) % pooltime; if (string.IsNullOrEmpty(hashmining) && time >= 1 && time < broadcasttime && timePass1.IsPassSet()) { Get_Random_diff_max(); await Submit(quest); //Log.Info("Task New"); } if (!string.IsNullOrEmpty(hashmining) && time > broadcasttime - 3 && time <= broadcasttime && timePass2.IsPassSet()) { Get_Random_diff_max(); if (diff_max > diff_max_lastSubmit) { diff_max_last = diff_max; diff_max_lastSubmit = diff_max; await Submit(quest); //Log.Info($"Task Submit {height}"); } } if (!string.IsNullOrEmpty(hashmining) && time > broadcasttime) { hashmining = null; changeCallback?.Invoke(); } } catch (Exception) { await Task.Delay(15000); } await Task.Delay(10); } }
public async Task Submit(HttpMessage quest) { quest.map.Clear(); quest.map.Add("cmd", "submit"); quest.map.Add("version", version); quest.map.Add("height", height.ToString()); quest.map.Add("address", address); quest.map.Add("number", number); quest.map.Add("random", random); quest.map.Add("taskid", taskid); quest.map.Add("average", calculatePower.GetPowerDouble().ToString()); HttpMessage result = null; try { result = await ComponentNetworkHttp.Query($"http://{poolUrl}/mining", quest); } catch (Exception) { if (timePassDebug.IsPassSet()) { Log.Warning($"\n Unable to open the network connection http://{poolUrl}/mining"); StopMining(); await Task.Delay(15000); } } if (result != null && result.map != null) { if (result.map.ContainsKey("tips")) { Log.Warning($"{result.map["tips"]}"); await Task.Delay(5000); } if (result.map["report"] == "error") { Log.Warning($"{result.map["tips"]}"); await Task.Delay(5000); } if (result.map.ContainsKey("minerLimit")) { if (timePassDebug.IsPassSet()) { Log.Warning($"\n http://{poolUrl}/mining is full"); StopMining(); await Task.Delay(15000); } } else if (result.map.ContainsKey("taskid")) { if (result.map.ContainsKey("number")) { number = result.map["number"]; SetTitle($" address:{address},thread:{thread}, number:{number}, poolUrl:{poolUrl}, version:{version}"); } long.TryParse(result.map["height"], out long tempheight); taskid = result.map["taskid"]; string temphash = result.map["hashmining"]; if (temphash == null || temphash == "" || temphash != hashmining) { if (result.map.TryGetValue("power", out string smypower) && double.TryParse(smypower, out double dmypower)) { submitCount++; calculatePower.InsertPower(dmypower); if (dmypower != 0) { effectiveShare++; } else { //calculatePower.Clear(); } } hashmining = temphash; hashmining_last = temphash; height = tempheight; diff_max = 0; diff_max_lastSubmit = 0; random = ""; for (int ii = 0; ii < thread; ii++) { lock (ThreadDataList[ii]) { ThreadDataList[ii].diff_max = 0; ThreadDataList[ii].random = ""; ThreadDataList[ii].hashmining = hashmining; } } if (result.map.ContainsKey("nodeTime")) { long.TryParse(result.map["nodeTime"], out nodeTimeOffset); } result.map.TryGetValue("poolPower", out poolPower); changeCallback?.Invoke(); } } } }
public void ThreadRun(object data) { System.Threading.Thread.Sleep(1000); // check url rulerRpc = rulerRpc ?? Entity.Root.Find("SmartxRpc")?.GetComponent <SmartxRpc>()?.GetIPEndPoint(); if (httpPoolRelay != null && GetHeight(rulerRpc, 5) == 0) { Log.Error($"rulerRpc: {rulerRpc} can't connect"); System.Diagnostics.Process.GetCurrentProcess().Kill(); return; } LoadTransferFromDB(); List <TransferHandle> transfersDel = new List <TransferHandle>(); Dictionary <string, Account> accounts = new Dictionary <string, Account>(); var timePassInfo = new TimePass(15 * 6); while (true) { System.Threading.Thread.Sleep(1000); // Query success try { lock (this) { if (runAction != null) { runAction?.Invoke(); runAction = null; SaveTransferToDB(); } } if (!timePassInfo.IsPassSet()) { continue; } transfersDel.Clear(); for (int ii = 0; ii < transfers.Count; ii++) { if (transfers[ii].sendCount <= 5) { if (string.IsNullOrEmpty(transfers[ii].unique)) { transfersDel.Add(transfers[ii]); continue; } var transfer = GetUniqueTransfer(rulerRpc, transfers[ii].unique); if (transfer != null) { if (transfer.data == transfers[ii].unique && transfer.height != 0) { transfers[ii].hash = transfer.hash; transfersDel.Add(transfers[ii]); } } } else { File.AppendAllText("./TransferBad.csv", JsonHelper.ToJson(transfers[ii]) + "\n", Encoding.UTF8); transfersDel.Add(transfers[ii]); } } using (DbSnapshot snapshot = Entity.Root.GetComponent <Pool>().PoolDBStore.GetSnapshot()) { bool remove = transfersDel.Count != 0; // Successfully deleted from table foreach (var it in transfersDel) { if (!string.IsNullOrEmpty(it.unique) && !string.IsNullOrEmpty(it.hash)) { snapshot.Add($"unique_{it.unique}", it.hash); // Add to transaction cross reference table } transfers.Remove(it); } if (remove) { snapshot.Commit(); } } accounts.Clear(); long curHeight = GetHeight(rulerRpc); if (curHeight == 0) { Log.Warning($"rulerRpc: {rulerRpc} can't connect"); continue; } // Start a new deal bool bSaveDb = false; for (int ii = transfers.Count - 1; ii >= 0; ii--) { if (transfers[ii].lastHeight < curHeight - 18 && transfers[ii].sendCount <= 5) { transfers[ii].lastHeight = curHeight; transfers[ii].sendCount++; if (BigHelper.Less(transfers[ii].amount, "0", true)) { transfers.RemoveAt(ii); continue; } Account account = null; if (!accounts.TryGetValue(transfers[ii].addressIn, out account)) { account = GetAccount(rulerRpc, transfers[ii].addressIn); if (account == null) { continue; } accounts.Add(transfers[ii].addressIn, account); } BlockSub transfer = new BlockSub(); transfer.addressIn = transfers[ii].addressIn; transfer.addressOut = transfers[ii].addressOut; transfer.amount = transfers[ii].amount; transfer.type = "transfer"; transfer.nonce = ++account.nonce; transfer.timestamp = TimeHelper.Now(); transfer.data = transfers[ii].unique; transfer.extend = new List <string>(); //transfer.extend.Add($"deadline:{curHeight + 16}"); transfer.extend.Add($"unique"); transfer.hash = transfer.ToHash(); transfer.sign = transfer.ToSign(Wallet.GetWallet().GetCurWallet()); //int rel = Entity.Root.GetComponent<Rule>().AddTransfer(transfer, false); int rel = SendTransfer(rulerRpc, transfer); if (rel == -1) { transfers[ii].sendCount--; continue; } if (rel != 1) { File.AppendAllText("./TransferBad.csv", JsonHelper.ToJson(transfers[ii]) + "\n", Encoding.UTF8); Log.Error($"TransferProcess: aAddTransfer Error! {rel}"); transfers.RemoveAt(ii); } bSaveDb = true; } } if (bSaveDb) { SaveTransferToDB(); } } catch (Exception) { Log.Warning($"TransferProcess throw Exception: {rulerRpc}"); } } }
public async void Run() { //Entity.Root.GetComponent<LevelDBStore>().Undo(100); await Task.Delay(3000); long.TryParse(levelDBStore.Get("UndoHeight"), out height); Log.Debug($"Rule.Run at height {height}"); Wallet wallet = Wallet.GetWallet(); P2P_NewBlock p2p_NewBlock = new P2P_NewBlock(); Block blk = null; Block preblk = null; TimePass timePass = new TimePass(1); var httpRule = Entity.Root.GetComponent <HttpPool>(); state = 0xff; while (true) { try { if (state < 0xff) { await Task.Delay(1000); } long time = (nodeManager.GetNodeTime() / 1000) % pooltime; if (blk == null && time < broadcasttime && timePass.IsPassSet()) { // 找到最新的Mc块 preblk = GetLastMcBlock(); // 是否在裁决节点列表中 if (consensus.IsRule(preblk.height + 1, wallet.GetCurWallet().ToAddress())) { // 生成主块 blk = CreateBlock(preblk); diff_max = 0; hashmining = blk.ToHashMining(); httpRule?.SetMinging(blk.height, hashmining, consensus.calculatePower.GetPower()); } else { long.TryParse(levelDBStore.Get("UndoHeight"), out height); await Task.Delay(1000); } } if (blk != null && httpRule == null) { // 挖矿 这里是提交算力 by sxh Mining(blk, hashmining); } // 广播块 if (blk != null && time >= broadcasttime) { if (httpRule != null) { Dictionary <string, MinerTask> miners = httpRule.GetMiner(blk.height); if (miners != null) { double diff = miners.Values.Max(t => t.diff); var miner = miners.Values.First(c => c.diff == diff); blk.random = miner.random; httpRule?.SetMinging(blk.height, "", consensus.calculatePower.GetPower()); } } height = blk.height; blk.hash = blk.ToHash(); blk.sign = blk.ToSign(Wallet.GetWallet().GetCurWallet()); blockMgr.AddBlock(blk); p2p_NewBlock.block = JsonHelper.ToJson(blk); p2p_NewBlock.ipEndPoint = networkInner.ipEndPoint.ToString(); nodeManager.Broadcast(p2p_NewBlock); diff_max = 0; Log.Debug($"Rule.Broadcast {blk.height} {blk.hash}"); calculatePower.Insert(blk); blk = null; hashmining = ""; } await Task.Delay(10); } catch (Exception) { await Task.Delay(1000); } } }