Ejemplo n.º 1
0
        public async override void Start()
        {
            timePass1 = new TimePass(0.1f);
            timePass2 = new TimePass(0.1f);

            pool     = Entity.Root.GetComponentInChild <Pool>();
            httpPool = Entity.Root.GetComponentInChild <HttpPool>();
            httpRpc  = Entity.Root.GetComponentInChild <HttpRpc>();
            pool.transferProcess.rulerRpc = rulerRpc;

            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(RunRegisterPool));
            thread.IsBackground = true;//设置为后台线程
            thread.Priority     = System.Threading.ThreadPriority.Normal;
            thread.Start(this);

            await Task.Delay(3000);

            Run();
        }
        public static string QueryStringSync(string url, HttpMessage request, float timeout = 1)
        {
            string jsonModel = JsonHelper.ToJson(request.map);
            var    timepass  = new TimePass(timeout);

            using (WebClient wc = new WebClient())
            {
                //发送到服务端并获得返回值
                var awaiter = wc.UploadDataTaskAsync(url, System.Text.Encoding.UTF8.GetBytes(jsonModel)).ConfigureAwait(false).GetAwaiter();
                while (!awaiter.IsCompleted)
                {
                    System.Threading.Thread.Sleep(10);
                    if (timepass.IsPassOnce())
                    {
                        return(null);
                    }
                }
                var str = System.Text.Encoding.UTF8.GetString(awaiter.GetResult()); //把服务端返回的信息转成字符串
                return(str);
            }
        }
Ejemplo n.º 3
0
        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);
                }
            }
        }
Ejemplo n.º 4
0
        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}");
                }
            }
        }
Ejemplo n.º 5
0
        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);
                }
            }
        }